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,975
25.01.2021 12:16:00
28,800
3d9f88894e50b747bb123ea745f16d026550f83e
Adjust benchtime for failing redis benchmarks.
[ { "change_type": "MODIFY", "old_path": ".buildkite/pipeline.yaml", "new_path": ".buildkite/pipeline.yaml", "diff": "@@ -200,7 +200,7 @@ steps:\ncommand: make benchmark-platforms BENCHMARKS_SUITE=node BENCHMARKS_TARGETS=test/benchmarks/network:node_test\n- <<: *benchmarks\nlabel: \":redis: Redis benchmarks\"\n- command: make benchmark-platforms BENCHMARKS_SUITE=redis BENCHMARKS_TARGETS=test/benchmarks/database:redis_test\n+ command: make benchmark-platforms BENCHMARKS_SUITE=redis BENCHMARKS_TARGETS=test/benchmarks/database:redis_test BENCHMARKS_OPTIONS=-test.benchtime=15s\n- <<: *benchmarks\nlabel: \":ruby: Ruby benchmarks\"\ncommand: make benchmark-platforms BENCHMARKS_SUITE=ruby BENCHMARKS_TARGETS=test/benchmarks/network:ruby_test\n" } ]
Go
Apache License 2.0
google/gvisor
Adjust benchtime for failing redis benchmarks. PiperOrigin-RevId: 353702265
260,003
25.01.2021 16:26:10
28,800
b4665aef8717d00f2f3320616ae4ef0914f9a1b4
fdbased: Dedup code related to iovec reading
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/BUILD", "new_path": "pkg/tcpip/link/fdbased/BUILD", "diff": "@@ -35,7 +35,6 @@ go_test(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n- \"//pkg/tcpip/link/rawfile\",\n\"//pkg/tcpip/stack\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/endpoint_test.go", "new_path": "pkg/tcpip/link/fdbased/endpoint_test.go", "diff": "@@ -30,7 +30,6 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n- \"gvisor.dev/gvisor/pkg/tcpip/link/rawfile\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -465,67 +464,85 @@ var capLengthTestCases = []struct {\nconfig: []int{1, 2, 3},\nn: 3,\nwantUsed: 2,\n- wantLengths: []int{1, 2, 3},\n+ wantLengths: []int{1, 2},\n},\n}\n-func TestReadVDispatcherCapLength(t *testing.T) {\n+func TestIovecBuffer(t *testing.T) {\nfor _, c := range capLengthTestCases {\n- // fd does not matter for this test.\n- d := readVDispatcher{fd: -1, e: &endpoint{}}\n- d.views = make([]buffer.View, len(c.config))\n- d.iovecs = make([]syscall.Iovec, len(c.config))\n- d.allocateViews(c.config)\n+ t.Run(c.comment, func(t *testing.T) {\n+ b := newIovecBuffer(c.config, false /* skipsVnetHdr */)\n- used := d.capViews(c.n, c.config)\n- if used != c.wantUsed {\n- t.Errorf(\"Test %q failed when calling capViews(%d, %v). Got %d. Want %d\", c.comment, c.n, c.config, used, c.wantUsed)\n+ // Test initial allocation.\n+ iovecs := b.nextIovecs()\n+ if got, want := len(iovecs), len(c.config); got != want {\n+ t.Fatalf(\"len(iovecs) = %d, want %d\", got, want)\n}\n- lengths := make([]int, len(d.views))\n- for i, v := range d.views {\n- lengths[i] = len(v)\n+\n+ // Make a copy as iovecs points to internal slice. We will need this state\n+ // later.\n+ oldIovecs := append([]syscall.Iovec(nil), iovecs...)\n+\n+ // Test the views that get pulled.\n+ vv := b.pullViews(c.n)\n+ var lengths []int\n+ for _, v := range vv.Views() {\n+ lengths = append(lengths, len(v))\n}\nif !reflect.DeepEqual(lengths, c.wantLengths) {\n- t.Errorf(\"Test %q failed when calling capViews(%d, %v). Got %v. Want %v\", c.comment, c.n, c.config, lengths, c.wantLengths)\n+ t.Errorf(\"Pulled view lengths = %v, want %v\", lengths, c.wantLengths)\n}\n+\n+ // Test that new views get reallocated.\n+ for i, newIov := range b.nextIovecs() {\n+ if i < c.wantUsed {\n+ if newIov.Base == oldIovecs[i].Base {\n+ t.Errorf(\"b.views[%d] should have been reallocated\", i)\n}\n+ } else {\n+ if newIov.Base != oldIovecs[i].Base {\n+ t.Errorf(\"b.views[%d] should not have been reallocated\", i)\n}\n-\n-func TestRecvMMsgDispatcherCapLength(t *testing.T) {\n- for _, c := range capLengthTestCases {\n- d := recvMMsgDispatcher{\n- fd: -1, // fd does not matter for this test.\n- e: &endpoint{},\n- views: make([][]buffer.View, 1),\n- iovecs: make([][]syscall.Iovec, 1),\n- msgHdrs: make([]rawfile.MMsgHdr, 1),\n}\n-\n- for i := range d.views {\n- d.views[i] = make([]buffer.View, len(c.config))\n}\n- for i := range d.iovecs {\n- d.iovecs[i] = make([]syscall.Iovec, len(c.config))\n+ })\n}\n- for k, msgHdr := range d.msgHdrs {\n- msgHdr.Msg.Iov = &d.iovecs[k][0]\n- msgHdr.Msg.Iovlen = uint64(len(c.config))\n}\n- d.allocateViews(c.config)\n-\n- used := d.capViews(0, c.n, c.config)\n- if used != c.wantUsed {\n- t.Errorf(\"Test %q failed when calling capViews(%d, %v). Got %d. Want %d\", c.comment, c.n, c.config, used, c.wantUsed)\n- }\n- lengths := make([]int, len(d.views[0]))\n- for i, v := range d.views[0] {\n- lengths[i] = len(v)\n+func TestIovecBufferSkipVnetHdr(t *testing.T) {\n+ for _, test := range []struct {\n+ desc string\n+ readN int\n+ wantLen int\n+ }{\n+ {\n+ desc: \"nothing read\",\n+ readN: 0,\n+ wantLen: 0,\n+ },\n+ {\n+ desc: \"smaller than vnet header\",\n+ readN: virtioNetHdrSize - 1,\n+ wantLen: 0,\n+ },\n+ {\n+ desc: \"header skipped\",\n+ readN: virtioNetHdrSize + 100,\n+ wantLen: 100,\n+ },\n+ } {\n+ t.Run(test.desc, func(t *testing.T) {\n+ b := newIovecBuffer([]int{10, 20, 50, 50}, true)\n+ // Pretend a read happend.\n+ b.nextIovecs()\n+ vv := b.pullViews(test.readN)\n+ if got, want := vv.Size(), test.wantLen; got != want {\n+ t.Errorf(\"b.pullView(%d).Size() = %d; want %d\", test.readN, got, want)\n}\n- if !reflect.DeepEqual(lengths, c.wantLengths) {\n- t.Errorf(\"Test %q failed when calling capViews(%d, %v). Got %v. Want %v\", c.comment, c.n, c.config, lengths, c.wantLengths)\n+ if got, want := len(vv.ToOwnedView()), test.wantLen; got != want {\n+ t.Errorf(\"b.pullView(%d).ToOwnedView() has length %d; want %d\", test.readN, got, want)\n}\n-\n+ })\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go", "new_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go", "diff": "@@ -29,92 +29,124 @@ import (\n// BufConfig defines the shape of the vectorised view used to read packets from the NIC.\nvar BufConfig = []int{128, 256, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}\n-// readVDispatcher uses readv() system call to read inbound packets and\n-// dispatches them.\n-type readVDispatcher struct {\n- // fd is the file descriptor used to send and receive packets.\n- fd int\n-\n- // e is the endpoint this dispatcher is attached to.\n- e *endpoint\n-\n+type iovecBuffer struct {\n// views are the actual buffers that hold the packet contents.\nviews []buffer.View\n// iovecs are initialized with base pointers/len of the corresponding\n- // entries in the views defined above, except when GSO is enabled then\n- // the first iovec points to a buffer for the vnet header which is\n- // stripped before the views are passed up the stack for further\n+ // entries in the views defined above, except when GSO is enabled\n+ // (skipsVnetHdr) then the first iovec points to a buffer for the vnet header\n+ // which is stripped before the views are passed up the stack for further\n// processing.\niovecs []syscall.Iovec\n+\n+ // sizes is an array of buffer sizes for the underlying views. sizes is\n+ // immutable.\n+ sizes []int\n+\n+ // skipsVnetHdr is true if virtioNetHdr is to skipped.\n+ skipsVnetHdr bool\n}\n-func newReadVDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\n- d := &readVDispatcher{fd: fd, e: e}\n- d.views = make([]buffer.View, len(BufConfig))\n- iovLen := len(BufConfig)\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n- iovLen++\n+func newIovecBuffer(sizes []int, skipsVnetHdr bool) *iovecBuffer {\n+ b := &iovecBuffer{\n+ views: make([]buffer.View, len(sizes)),\n+ sizes: sizes,\n+ skipsVnetHdr: skipsVnetHdr,\n}\n- d.iovecs = make([]syscall.Iovec, iovLen)\n- return d, nil\n+ niov := len(b.views)\n+ if b.skipsVnetHdr {\n+ niov++\n+ }\n+ b.iovecs = make([]syscall.Iovec, niov)\n+ return b\n}\n-func (d *readVDispatcher) allocateViews(bufConfig []int) {\n- var vnetHdr [virtioNetHdrSize]byte\n+func (b *iovecBuffer) nextIovecs() []syscall.Iovec {\nvnetHdrOff := 0\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n+ if b.skipsVnetHdr {\n+ var vnetHdr [virtioNetHdrSize]byte\n// The kernel adds virtioNetHdr before each packet, but\n// we don't use it, so so we allocate a buffer for it,\n// add it in iovecs but don't add it in a view.\n- d.iovecs[0] = syscall.Iovec{\n+ b.iovecs[0] = syscall.Iovec{\nBase: &vnetHdr[0],\nLen: uint64(virtioNetHdrSize),\n}\nvnetHdrOff++\n}\n- for i := 0; i < len(bufConfig); i++ {\n- if d.views[i] != nil {\n+ for i := range b.views {\n+ if b.views[i] != nil {\nbreak\n}\n- b := buffer.NewView(bufConfig[i])\n- d.views[i] = b\n- d.iovecs[i+vnetHdrOff] = syscall.Iovec{\n- Base: &b[0],\n- Len: uint64(len(b)),\n+ v := buffer.NewView(b.sizes[i])\n+ b.views[i] = v\n+ b.iovecs[i+vnetHdrOff] = syscall.Iovec{\n+ Base: &v[0],\n+ Len: uint64(len(v)),\n}\n}\n+ return b.iovecs\n}\n-func (d *readVDispatcher) capViews(n int, buffers []int) int {\n+func (b *iovecBuffer) pullViews(n int) buffer.VectorisedView {\n+ var views []buffer.View\nc := 0\n- for i, s := range buffers {\n- c += s\n+ if b.skipsVnetHdr {\n+ c += virtioNetHdrSize\nif c >= n {\n- d.views[i].CapLength(s - (c - n))\n- return i + 1\n+ // Nothing in the packet.\n+ return buffer.NewVectorisedView(0, nil)\n+ }\n+ }\n+ for i, v := range b.views {\n+ c += len(v)\n+ if c >= n {\n+ b.views[i].CapLength(len(v) - (c - n))\n+ views = append([]buffer.View(nil), b.views[:i+1]...)\n+ break\n+ }\n+ }\n+ // Remove the first len(views) used views from the state.\n+ for i := range views {\n+ b.views[i] = nil\n}\n+ if b.skipsVnetHdr {\n+ // Exclude the size of the vnet header.\n+ n -= virtioNetHdrSize\n+ }\n+ return buffer.NewVectorisedView(n, views)\n}\n- return len(buffers)\n+\n+// readVDispatcher uses readv() system call to read inbound packets and\n+// dispatches them.\n+type readVDispatcher struct {\n+ // fd is the file descriptor used to send and receive packets.\n+ fd int\n+\n+ // e is the endpoint this dispatcher is attached to.\n+ e *endpoint\n+\n+ // buf is the iovec buffer that contains the packet contents.\n+ buf *iovecBuffer\n+}\n+\n+func newReadVDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\n+ d := &readVDispatcher{fd: fd, e: e}\n+ skipsVnetHdr := d.e.Capabilities()&stack.CapabilityHardwareGSO != 0\n+ d.buf = newIovecBuffer(BufConfig, skipsVnetHdr)\n+ return d, nil\n}\n// dispatch reads one packet from the file descriptor and dispatches it.\nfunc (d *readVDispatcher) dispatch() (bool, *tcpip.Error) {\n- d.allocateViews(BufConfig)\n-\n- n, err := rawfile.BlockingReadv(d.fd, d.iovecs)\n+ n, err := rawfile.BlockingReadv(d.fd, d.buf.nextIovecs())\nif n == 0 || err != nil {\nreturn false, err\n}\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n- // Skip virtioNetHdr which is added before each packet, it\n- // isn't used and it isn't in a view.\n- n -= virtioNetHdrSize\n- }\n- used := d.capViews(n, BufConfig)\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Data: buffer.NewVectorisedView(n, append([]buffer.View(nil), d.views[:used]...)),\n+ Data: d.buf.pullViews(n),\n})\nvar (\n@@ -133,7 +165,12 @@ func (d *readVDispatcher) dispatch() (bool, *tcpip.Error) {\n} else {\n// We don't get any indication of what the packet is, so try to guess\n// if it's an IPv4 or IPv6 packet.\n- switch header.IPVersion(d.views[0]) {\n+ // IP version information is at the first octet, so pulling up 1 byte.\n+ h, ok := pkt.Data.PullUp(1)\n+ if !ok {\n+ return true, nil\n+ }\n+ switch header.IPVersion(h) {\ncase header.IPv4Version:\np = header.IPv4ProtocolNumber\ncase header.IPv6Version:\n@@ -145,11 +182,6 @@ func (d *readVDispatcher) dispatch() (bool, *tcpip.Error) {\nd.e.dispatcher.DeliverNetworkPacket(remote, local, p, pkt)\n- // Prepare e.views for another packet: release used views.\n- for i := 0; i < used; i++ {\n- d.views[i] = nil\n- }\n-\nreturn true, nil\n}\n@@ -162,15 +194,8 @@ type recvMMsgDispatcher struct {\n// e is the endpoint this dispatcher is attached to.\ne *endpoint\n- // views is an array of array of buffers that contain packet contents.\n- views [][]buffer.View\n-\n- // iovecs is an array of array of iovec records where each iovec base\n- // pointer and length are initialzed to the corresponding view above,\n- // except when GSO is enabled then the first iovec in each array of\n- // iovecs points to a buffer for the vnet header which is stripped\n- // before the views are passed up the stack for further processing.\n- iovecs [][]syscall.Iovec\n+ // bufs is an array of iovec buffers that contain packet contents.\n+ bufs []*iovecBuffer\n// msgHdrs is an array of MMsgHdr objects where each MMsghdr is used to\n// reference an array of iovecs in the iovecs field defined above. This\n@@ -189,72 +214,30 @@ func newRecvMMsgDispatcher(fd int, e *endpoint) (linkDispatcher, error) {\nd := &recvMMsgDispatcher{\nfd: fd,\ne: e,\n+ bufs: make([]*iovecBuffer, MaxMsgsPerRecv),\n+ msgHdrs: make([]rawfile.MMsgHdr, MaxMsgsPerRecv),\n}\n- d.views = make([][]buffer.View, MaxMsgsPerRecv)\n- for i := range d.views {\n- d.views[i] = make([]buffer.View, len(BufConfig))\n- }\n- d.iovecs = make([][]syscall.Iovec, MaxMsgsPerRecv)\n- iovLen := len(BufConfig)\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n- // virtioNetHdr is prepended before each packet.\n- iovLen++\n- }\n- for i := range d.iovecs {\n- d.iovecs[i] = make([]syscall.Iovec, iovLen)\n- }\n- d.msgHdrs = make([]rawfile.MMsgHdr, MaxMsgsPerRecv)\n- for i := range d.msgHdrs {\n- d.msgHdrs[i].Msg.Iov = &d.iovecs[i][0]\n- d.msgHdrs[i].Msg.Iovlen = uint64(iovLen)\n+ skipsVnetHdr := d.e.Capabilities()&stack.CapabilityHardwareGSO != 0\n+ for i := range d.bufs {\n+ d.bufs[i] = newIovecBuffer(BufConfig, skipsVnetHdr)\n}\nreturn d, nil\n}\n-func (d *recvMMsgDispatcher) capViews(k, n int, buffers []int) int {\n- c := 0\n- for i, s := range buffers {\n- c += s\n- if c >= n {\n- d.views[k][i].CapLength(s - (c - n))\n- return i + 1\n- }\n- }\n- return len(buffers)\n-}\n-\n-func (d *recvMMsgDispatcher) allocateViews(bufConfig []int) {\n- for k := 0; k < len(d.views); k++ {\n- var vnetHdr [virtioNetHdrSize]byte\n- vnetHdrOff := 0\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n- // The kernel adds virtioNetHdr before each packet, but\n- // we don't use it, so so we allocate a buffer for it,\n- // add it in iovecs but don't add it in a view.\n- d.iovecs[k][0] = syscall.Iovec{\n- Base: &vnetHdr[0],\n- Len: uint64(virtioNetHdrSize),\n- }\n- vnetHdrOff++\n- }\n- for i := 0; i < len(bufConfig); i++ {\n- if d.views[k][i] != nil {\n- break\n- }\n- b := buffer.NewView(bufConfig[i])\n- d.views[k][i] = b\n- d.iovecs[k][i+vnetHdrOff] = syscall.Iovec{\n- Base: &b[0],\n- Len: uint64(len(b)),\n- }\n- }\n- }\n-}\n-\n// recvMMsgDispatch reads more than one packet at a time from the file\n// descriptor and dispatches it.\nfunc (d *recvMMsgDispatcher) dispatch() (bool, *tcpip.Error) {\n- d.allocateViews(BufConfig)\n+ // Fill message headers.\n+ for k := range d.msgHdrs {\n+ if d.msgHdrs[k].Msg.Iovlen > 0 {\n+ break\n+ }\n+ iovecs := d.bufs[k].nextIovecs()\n+ iovLen := len(iovecs)\n+ d.msgHdrs[k].Len = 0\n+ d.msgHdrs[k].Msg.Iov = &iovecs[0]\n+ d.msgHdrs[k].Msg.Iovlen = uint64(iovLen)\n+ }\nnMsgs, err := rawfile.BlockingRecvMMsg(d.fd, d.msgHdrs)\nif err != nil {\n@@ -263,15 +246,14 @@ func (d *recvMMsgDispatcher) dispatch() (bool, *tcpip.Error) {\n// Process each of received packets.\nfor k := 0; k < nMsgs; k++ {\nn := int(d.msgHdrs[k].Len)\n- if d.e.Capabilities()&stack.CapabilityHardwareGSO != 0 {\n- n -= virtioNetHdrSize\n- }\n- used := d.capViews(k, int(n), BufConfig)\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- Data: buffer.NewVectorisedView(int(n), append([]buffer.View(nil), d.views[k][:used]...)),\n+ Data: d.bufs[k].pullViews(n),\n})\n+ // Mark that this iovec has been processed.\n+ d.msgHdrs[k].Msg.Iovlen = 0\n+\nvar (\np tcpip.NetworkProtocolNumber\nremote, local tcpip.LinkAddress\n@@ -288,26 +270,24 @@ func (d *recvMMsgDispatcher) dispatch() (bool, *tcpip.Error) {\n} else {\n// We don't get any indication of what the packet is, so try to guess\n// if it's an IPv4 or IPv6 packet.\n- switch header.IPVersion(d.views[k][0]) {\n+ // IP version information is at the first octet, so pulling up 1 byte.\n+ h, ok := pkt.Data.PullUp(1)\n+ if !ok {\n+ // Skip this packet.\n+ continue\n+ }\n+ switch header.IPVersion(h) {\ncase header.IPv4Version:\np = header.IPv4ProtocolNumber\ncase header.IPv6Version:\np = header.IPv6ProtocolNumber\ndefault:\n- return true, nil\n+ // Skip this packet.\n+ continue\n}\n}\nd.e.dispatcher.DeliverNetworkPacket(remote, local, p, pkt)\n-\n- // Prepare e.views for another packet: release used views.\n- for i := 0; i < used; i++ {\n- d.views[k][i] = nil\n- }\n- }\n-\n- for k := 0; k < nMsgs; k++ {\n- d.msgHdrs[k].Len = 0\n}\nreturn true, nil\n" } ]
Go
Apache License 2.0
google/gvisor
fdbased: Dedup code related to iovec reading PiperOrigin-RevId: 353755271
259,951
25.01.2021 16:50:14
28,800
39db3b93554ea74611602ad4c20dfa5c08e748f2
Add per endpoint ARP statistics The ARP stat NetworkUnreachable was removed, and was replaced by InterfaceHasNoLocalAddress. No stats are recorded when dealing with an missing endpoint (ErrNotConnected) (because if there is no endpoint, there is no valid per-endpoint stats).
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -193,7 +193,6 @@ var Metrics = tcpip.Stats{\nRequestsReceivedUnknownTargetAddress: mustCreateMetric(\"/netstack/arp/requests_received_unknown_addr\", \"Number of ARP requests received with an unknown target address.\"),\nOutgoingRequestInterfaceHasNoLocalAddressErrors: mustCreateMetric(\"/netstack/arp/outgoing_requests_iface_has_no_addr\", \"Number of failed attempts to send an ARP request with an interface that has no network address.\"),\nOutgoingRequestBadLocalAddressErrors: mustCreateMetric(\"/netstack/arp/outgoing_requests_invalid_local_addr\", \"Number of failed attempts to send an ARP request with a provided local address that is invalid.\"),\n- OutgoingRequestNetworkUnreachableErrors: mustCreateMetric(\"/netstack/arp/outgoing_requests_network_unreachable\", \"Number of failed attempts to send an ARP request with a network unreachable error.\"),\nOutgoingRequestsDropped: mustCreateMetric(\"/netstack/arp/outgoing_requests_dropped\", \"Number of ARP requests which failed to write to a link-layer endpoint.\"),\nOutgoingRequestsSent: mustCreateMetric(\"/netstack/arp/outgoing_requests_sent\", \"Number of ARP requests sent.\"),\nRepliesReceived: mustCreateMetric(\"/netstack/arp/replies_received\", \"Number of ARP replies received.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/BUILD", "new_path": "pkg/tcpip/network/arp/BUILD", "diff": "@@ -4,9 +4,13 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"arp\",\n- srcs = [\"arp.go\"],\n+ srcs = [\n+ \"arp.go\",\n+ \"stats.go\",\n+ ],\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n@@ -33,3 +37,15 @@ go_test(\n\"@com_github_google_go_cmp//cmp/cmpopts:go_default_library\",\n],\n)\n+\n+go_test(\n+ name = \"stats_test\",\n+ size = \"small\",\n+ srcs = [\"stats_test.go\"],\n+ library = \":arp\",\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/network/testutil\",\n+ \"//pkg/tcpip/stack\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp.go", "new_path": "pkg/tcpip/network/arp/arp.go", "diff": "@@ -19,8 +19,10 @@ package arp\nimport (\n\"fmt\"\n+ \"reflect\"\n\"sync/atomic\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -50,6 +52,7 @@ type endpoint struct {\nnic stack.NetworkInterface\nlinkAddrCache stack.LinkAddressCache\nnud stack.NUDHandler\n+ stats sharedStats\n}\nfunc (e *endpoint) Enable() *tcpip.Error {\n@@ -98,7 +101,9 @@ func (e *endpoint) MaxHeaderLength() uint16 {\nreturn e.nic.MaxHeaderLength() + header.ARPSize\n}\n-func (*endpoint) Close() {}\n+func (e *endpoint) Close() {\n+ e.protocol.forgetEndpoint(e.nic.ID())\n+}\nfunc (*endpoint) WritePacket(*stack.Route, *stack.GSO, stack.NetworkHeaderParams, *stack.PacketBuffer) *tcpip.Error {\nreturn tcpip.ErrNotSupported\n@@ -119,27 +124,27 @@ func (*endpoint) WriteHeaderIncludedPacket(*stack.Route, *stack.PacketBuffer) *t\n}\nfunc (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n- stats := e.protocol.stack.Stats().ARP\n- stats.PacketsReceived.Increment()\n+ stats := e.stats.arp\n+ stats.packetsReceived.Increment()\nif !e.isEnabled() {\n- stats.DisabledPacketsReceived.Increment()\n+ stats.disabledPacketsReceived.Increment()\nreturn\n}\nh := header.ARP(pkt.NetworkHeader().View())\nif !h.IsValid() {\n- stats.MalformedPacketsReceived.Increment()\n+ stats.malformedPacketsReceived.Increment()\nreturn\n}\nswitch h.Op() {\ncase header.ARPRequest:\n- stats.RequestsReceived.Increment()\n+ stats.requestsReceived.Increment()\nlocalAddr := tcpip.Address(h.ProtocolAddressTarget())\nif e.protocol.stack.CheckLocalAddress(e.nic.ID(), header.IPv4ProtocolNumber, localAddr) == 0 {\n- stats.RequestsReceivedUnknownTargetAddress.Increment()\n+ stats.requestsReceivedUnknownTargetAddress.Increment()\nreturn // we have no useful answer, ignore the request\n}\n@@ -180,13 +185,13 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Send the packet to the (new) target hardware address on the same\n// hardware on which the request was received.\nif err := e.nic.WritePacketToRemote(tcpip.LinkAddress(origSender), nil /* gso */, ProtocolNumber, respPkt); err != nil {\n- stats.OutgoingRepliesDropped.Increment()\n+ stats.outgoingRepliesDropped.Increment()\n} else {\n- stats.OutgoingRepliesSent.Increment()\n+ stats.outgoingRepliesSent.Increment()\n}\ncase header.ARPReply:\n- stats.RepliesReceived.Increment()\n+ stats.repliesReceived.Increment()\naddr := tcpip.Address(h.ProtocolAddressSender())\nlinkAddr := tcpip.LinkAddress(h.HardwareAddressSender())\n@@ -212,21 +217,23 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Stats implements stack.NetworkEndpoint.\nfunc (e *endpoint) Stats() stack.NetworkEndpointStats {\n- // TODO(gvisor.dev/issues/4963): Record statistics for ARP.\n- return &Stats{}\n+ return &e.stats.localStats\n}\n-var _ stack.NetworkEndpointStats = (*Stats)(nil)\n-\n-// Stats holds ARP statistics.\n-type Stats struct{}\n-\n-// IsNetworkEndpointStats implements stack.NetworkEndpointStats.\n-func (*Stats) IsNetworkEndpointStats() {}\n+var _ stack.NetworkProtocol = (*protocol)(nil)\n+var _ stack.LinkAddressResolver = (*protocol)(nil)\n// protocol implements stack.NetworkProtocol and stack.LinkAddressResolver.\ntype protocol struct {\nstack *stack.Stack\n+\n+ mu struct {\n+ sync.RWMutex\n+\n+ // eps is keyed by NICID to allow protocol methods to retrieve the correct\n+ // endpoint depending on the NIC.\n+ eps map[tcpip.NICID]*endpoint\n+ }\n}\nfunc (p *protocol) Number() tcpip.NetworkProtocolNumber { return ProtocolNumber }\n@@ -244,9 +251,25 @@ func (p *protocol) NewEndpoint(nic stack.NetworkInterface, linkAddrCache stack.L\nlinkAddrCache: linkAddrCache,\nnud: nud,\n}\n+\n+ tcpip.InitStatCounters(reflect.ValueOf(&e.stats.localStats).Elem())\n+\n+ stackStats := p.stack.Stats()\n+ e.stats.arp.init(&e.stats.localStats.ARP, &stackStats.ARP)\n+\n+ p.mu.Lock()\n+ p.mu.eps[nic.ID()] = e\n+ p.mu.Unlock()\n+\nreturn e\n}\n+func (p *protocol) forgetEndpoint(nicID tcpip.NICID) {\n+ p.mu.Lock()\n+ defer p.mu.Unlock()\n+ delete(p.mu.eps, nicID)\n+}\n+\n// LinkAddressProtocol implements stack.LinkAddressResolver.LinkAddressProtocol.\nfunc (*protocol) LinkAddressProtocol() tcpip.NetworkProtocolNumber {\nreturn header.IPv4ProtocolNumber\n@@ -254,28 +277,35 @@ func (*protocol) LinkAddressProtocol() tcpip.NetworkProtocolNumber {\n// LinkAddressRequest implements stack.LinkAddressResolver.LinkAddressRequest.\nfunc (p *protocol) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remoteLinkAddr tcpip.LinkAddress, nic stack.NetworkInterface) *tcpip.Error {\n- stats := p.stack.Stats().ARP\n+ nicID := nic.ID()\n+\n+ p.mu.Lock()\n+ netEP, ok := p.mu.eps[nicID]\n+ p.mu.Unlock()\n+ if !ok {\n+ return tcpip.ErrNotConnected\n+ }\n+\n+ stats := netEP.stats.arp\nif len(remoteLinkAddr) == 0 {\nremoteLinkAddr = header.EthernetBroadcastAddress\n}\n- nicID := nic.ID()\nif len(localAddr) == 0 {\naddr, ok := p.stack.GetMainNICAddress(nicID, header.IPv4ProtocolNumber)\nif !ok {\n- stats.OutgoingRequestInterfaceHasNoLocalAddressErrors.Increment()\nreturn tcpip.ErrUnknownNICID\n}\nif len(addr.Address) == 0 {\n- stats.OutgoingRequestNetworkUnreachableErrors.Increment()\n+ stats.outgoingRequestInterfaceHasNoLocalAddressErrors.Increment()\nreturn tcpip.ErrNetworkUnreachable\n}\nlocalAddr = addr.Address\n} else if p.stack.CheckLocalAddress(nicID, header.IPv4ProtocolNumber, localAddr) == 0 {\n- stats.OutgoingRequestBadLocalAddressErrors.Increment()\n+ stats.outgoingRequestBadLocalAddressErrors.Increment()\nreturn tcpip.ErrBadLocalAddress\n}\n@@ -296,10 +326,10 @@ func (p *protocol) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remot\npanic(fmt.Sprintf(\"copied %d bytes, expected %d bytes\", n, header.IPv4AddressSize))\n}\nif err := nic.WritePacketToRemote(remoteLinkAddr, nil /* gso */, ProtocolNumber, pkt); err != nil {\n- stats.OutgoingRequestsDropped.Increment()\n+ stats.outgoingRequestsDropped.Increment()\nreturn err\n}\n- stats.OutgoingRequestsSent.Increment()\n+ stats.outgoingRequestsSent.Increment()\nreturn nil\n}\n@@ -337,5 +367,11 @@ func (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNu\n// NewProtocol returns an ARP network protocol.\nfunc NewProtocol(s *stack.Stack) stack.NetworkProtocol {\n- return &protocol{stack: s}\n+ return &protocol{\n+ stack: s,\n+ mu: struct {\n+ sync.RWMutex\n+ eps map[tcpip.NICID]*endpoint\n+ }{eps: make(map[tcpip.NICID]*endpoint)},\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp_test.go", "new_path": "pkg/tcpip/network/arp/arp_test.go", "diff": "@@ -589,14 +589,13 @@ func TestLinkAddressRequest(t *testing.T) {\nnicAddr tcpip.Address\nlocalAddr tcpip.Address\nremoteLinkAddr tcpip.LinkAddress\n-\nlinkErr *tcpip.Error\nexpectedErr *tcpip.Error\nexpectedLocalAddr tcpip.Address\nexpectedRemoteLinkAddr tcpip.LinkAddress\nexpectedRequestsSent uint64\nexpectedRequestBadLocalAddressErrors uint64\n- expectedRequestNetworkUnreachableErrors uint64\n+ expectedRequestInterfaceHasNoLocalAddressErrors uint64\nexpectedRequestDroppedErrors uint64\n}{\n{\n@@ -608,7 +607,8 @@ func TestLinkAddressRequest(t *testing.T) {\nexpectedRemoteLinkAddr: remoteLinkAddr,\nexpectedRequestsSent: 1,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Multicast\",\n@@ -619,61 +619,76 @@ func TestLinkAddressRequest(t *testing.T) {\nexpectedRemoteLinkAddr: header.EthernetBroadcastAddress,\nexpectedRequestsSent: 1,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Unicast with unspecified source\",\nnicAddr: stackAddr,\n+ localAddr: \"\",\nremoteLinkAddr: remoteLinkAddr,\nexpectedLocalAddr: stackAddr,\nexpectedRemoteLinkAddr: remoteLinkAddr,\nexpectedRequestsSent: 1,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Multicast with unspecified source\",\nnicAddr: stackAddr,\n+ localAddr: \"\",\nremoteLinkAddr: \"\",\nexpectedLocalAddr: stackAddr,\nexpectedRemoteLinkAddr: header.EthernetBroadcastAddress,\nexpectedRequestsSent: 1,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Unicast with unassigned address\",\n+ nicAddr: stackAddr,\nlocalAddr: testAddr,\nremoteLinkAddr: remoteLinkAddr,\nexpectedErr: tcpip.ErrBadLocalAddress,\nexpectedRequestsSent: 0,\nexpectedRequestBadLocalAddressErrors: 1,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Multicast with unassigned address\",\n+ nicAddr: stackAddr,\nlocalAddr: testAddr,\nremoteLinkAddr: \"\",\nexpectedErr: tcpip.ErrBadLocalAddress,\nexpectedRequestsSent: 0,\nexpectedRequestBadLocalAddressErrors: 1,\n- expectedRequestNetworkUnreachableErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Unicast with no local address available\",\n+ nicAddr: \"\",\n+ localAddr: \"\",\nremoteLinkAddr: remoteLinkAddr,\nexpectedErr: tcpip.ErrNetworkUnreachable,\nexpectedRequestsSent: 0,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 1,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 1,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Multicast with no local address available\",\n+ nicAddr: \"\",\n+ localAddr: \"\",\nremoteLinkAddr: \"\",\nexpectedErr: tcpip.ErrNetworkUnreachable,\nexpectedRequestsSent: 0,\nexpectedRequestBadLocalAddressErrors: 0,\n- expectedRequestNetworkUnreachableErrors: 1,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 1,\n+ expectedRequestDroppedErrors: 0,\n},\n{\nname: \"Link error\",\n@@ -682,6 +697,9 @@ func TestLinkAddressRequest(t *testing.T) {\nremoteLinkAddr: remoteLinkAddr,\nlinkErr: tcpip.ErrInvalidEndpointState,\nexpectedErr: tcpip.ErrInvalidEndpointState,\n+ expectedRequestsSent: 0,\n+ expectedRequestBadLocalAddressErrors: 0,\n+ expectedRequestInterfaceHasNoLocalAddressErrors: 0,\nexpectedRequestDroppedErrors: 1,\n},\n}\n@@ -721,12 +739,12 @@ func TestLinkAddressRequest(t *testing.T) {\nif got := s.Stats().ARP.OutgoingRequestsSent.Value(); got != test.expectedRequestsSent {\nt.Errorf(\"got s.Stats().ARP.OutgoingRequestsSent.Value() = %d, want = %d\", got, test.expectedRequestsSent)\n}\n+ if got := s.Stats().ARP.OutgoingRequestInterfaceHasNoLocalAddressErrors.Value(); got != test.expectedRequestInterfaceHasNoLocalAddressErrors {\n+ t.Errorf(\"got s.Stats().ARP.OutgoingRequestInterfaceHasNoLocalAddressErrors.Value() = %d, want = %d\", got, test.expectedRequestInterfaceHasNoLocalAddressErrors)\n+ }\nif got := s.Stats().ARP.OutgoingRequestBadLocalAddressErrors.Value(); got != test.expectedRequestBadLocalAddressErrors {\nt.Errorf(\"got s.Stats().ARP.OutgoingRequestBadLocalAddressErrors.Value() = %d, want = %d\", got, test.expectedRequestBadLocalAddressErrors)\n}\n- if got := s.Stats().ARP.OutgoingRequestNetworkUnreachableErrors.Value(); got != test.expectedRequestNetworkUnreachableErrors {\n- t.Errorf(\"got s.Stats().ARP.OutgoingRequestNetworkUnreachableErrors.Value() = %d, want = %d\", got, test.expectedRequestNetworkUnreachableErrors)\n- }\nif got := s.Stats().ARP.OutgoingRequestsDropped.Value(); got != test.expectedRequestDroppedErrors {\nt.Errorf(\"got s.Stats().ARP.OutgoingRequestsDropped.Value() = %d, want = %d\", got, test.expectedRequestDroppedErrors)\n}\n@@ -774,11 +792,7 @@ func TestLinkAddressRequestWithoutNIC(t *testing.T) {\nt.Fatal(\"expected ARP protocol to implement stack.LinkAddressResolver\")\n}\n- if err := linkRes.LinkAddressRequest(remoteAddr, \"\", remoteLinkAddr, &testInterface{nicID: nicID}); err != tcpip.ErrUnknownNICID {\n- t.Fatalf(\"got p.LinkAddressRequest(%s, %s, %s, _) = %s, want = %s\", remoteAddr, \"\", remoteLinkAddr, err, tcpip.ErrUnknownNICID)\n- }\n-\n- if got := s.Stats().ARP.OutgoingRequestInterfaceHasNoLocalAddressErrors.Value(); got != 1 {\n- t.Errorf(\"got s.Stats().ARP.OutgoingRequestInterfaceHasNoLocalAddressErrors.Value() = %d, want = 1\", got)\n+ if err := linkRes.LinkAddressRequest(remoteAddr, \"\", remoteLinkAddr, &testInterface{nicID: nicID}); err != tcpip.ErrNotConnected {\n+ t.Fatalf(\"got p.LinkAddressRequest(%s, %s, %s, _) = %s, want = %s\", remoteAddr, \"\", remoteLinkAddr, err, tcpip.ErrNotConnected)\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/network/arp/stats.go", "diff": "+// Copyright 2021 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 arp\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+)\n+\n+var _ stack.NetworkEndpointStats = (*Stats)(nil)\n+\n+// Stats holds statistics related to ARP.\n+type Stats struct {\n+ // ARP holds ARP statistics.\n+ ARP tcpip.ARPStats\n+}\n+\n+// IsNetworkEndpointStats implements stack.NetworkEndpointStats.\n+func (*Stats) IsNetworkEndpointStats() {}\n+\n+type sharedStats struct {\n+ localStats Stats\n+ arp multiCounterARPStats\n+}\n+\n+// LINT.IfChange(multiCounterARPStats)\n+\n+type multiCounterARPStats struct {\n+ packetsReceived tcpip.MultiCounterStat\n+ disabledPacketsReceived tcpip.MultiCounterStat\n+ malformedPacketsReceived tcpip.MultiCounterStat\n+ requestsReceived tcpip.MultiCounterStat\n+ requestsReceivedUnknownTargetAddress tcpip.MultiCounterStat\n+ outgoingRequestInterfaceHasNoLocalAddressErrors tcpip.MultiCounterStat\n+ outgoingRequestBadLocalAddressErrors tcpip.MultiCounterStat\n+ outgoingRequestsDropped tcpip.MultiCounterStat\n+ outgoingRequestsSent tcpip.MultiCounterStat\n+ repliesReceived tcpip.MultiCounterStat\n+ outgoingRepliesDropped tcpip.MultiCounterStat\n+ outgoingRepliesSent tcpip.MultiCounterStat\n+}\n+\n+func (m *multiCounterARPStats) init(a, b *tcpip.ARPStats) {\n+ m.packetsReceived.Init(a.PacketsReceived, b.PacketsReceived)\n+ m.disabledPacketsReceived.Init(a.DisabledPacketsReceived, b.DisabledPacketsReceived)\n+ m.malformedPacketsReceived.Init(a.MalformedPacketsReceived, b.MalformedPacketsReceived)\n+ m.requestsReceived.Init(a.RequestsReceived, b.RequestsReceived)\n+ m.requestsReceivedUnknownTargetAddress.Init(a.RequestsReceivedUnknownTargetAddress, b.RequestsReceivedUnknownTargetAddress)\n+ m.outgoingRequestInterfaceHasNoLocalAddressErrors.Init(a.OutgoingRequestInterfaceHasNoLocalAddressErrors, b.OutgoingRequestInterfaceHasNoLocalAddressErrors)\n+ m.outgoingRequestBadLocalAddressErrors.Init(a.OutgoingRequestBadLocalAddressErrors, b.OutgoingRequestBadLocalAddressErrors)\n+ m.outgoingRequestsDropped.Init(a.OutgoingRequestsDropped, b.OutgoingRequestsDropped)\n+ m.outgoingRequestsSent.Init(a.OutgoingRequestsSent, b.OutgoingRequestsSent)\n+ m.repliesReceived.Init(a.RepliesReceived, b.RepliesReceived)\n+ m.outgoingRepliesDropped.Init(a.OutgoingRepliesDropped, b.OutgoingRepliesDropped)\n+ m.outgoingRepliesSent.Init(a.OutgoingRepliesSent, b.OutgoingRepliesSent)\n+}\n+\n+// LINT.ThenChange(../../tcpip.go:ARPStats)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/network/arp/stats_test.go", "diff": "+// Copyright 2021 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 arp\n+\n+import (\n+ \"reflect\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/testutil\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+)\n+\n+var _ stack.NetworkInterface = (*testInterface)(nil)\n+\n+type testInterface struct {\n+ stack.NetworkInterface\n+ nicID tcpip.NICID\n+}\n+\n+func (t *testInterface) ID() tcpip.NICID {\n+ return t.nicID\n+}\n+\n+func knownNICIDs(proto *protocol) []tcpip.NICID {\n+ var nicIDs []tcpip.NICID\n+\n+ for k := range proto.mu.eps {\n+ nicIDs = append(nicIDs, k)\n+ }\n+\n+ return nicIDs\n+}\n+\n+func TestClearEndpointFromProtocolOnClose(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n+ })\n+ proto := s.NetworkProtocolInstance(ProtocolNumber).(*protocol)\n+ nic := testInterface{nicID: 1}\n+ ep := proto.NewEndpoint(&nic, nil, nil, nil).(*endpoint)\n+ var nicIDs []tcpip.NICID\n+\n+ proto.mu.Lock()\n+ foundEP, hasEndpointBeforeClose := proto.mu.eps[nic.ID()]\n+ nicIDs = knownNICIDs(proto)\n+ proto.mu.Unlock()\n+\n+ if !hasEndpointBeforeClose {\n+ t.Fatalf(\"expected to find the nic id %d in the protocol's endpoint map (%v)\", nic.ID(), nicIDs)\n+ }\n+ if foundEP != ep {\n+ t.Fatalf(\"found an incorrect endpoint mapped to nic id %d\", nic.ID())\n+ }\n+\n+ ep.Close()\n+\n+ proto.mu.Lock()\n+ _, hasEndpointAfterClose := proto.mu.eps[nic.ID()]\n+ nicIDs = knownNICIDs(proto)\n+ proto.mu.Unlock()\n+ if hasEndpointAfterClose {\n+ t.Fatalf(\"unexpectedly found an endpoint mapped to the nic id %d in the protocol's known nic ids (%v)\", nic.ID(), nicIDs)\n+ }\n+}\n+\n+func TestMultiCounterStatsInitialization(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n+ })\n+ proto := s.NetworkProtocolInstance(ProtocolNumber).(*protocol)\n+ var nic testInterface\n+ ep := proto.NewEndpoint(&nic, nil, nil, nil).(*endpoint)\n+ // At this point, the Stack's stats and the NetworkEndpoint's stats are\n+ // expected to be bound by a MultiCounterStat.\n+ refStack := s.Stats()\n+ refEP := ep.stats.localStats\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.arp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.ARP).Elem(), reflect.ValueOf(&refStack.ARP).Elem()}); err != nil {\n+ t.Error(err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/stats.go", "new_path": "pkg/tcpip/network/ipv4/stats.go", "diff": "@@ -35,7 +35,7 @@ type Stats struct {\n}\n// IsNetworkEndpointStats implements stack.NetworkEndpointStats.\n-func (s *Stats) IsNetworkEndpointStats() {}\n+func (*Stats) IsNetworkEndpointStats() {}\n// IPStats implements stack.IPNetworkEndointStats\nfunc (s *Stats) IPStats() *tcpip.IPStats {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/stats_test.go", "new_path": "pkg/tcpip/network/ipv4/stats_test.go", "diff": "@@ -34,7 +34,7 @@ func (t *testInterface) ID() tcpip.NICID {\nreturn t.nicID\n}\n-func getKnownNICIDs(proto *protocol) []tcpip.NICID {\n+func knownNICIDs(proto *protocol) []tcpip.NICID {\nvar nicIDs []tcpip.NICID\nfor k := range proto.mu.eps {\n@@ -51,32 +51,30 @@ func TestClearEndpointFromProtocolOnClose(t *testing.T) {\nproto := s.NetworkProtocolInstance(ProtocolNumber).(*protocol)\nnic := testInterface{nicID: 1}\nep := proto.NewEndpoint(&nic, nil, nil, nil).(*endpoint)\n- {\n+ var nicIDs []tcpip.NICID\n+\nproto.mu.Lock()\n- foundEP, hasEP := proto.mu.eps[nic.ID()]\n- nicIDs := getKnownNICIDs(proto)\n+ foundEP, hasEndpointBeforeClose := proto.mu.eps[nic.ID()]\n+ nicIDs = knownNICIDs(proto)\nproto.mu.Unlock()\n- if !hasEP {\n+ if !hasEndpointBeforeClose {\nt.Fatalf(\"expected to find the nic id %d in the protocol's endpoint map (%v)\", nic.ID(), nicIDs)\n}\nif foundEP != ep {\n- t.Fatalf(\"expected protocol to map endpoint %p to nic id %d, but endpoint %p was found instead\", ep, nic.ID(), foundEP)\n- }\n+ t.Fatalf(\"found an incorrect endpoint mapped to nic id %d\", nic.ID())\n}\nep.Close()\n- {\nproto.mu.Lock()\n_, hasEP := proto.mu.eps[nic.ID()]\n- nicIDs := getKnownNICIDs(proto)\n+ nicIDs = knownNICIDs(proto)\nproto.mu.Unlock()\nif hasEP {\nt.Fatalf(\"unexpectedly found an endpoint mapped to the nic id %d in the protocol's known nic ids (%v)\", nic.ID(), nicIDs)\n}\n}\n-}\nfunc TestMultiCounterStatsInitialization(t *testing.T) {\ns := stack.New(stack.Options{\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -2581,7 +2581,7 @@ func (lm *limitedMatcher) Match(stack.Hook, *stack.PacketBuffer, string, string)\nreturn false, false\n}\n-func getKnownNICIDs(proto *protocol) []tcpip.NICID {\n+func knownNICIDs(proto *protocol) []tcpip.NICID {\nvar nicIDs []tcpip.NICID\nfor k := range proto.mu.eps {\n@@ -2598,31 +2598,29 @@ func TestClearEndpointFromProtocolOnClose(t *testing.T) {\nproto := s.NetworkProtocolInstance(ProtocolNumber).(*protocol)\nvar nic testInterface\nep := proto.NewEndpoint(&nic, nil, nil, nil).(*endpoint)\n- {\n+ var nicIDs []tcpip.NICID\n+\nproto.mu.Lock()\n- foundEP, hasEP := proto.mu.eps[nic.ID()]\n- nicIDs := getKnownNICIDs(proto)\n+ foundEP, hasEndpointBeforeClose := proto.mu.eps[nic.ID()]\n+ nicIDs = knownNICIDs(proto)\nproto.mu.Unlock()\n- if !hasEP {\n+ if !hasEndpointBeforeClose {\nt.Fatalf(\"expected to find the nic id %d in the protocol's known nic ids (%v)\", nic.ID(), nicIDs)\n}\nif foundEP != ep {\n- t.Fatalf(\"expected protocol to map endpoint %p to nic id %d, but endpoint %p was found instead\", ep, nic.ID(), foundEP)\n- }\n+ t.Fatalf(\"found an incorrect endpoint mapped to nic id %d\", nic.ID())\n}\nep.Close()\n- {\nproto.mu.Lock()\n- _, hasEP := proto.mu.eps[nic.ID()]\n- nicIDs := getKnownNICIDs(proto)\n+ _, hasEndpointAfterClose := proto.mu.eps[nic.ID()]\n+ nicIDs = knownNICIDs(proto)\nproto.mu.Unlock()\n- if hasEP {\n+ if hasEndpointAfterClose {\nt.Fatalf(\"unexpectedly found an endpoint mapped to the nic id %d in the protocol's known nic ids (%v)\", nic.ID(), nicIDs)\n}\n}\n-}\ntype fragmentInfo struct {\noffset uint16\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/stats.go", "new_path": "pkg/tcpip/network/ipv6/stats.go", "diff": "@@ -32,7 +32,7 @@ type Stats struct {\n}\n// IsNetworkEndpointStats implements stack.NetworkEndpointStats.\n-func (s *Stats) IsNetworkEndpointStats() {}\n+func (*Stats) IsNetworkEndpointStats() {}\n// IPStats implements stack.IPNetworkEndointStats\nfunc (s *Stats) IPStats() *tcpip.IPStats {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/testutil/BUILD", "new_path": "pkg/tcpip/network/testutil/BUILD", "diff": "@@ -9,6 +9,7 @@ go_library(\n\"testutil_unsafe.go\",\n],\nvisibility = [\n+ \"//pkg/tcpip/network/arp:__pkg__\",\n\"//pkg/tcpip/network/fragmentation:__pkg__\",\n\"//pkg/tcpip/network/ipv4:__pkg__\",\n\"//pkg/tcpip/network/ipv6:__pkg__\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1667,6 +1667,8 @@ type IPStats struct {\n// ARPStats collects ARP-specific stats.\ntype ARPStats struct {\n+ // LINT.IfChange(ARPStats)\n+\n// PacketsReceived is the number of ARP packets received from the link layer.\nPacketsReceived *StatCounter\n@@ -1694,10 +1696,6 @@ type ARPStats struct {\n// ARP request with a bad local address.\nOutgoingRequestBadLocalAddressErrors *StatCounter\n- // OutgoingRequestNetworkUnreachableErrors is the number of failures to send\n- // an ARP request with a network unreachable error.\n- OutgoingRequestNetworkUnreachableErrors *StatCounter\n-\n// OutgoingRequestsDropped is the number of ARP requests which failed to write\n// to a link-layer endpoint.\nOutgoingRequestsDropped *StatCounter\n@@ -1716,6 +1714,8 @@ type ARPStats struct {\n// OutgoingRepliesSent is the number of ARP replies successfully written to a\n// link-layer endpoint.\nOutgoingRepliesSent *StatCounter\n+\n+ // LINT.ThenChange(network/arp/stats.go:multiCounterARPStats)\n}\n// TCPStats collects TCP-specific stats.\n" } ]
Go
Apache License 2.0
google/gvisor
Add per endpoint ARP statistics The ARP stat NetworkUnreachable was removed, and was replaced by InterfaceHasNoLocalAddress. No stats are recorded when dealing with an missing endpoint (ErrNotConnected) (because if there is no endpoint, there is no valid per-endpoint stats). PiperOrigin-RevId: 353759462
259,860
26.01.2021 00:00:52
28,800
3946075403a93907138f13e61bdba075aeabfecf
Do not generate extraneous IN_CLOSE inotify events. IN_CLOSE should only be generated when a file description loses its last reference; not when a file descriptor is closed. See fs/file_table.c:__fput. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table.go", "new_path": "pkg/sentry/kernel/fd_table.go", "diff": "@@ -159,13 +159,6 @@ func (f *FDTable) dropVFS2(ctx context.Context, file *vfs.FileDescription) {\npanic(fmt.Sprintf(\"UnlockPOSIX failed: %v\", err))\n}\n- // Generate inotify events.\n- ev := uint32(linux.IN_CLOSE_NOWRITE)\n- if file.IsWritable() {\n- ev = linux.IN_CLOSE_WRITE\n- }\n- file.Dentry().InotifyWithParent(ctx, ev, 0, vfs.PathEvent)\n-\n// Drop the table's reference.\nfile.DecRef(ctx)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -161,6 +161,13 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, flags uint32, mnt *Mou\n// DecRef decrements fd's reference count.\nfunc (fd *FileDescription) DecRef(ctx context.Context) {\nfd.FileDescriptionRefs.DecRef(func() {\n+ // Generate inotify events.\n+ ev := uint32(linux.IN_CLOSE_NOWRITE)\n+ if fd.IsWritable() {\n+ ev = linux.IN_CLOSE_WRITE\n+ }\n+ fd.Dentry().InotifyWithParent(ctx, ev, 0, PathEvent)\n+\n// Unregister fd from all epoll instances.\nfd.epollMu.Lock()\nepolls := fd.epolls\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -782,6 +782,38 @@ TEST(Inotify, MoveWatchedTargetGeneratesEvents) {\nEXPECT_EQ(events[0].cookie, events[1].cookie);\n}\n+// Tests that close events are only emitted when a file description drops its\n+// last reference.\n+TEST(Inotify, DupFD) {\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor inotify_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+\n+ const int wd = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(inotify_fd.get(), file.path(), IN_ALL_EVENTS));\n+\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+ FileDescriptor fd2 = ASSERT_NO_ERRNO_AND_VALUE(fd.Dup());\n+\n+ std::vector<Event> events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\n+ EXPECT_THAT(events, Are({\n+ Event(IN_OPEN, wd),\n+ }));\n+\n+ fd.reset();\n+ events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\n+ EXPECT_THAT(events, Are({}));\n+\n+ fd2.reset();\n+ events = ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(inotify_fd.get()));\n+ EXPECT_THAT(events, Are({\n+ Event(IN_CLOSE_NOWRITE, wd),\n+ }));\n+}\n+\nTEST(Inotify, CoalesceEvents) {\nconst TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nconst FileDescriptor fd =\n" } ]
Go
Apache License 2.0
google/gvisor
Do not generate extraneous IN_CLOSE inotify events. IN_CLOSE should only be generated when a file description loses its last reference; not when a file descriptor is closed. See fs/file_table.c:__fput. Updates #5348. PiperOrigin-RevId: 353810697
259,860
26.01.2021 09:47:24
28,800
abdff887483f1d9487bffa0278dd6f7a40e59a74
Do not send SCM Rights more than once when message is truncated. If data is sent over a stream socket that will not fit all at once, it will be sent over multiple packets. SCM Rights should only be sent with the first packet (see net/unix/af_unix.c:unix_stream_sendmsg in Linux). Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix.go", "new_path": "pkg/sentry/socket/unix/unix.go", "diff": "@@ -496,6 +496,9 @@ func (s *socketOpsCommon) SendMsg(t *kernel.Task, src usermem.IOSequence, to []b\nreturn int(n), syserr.FromError(err)\n}\n+ // Only send SCM Rights once (see net/unix/af_unix.c:unix_stream_sendmsg).\n+ w.Control.Rights = nil\n+\n// We'll have to block. Register for notification and keep trying to\n// send all the data.\ne, ch := waiter.NewChannelEntry(nil)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket.cc", "new_path": "test/syscalls/linux/socket.cc", "diff": "#include <sys/stat.h>\n#include <sys/statfs.h>\n#include <sys/types.h>\n+#include <sys/wait.h>\n#include <unistd.h>\n#include \"gtest/gtest.h\"\n@@ -111,6 +112,77 @@ TEST(SocketTest, UnixSocketStatFS) {\nEXPECT_EQ(st.f_namelen, NAME_MAX);\n}\n+TEST(SocketTest, UnixSCMRightsOnlyPassedOnce_NoRandomSave) {\n+ const DisableSave ds;\n+\n+ int sockets[2];\n+ ASSERT_THAT(socketpair(AF_UNIX, SOCK_STREAM, 0, sockets), SyscallSucceeds());\n+ // Send more than what will fit inside the send/receive buffers, so that it is\n+ // split into multiple messages.\n+ constexpr int kBufSize = 0x100000;\n+\n+ pid_t pid = fork();\n+ if (pid == 0) {\n+ TEST_PCHECK(close(sockets[0]) == 0);\n+\n+ // Construct a message with some control message.\n+ struct msghdr msg = {};\n+ char control[CMSG_SPACE(sizeof(int))] = {};\n+ std::vector<char> buf(kBufSize);\n+ struct iovec iov = {};\n+ msg.msg_control = control;\n+ msg.msg_controllen = sizeof(control);\n+\n+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);\n+ cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n+ cmsg->cmsg_level = SOL_SOCKET;\n+ cmsg->cmsg_type = SCM_RIGHTS;\n+ ((int*)CMSG_DATA(cmsg))[0] = sockets[1];\n+\n+ iov.iov_base = buf.data();\n+ iov.iov_len = kBufSize;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ int n = sendmsg(sockets[1], &msg, 0);\n+ TEST_PCHECK(n == kBufSize);\n+ TEST_PCHECK(shutdown(sockets[1], SHUT_RDWR) == 0);\n+ TEST_PCHECK(close(sockets[1]) == 0);\n+ _exit(0);\n+ }\n+\n+ close(sockets[1]);\n+\n+ struct msghdr msg = {};\n+ char control[CMSG_SPACE(sizeof(int))] = {};\n+ std::vector<char> buf(kBufSize);\n+ struct iovec iov = {};\n+ msg.msg_control = &control;\n+ msg.msg_controllen = sizeof(control);\n+\n+ iov.iov_base = buf.data();\n+ iov.iov_len = kBufSize;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ // The control message should only be present in the first message received.\n+ int n;\n+ ASSERT_THAT(n = recvmsg(sockets[0], &msg, 0), SyscallSucceeds());\n+ ASSERT_GT(n, 0);\n+ ASSERT_EQ(msg.msg_controllen, CMSG_SPACE(sizeof(int)));\n+\n+ while (n > 0) {\n+ ASSERT_THAT(n = recvmsg(sockets[0], &msg, 0), SyscallSucceeds());\n+ ASSERT_EQ(msg.msg_controllen, 0);\n+ }\n+\n+ close(sockets[0]);\n+\n+ int status;\n+ ASSERT_THAT(waitpid(pid, &status, 0), SyscallSucceedsWithValue(pid));\n+ ASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n+}\n+\nusing SocketOpenTest = ::testing::TestWithParam<int>;\n// UDS cannot be opened.\n" } ]
Go
Apache License 2.0
google/gvisor
Do not send SCM Rights more than once when message is truncated. If data is sent over a stream socket that will not fit all at once, it will be sent over multiple packets. SCM Rights should only be sent with the first packet (see net/unix/af_unix.c:unix_stream_sendmsg in Linux). Reported-by: [email protected] PiperOrigin-RevId: 353886442
260,004
26.01.2021 10:32:46
28,800
9ba24d449f8c62756b809610ec4cd02222e18bd3
Drop nicID from transport endpoint reg/cleanup fns ...as it is unused.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -1629,25 +1629,25 @@ func (s *Stack) ClearNeighbors(nicID tcpip.NICID) *tcpip.Error {\n// transport dispatcher. Received packets that match the provided id will be\n// delivered to the given endpoint; specifying a nic is optional, but\n// nic-specific IDs have precedence over global ones.\n-func (s *Stack) RegisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) *tcpip.Error {\n+func (s *Stack) RegisterTransportEndpoint(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) *tcpip.Error {\nreturn s.demux.registerEndpoint(netProtos, protocol, id, ep, flags, bindToDevice)\n}\n// CheckRegisterTransportEndpoint checks if an endpoint can be registered with\n// the stack transport dispatcher.\n-func (s *Stack) CheckRegisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, flags ports.Flags, bindToDevice tcpip.NICID) *tcpip.Error {\n+func (s *Stack) CheckRegisterTransportEndpoint(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, flags ports.Flags, bindToDevice tcpip.NICID) *tcpip.Error {\nreturn s.demux.checkEndpoint(netProtos, protocol, id, flags, bindToDevice)\n}\n// UnregisterTransportEndpoint removes the endpoint with the given id from the\n// stack transport dispatcher.\n-func (s *Stack) UnregisterTransportEndpoint(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) {\n+func (s *Stack) UnregisterTransportEndpoint(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) {\ns.demux.unregisterEndpoint(netProtos, protocol, id, ep, flags, bindToDevice)\n}\n// StartTransportEndpointCleanup removes the endpoint with the given id from\n// the stack transport dispatcher. It also transitions it to the cleanup stage.\n-func (s *Stack) StartTransportEndpointCleanup(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) {\n+func (s *Stack) StartTransportEndpointCleanup(netProtos []tcpip.NetworkProtocolNumber, protocol tcpip.TransportProtocolNumber, id TransportEndpointID, ep TransportEndpoint, flags ports.Flags, bindToDevice tcpip.NICID) {\ns.cleanupEndpointsMu.Lock()\ns.cleanupEndpoints[ep] = struct{}{}\ns.cleanupEndpointsMu.Unlock()\n@@ -1672,13 +1672,13 @@ func (s *Stack) FindTransportEndpoint(netProto tcpip.NetworkProtocolNumber, tran\n// RegisterRawTransportEndpoint registers the given endpoint with the stack\n// transport dispatcher. Received packets that match the provided transport\n// protocol will be delivered to the given endpoint.\n-func (s *Stack) RegisterRawTransportEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint) *tcpip.Error {\n+func (s *Stack) RegisterRawTransportEndpoint(netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint) *tcpip.Error {\nreturn s.demux.registerRawEndpoint(netProto, transProto, ep)\n}\n// UnregisterRawTransportEndpoint removes the endpoint for the transport\n// protocol from the stack transport dispatcher.\n-func (s *Stack) UnregisterRawTransportEndpoint(nicID tcpip.NICID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint) {\n+func (s *Stack) UnregisterRawTransportEndpoint(netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ep RawTransportEndpoint) {\ns.demux.unregisterRawEndpoint(netProto, transProto, ep)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer_test.go", "new_path": "pkg/tcpip/stack/transport_demuxer_test.go", "diff": "@@ -194,7 +194,7 @@ func TestTransportDemuxerRegister(t *testing.T) {\nif !ok {\nt.Fatalf(\"%T does not implement stack.TransportEndpoint\", ep)\n}\n- if got, want := s.RegisterTransportEndpoint(0, []tcpip.NetworkProtocolNumber{test.proto}, udp.ProtocolNumber, stack.TransportEndpointID{}, tEP, ports.Flags{}, 0), test.want; got != want {\n+ if got, want := s.RegisterTransportEndpoint([]tcpip.NetworkProtocolNumber{test.proto}, udp.ProtocolNumber, stack.TransportEndpointID{}, tEP, ports.Flags{}, 0), test.want; got != want {\nt.Fatalf(\"s.RegisterTransportEndpoint(...) = %s, want %s\", got, want)\n}\n})\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_test.go", "new_path": "pkg/tcpip/stack/transport_test.go", "diff": "@@ -149,7 +149,7 @@ func (f *fakeTransportEndpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n// Try to register so that we can start receiving packets.\nf.ID.RemoteAddress = addr.Addr\n- err = f.proto.stack.RegisterTransportEndpoint(0, []tcpip.NetworkProtocolNumber{fakeNetNumber}, fakeTransNumber, f.ID, f, ports.Flags{}, 0 /* bindToDevice */)\n+ err = f.proto.stack.RegisterTransportEndpoint([]tcpip.NetworkProtocolNumber{fakeNetNumber}, fakeTransNumber, f.ID, f, ports.Flags{}, 0 /* bindToDevice */)\nif err != nil {\nr.Release()\nreturn err\n@@ -190,7 +190,6 @@ func (f *fakeTransportEndpoint) Accept(*tcpip.FullAddress) (tcpip.Endpoint, *wai\nfunc (f *fakeTransportEndpoint) Bind(a tcpip.FullAddress) *tcpip.Error {\nif err := f.proto.stack.RegisterTransportEndpoint(\n- a.NIC,\n[]tcpip.NetworkProtocolNumber{fakeNetNumber},\nfakeTransNumber,\nstack.TransportEndpointID{LocalAddress: a.Addr},\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -124,7 +124,7 @@ func (e *endpoint) Close() {\ne.shutdownFlags = tcpip.ShutdownRead | tcpip.ShutdownWrite\nswitch e.state {\ncase stateBound, stateConnected:\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, []tcpip.NetworkProtocolNumber{e.NetProto}, e.TransProto, e.ID, e, ports.Flags{}, 0 /* bindToDevice */)\n+ e.stack.UnregisterTransportEndpoint([]tcpip.NetworkProtocolNumber{e.NetProto}, e.TransProto, e.ID, e, ports.Flags{}, 0 /* bindToDevice */)\n}\n// Close the receive list and drain it.\n@@ -579,14 +579,14 @@ func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.Networ\nif id.LocalPort != 0 {\n// The endpoint already has a local port, just attempt to\n// register it.\n- err := e.stack.RegisterTransportEndpoint(nicID, netProtos, e.TransProto, id, e, ports.Flags{}, 0 /* bindToDevice */)\n+ err := e.stack.RegisterTransportEndpoint(netProtos, e.TransProto, id, e, ports.Flags{}, 0 /* bindToDevice */)\nreturn id, err\n}\n// We need to find a port for the endpoint.\n_, err := e.stack.PickEphemeralPort(func(p uint16) (bool, *tcpip.Error) {\nid.LocalPort = p\n- err := e.stack.RegisterTransportEndpoint(nicID, netProtos, e.TransProto, id, e, ports.Flags{}, 0 /* bindtodevice */)\n+ err := e.stack.RegisterTransportEndpoint(netProtos, e.TransProto, id, e, ports.Flags{}, 0 /* bindtodevice */)\nswitch err {\ncase nil:\nreturn true, nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -136,7 +136,7 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nreturn e, nil\n}\n- if err := e.stack.RegisterRawTransportEndpoint(e.RegisterNICID, e.NetProto, e.TransProto, e); err != nil {\n+ if err := e.stack.RegisterRawTransportEndpoint(e.NetProto, e.TransProto, e); err != nil {\nreturn nil, err\n}\n@@ -157,7 +157,7 @@ func (e *endpoint) Close() {\nreturn\n}\n- e.stack.UnregisterRawTransportEndpoint(e.RegisterNICID, e.NetProto, e.TransProto, e)\n+ e.stack.UnregisterRawTransportEndpoint(e.NetProto, e.TransProto, e)\ne.rcvMu.Lock()\ndefer e.rcvMu.Unlock()\n@@ -405,11 +405,11 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nif e.associated {\n// Re-register the endpoint with the appropriate NIC.\n- if err := e.stack.RegisterRawTransportEndpoint(addr.NIC, e.NetProto, e.TransProto, e); err != nil {\n+ if err := e.stack.RegisterRawTransportEndpoint(e.NetProto, e.TransProto, e); err != nil {\nroute.Release()\nreturn err\n}\n- e.stack.UnregisterRawTransportEndpoint(e.RegisterNICID, e.NetProto, e.TransProto, e)\n+ e.stack.UnregisterRawTransportEndpoint(e.NetProto, e.TransProto, e)\ne.RegisterNICID = nic\n}\n@@ -447,16 +447,16 @@ func (e *endpoint) Bind(addr tcpip.FullAddress) *tcpip.Error {\ndefer e.mu.Unlock()\n// If a local address was specified, verify that it's valid.\n- if len(addr.Addr) != 0 && e.stack.CheckLocalAddress(addr.NIC, e.NetProto, addr.Addr) == 0 {\n+ if len(addr.Addr) != 0 && e.stack.CheckLocalAddress(e.RegisterNICID, e.NetProto, addr.Addr) == 0 {\nreturn tcpip.ErrBadLocalAddress\n}\nif e.associated {\n// Re-register the endpoint with the appropriate NIC.\n- if err := e.stack.RegisterRawTransportEndpoint(addr.NIC, e.NetProto, e.TransProto, e); err != nil {\n+ if err := e.stack.RegisterRawTransportEndpoint(e.NetProto, e.TransProto, e); err != nil {\nreturn err\n}\n- e.stack.UnregisterRawTransportEndpoint(e.RegisterNICID, e.NetProto, e.TransProto, e)\n+ e.stack.UnregisterRawTransportEndpoint(e.NetProto, e.TransProto, e)\ne.RegisterNICID = addr.NIC\ne.BindNICID = addr.NIC\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint_state.go", "new_path": "pkg/tcpip/transport/raw/endpoint_state.go", "diff": "@@ -94,7 +94,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\n}\nif e.associated {\n- if err := e.stack.RegisterRawTransportEndpoint(e.RegisterNICID, e.NetProto, e.TransProto, e); err != nil {\n+ if err := e.stack.RegisterRawTransportEndpoint(e.NetProto, e.TransProto, e); err != nil {\npanic(err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -288,7 +288,7 @@ func (l *listenContext) startHandshake(s *segment, opts *header.TCPSynOptions, q\n}\n// Register new endpoint so that packets are routed to it.\n- if err := ep.stack.RegisterTransportEndpoint(ep.boundNICID, ep.effectiveNetProtos, ProtocolNumber, ep.ID, ep, ep.boundPortFlags, ep.boundBindToDevice); err != nil {\n+ if err := ep.stack.RegisterTransportEndpoint(ep.effectiveNetProtos, ProtocolNumber, ep.ID, ep, ep.boundPortFlags, ep.boundBindToDevice); err != nil {\nep.mu.Unlock()\nep.Close()\n@@ -692,7 +692,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) *tcpip.Er\n}\n// Register new endpoint so that packets are routed to it.\n- if err := n.stack.RegisterTransportEndpoint(n.boundNICID, n.effectiveNetProtos, ProtocolNumber, n.ID, n, n.boundPortFlags, n.boundBindToDevice); err != nil {\n+ if err := n.stack.RegisterTransportEndpoint(n.effectiveNetProtos, ProtocolNumber, n.ID, n, n.boundPortFlags, n.boundBindToDevice); err != nil {\nn.mu.Unlock()\nn.Close()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1087,7 +1087,7 @@ func (e *endpoint) closeNoShutdownLocked() {\n// in Listen() when trying to register.\nif e.EndpointState() == StateListen && e.isPortReserved {\nif e.isRegistered {\n- e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\n+ e.stack.StartTransportEndpointCleanup(e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\ne.isRegistered = false\n}\n@@ -1161,7 +1161,7 @@ func (e *endpoint) cleanupLocked() {\ne.workerCleanup = false\nif e.isRegistered {\n- e.stack.StartTransportEndpointCleanup(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\n+ e.stack.StartTransportEndpointCleanup(e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\ne.isRegistered = false\n}\n@@ -2178,7 +2178,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) *tc\nif e.ID.LocalPort != 0 {\n// The endpoint is bound to a port, attempt to register it.\n- err := e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\n+ err := e.stack.RegisterTransportEndpoint(netProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\nif err != nil {\nreturn err\n}\n@@ -2266,7 +2266,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) *tc\nid := e.ID\nid.LocalPort = p\n- if err := e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, id, e, e.portFlags, bindToDevice); err != nil {\n+ if err := e.stack.RegisterTransportEndpoint(netProtos, ProtocolNumber, id, e, e.portFlags, bindToDevice); err != nil {\ne.stack.ReleasePort(netProtos, ProtocolNumber, e.ID.LocalAddress, p, e.portFlags, bindToDevice, addr)\nif err == tcpip.ErrPortInUse {\nreturn false, nil\n@@ -2470,7 +2470,7 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\n}\n// Register the endpoint.\n- if err := e.stack.RegisterTransportEndpoint(e.boundNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice); err != nil {\n+ if err := e.stack.RegisterTransportEndpoint(e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice); err != nil {\nreturn err\n}\n@@ -2592,7 +2592,7 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) (err *tcpip.Error) {\n// demuxer. Further connected endpoints always have a remote\n// address/port. Hence this will only return an error if there is a matching\n// listening endpoint.\n- if err := e.stack.CheckRegisterTransportEndpoint(nic, netProtos, ProtocolNumber, id, e.portFlags, bindToDevice); err != nil {\n+ if err := e.stack.CheckRegisterTransportEndpoint(netProtos, ProtocolNumber, id, e.portFlags, bindToDevice); err != nil {\nreturn false\n}\nreturn true\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -244,7 +244,7 @@ func (e *endpoint) Close() {\nswitch e.EndpointState() {\ncase StateBound, StateConnected:\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.effectiveNetProtos, ProtocolNumber, e.ID, e, e.boundPortFlags, e.boundBindToDevice)\ne.stack.ReleasePort(e.effectiveNetProtos, ProtocolNumber, e.ID.LocalAddress, e.ID.LocalPort, e.boundPortFlags, e.boundBindToDevice, tcpip.FullAddress{})\ne.boundBindToDevice = 0\ne.boundPortFlags = ports.Flags{}\n@@ -908,7 +908,7 @@ func (e *endpoint) Disconnect() *tcpip.Error {\nLocalPort: e.ID.LocalPort,\nLocalAddress: e.ID.LocalAddress,\n}\n- id, btd, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\n+ id, btd, err = e.registerWithStack(e.effectiveNetProtos, id)\nif err != nil {\nreturn err\n}\n@@ -923,7 +923,7 @@ func (e *endpoint) Disconnect() *tcpip.Error {\ne.setEndpointState(StateInitial)\n}\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, boundPortFlags, e.boundBindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.effectiveNetProtos, ProtocolNumber, e.ID, e, boundPortFlags, e.boundBindToDevice)\ne.ID = id\ne.boundBindToDevice = btd\ne.route.Release()\n@@ -996,7 +996,7 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\noldPortFlags := e.boundPortFlags\n- id, btd, err := e.registerWithStack(nicID, netProtos, id)\n+ id, btd, err := e.registerWithStack(netProtos, id)\nif err != nil {\nr.Release()\nreturn err\n@@ -1004,7 +1004,7 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n// Remove the old registration.\nif e.ID.LocalPort != 0 {\n- e.stack.UnregisterTransportEndpoint(e.RegisterNICID, e.effectiveNetProtos, ProtocolNumber, e.ID, e, oldPortFlags, e.boundBindToDevice)\n+ e.stack.UnregisterTransportEndpoint(e.effectiveNetProtos, ProtocolNumber, e.ID, e, oldPortFlags, e.boundBindToDevice)\n}\ne.ID = id\n@@ -1066,7 +1066,7 @@ func (*endpoint) Accept(*tcpip.FullAddress) (tcpip.Endpoint, *waiter.Queue, *tcp\nreturn nil, nil, tcpip.ErrNotSupported\n}\n-func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, tcpip.NICID, *tcpip.Error) {\n+func (e *endpoint) registerWithStack(netProtos []tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, tcpip.NICID, *tcpip.Error) {\nbindToDevice := tcpip.NICID(e.ops.GetBindToDevice())\nif e.ID.LocalPort == 0 {\nport, err := e.stack.ReservePort(netProtos, ProtocolNumber, id.LocalAddress, id.LocalPort, e.portFlags, bindToDevice, tcpip.FullAddress{}, nil /* testPort */)\n@@ -1077,7 +1077,7 @@ func (e *endpoint) registerWithStack(nicID tcpip.NICID, netProtos []tcpip.Networ\n}\ne.boundPortFlags = e.portFlags\n- err := e.stack.RegisterTransportEndpoint(nicID, netProtos, ProtocolNumber, id, e, e.boundPortFlags, bindToDevice)\n+ err := e.stack.RegisterTransportEndpoint(netProtos, ProtocolNumber, id, e, e.boundPortFlags, bindToDevice)\nif err != nil {\ne.stack.ReleasePort(netProtos, ProtocolNumber, id.LocalAddress, id.LocalPort, e.boundPortFlags, bindToDevice, tcpip.FullAddress{})\ne.boundPortFlags = ports.Flags{}\n@@ -1121,7 +1121,7 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) *tcpip.Error {\nLocalPort: addr.Port,\nLocalAddress: addr.Addr,\n}\n- id, btd, err := e.registerWithStack(nicID, netProtos, id)\n+ id, btd, err := e.registerWithStack(netProtos, id)\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint_state.go", "new_path": "pkg/tcpip/transport/udp/endpoint_state.go", "diff": "@@ -132,7 +132,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\n// pass it to the reservation machinery.\nid := e.ID\ne.ID.LocalPort = 0\n- e.ID, e.boundBindToDevice, err = e.registerWithStack(e.RegisterNICID, e.effectiveNetProtos, id)\n+ e.ID, e.boundBindToDevice, err = e.registerWithStack(e.effectiveNetProtos, id)\nif err != nil {\npanic(err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/forwarder.go", "new_path": "pkg/tcpip/transport/udp/forwarder.go", "diff": "@@ -77,7 +77,7 @@ func (r *ForwarderRequest) CreateEndpoint(queue *waiter.Queue) (tcpip.Endpoint,\n}\nep := newEndpoint(r.stack, r.pkt.NetworkProtocolNumber, queue)\n- if err := r.stack.RegisterTransportEndpoint(r.pkt.NICID, []tcpip.NetworkProtocolNumber{r.pkt.NetworkProtocolNumber}, ProtocolNumber, r.id, ep, ep.portFlags, tcpip.NICID(ep.ops.GetBindToDevice())); err != nil {\n+ if err := r.stack.RegisterTransportEndpoint([]tcpip.NetworkProtocolNumber{r.pkt.NetworkProtocolNumber}, ProtocolNumber, r.id, ep, ep.portFlags, tcpip.NICID(ep.ops.GetBindToDevice())); err != nil {\nep.Close()\nroute.Release()\nreturn nil, err\n" } ]
Go
Apache License 2.0
google/gvisor
Drop nicID from transport endpoint reg/cleanup fns ...as it is unused. PiperOrigin-RevId: 353896981
259,860
26.01.2021 12:00:04
28,800
96bd076e8a002ccacc414e92c83dedf2e35ca07b
Initialize timestamps for gofer synthetic children. Contrary to the comment on the socket test, the failure was due to an issue with goferfs rather than kernfs.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/directory.go", "new_path": "pkg/sentry/fsimpl/gofer/directory.go", "diff": "@@ -90,6 +90,7 @@ type createSyntheticOpts struct {\n// * d.isDir().\n// * d does not already contain a child with the given name.\nfunc (d *dentry) createSyntheticChildLocked(opts *createSyntheticOpts) {\n+ now := d.fs.clock.Now().Nanoseconds()\nchild := &dentry{\nrefs: 1, // held by d\nfs: d.fs,\n@@ -98,6 +99,10 @@ func (d *dentry) createSyntheticChildLocked(opts *createSyntheticOpts) {\nuid: uint32(opts.kuid),\ngid: uint32(opts.kgid),\nblockSize: usermem.PageSize, // arbitrary\n+ atime: now,\n+ mtime: now,\n+ ctime: now,\n+ btime: now,\nreadFD: -1,\nwriteFD: -1,\nmmapFD: -1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket.cc", "new_path": "test/syscalls/linux/socket.cc", "diff": "@@ -91,8 +91,7 @@ TEST(SocketTest, UnixSocketStat) {\nEXPECT_EQ(statbuf.st_mode, S_IFSOCK | (sock_perm & ~mask));\n// Timestamps should be equal and non-zero.\n- // TODO(b/158882152): Sockets currently don't implement timestamps.\n- if (!IsRunningOnGvisor()) {\n+ if (!IsRunningWithVFS1()) {\nEXPECT_NE(statbuf.st_atime, 0);\nEXPECT_EQ(statbuf.st_atime, statbuf.st_mtime);\nEXPECT_EQ(statbuf.st_atime, statbuf.st_ctime);\n" } ]
Go
Apache License 2.0
google/gvisor
Initialize timestamps for gofer synthetic children. Contrary to the comment on the socket test, the failure was due to an issue with goferfs rather than kernfs. PiperOrigin-RevId: 353918021
259,962
26.01.2021 12:07:16
28,800
a90661654d14e77b6442c4a34ced900e2cd9953e
Fix couple of potential route leaks. connect() can be invoked multiple times on UDP/RAW sockets and in such a case we should release the cached route from the previous connect. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -413,7 +413,10 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.RegisterNICID = nic\n}\n- // Save the route we've connected via.\n+ if e.route != nil {\n+ // If the endpoint was previously connected then release any previous route.\n+ e.route.Release()\n+ }\ne.route = route\ne.connected = true\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -1009,6 +1009,11 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.ID = id\ne.boundBindToDevice = btd\n+ if e.route != nil {\n+ // If the endpoint was already connected then make sure we release the\n+ // previous route.\n+ e.route.Release()\n+ }\ne.route = r\ne.dstPort = addr.Port\ne.RegisterNICID = nicID\n" } ]
Go
Apache License 2.0
google/gvisor
Fix couple of potential route leaks. connect() can be invoked multiple times on UDP/RAW sockets and in such a case we should release the cached route from the previous connect. Fixes #5359 PiperOrigin-RevId: 353919891
260,004
26.01.2021 15:43:22
28,800
8bb7d61bdca59b98761b198ec258a6d77441c7ed
Do not use stack.Route to send NDP NS When sending packets through a stack.Route, we attempt to perform link resolution. Neighbor Solicitation messages do not need link resolution to be performed so send the packets out the interface directly instead.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -688,25 +688,38 @@ func (*protocol) LinkAddressProtocol() tcpip.NetworkProtocolNumber {\n// LinkAddressRequest implements stack.LinkAddressResolver.\nfunc (p *protocol) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remoteLinkAddr tcpip.LinkAddress, nic stack.NetworkInterface) *tcpip.Error {\n+ nicID := nic.ID()\n+\n+ p.mu.Lock()\n+ netEP, ok := p.mu.eps[nicID]\n+ p.mu.Unlock()\n+ if !ok {\n+ return tcpip.ErrNotConnected\n+ }\n+\nremoteAddr := targetAddr\nif len(remoteLinkAddr) == 0 {\nremoteAddr = header.SolicitedNodeAddr(targetAddr)\nremoteLinkAddr = header.EthernetAddressFromMulticastIPv6Address(remoteAddr)\n}\n- r, err := p.stack.FindRoute(nic.ID(), localAddr, remoteAddr, ProtocolNumber, false /* multicastLoop */)\n- if err != nil {\n- return err\n+ if len(localAddr) == 0 {\n+ addressEndpoint := netEP.AcquireOutgoingPrimaryAddress(remoteAddr, false /* allowExpired */)\n+ if addressEndpoint == nil {\n+ return tcpip.ErrNetworkUnreachable\n+ }\n+\n+ localAddr = addressEndpoint.AddressWithPrefix().Address\n+ } else if p.stack.CheckLocalAddress(nicID, ProtocolNumber, localAddr) == 0 {\n+ return tcpip.ErrBadLocalAddress\n}\n- defer r.Release()\n- r.ResolveWith(remoteLinkAddr)\noptsSerializer := header.NDPOptionsSerializer{\nheader.NDPSourceLinkLayerAddressOption(nic.LinkAddress()),\n}\nneighborSolicitSize := header.ICMPv6NeighborSolicitMinimumSize + optsSerializer.Length()\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: int(r.MaxHeaderLength()) + neighborSolicitSize,\n+ ReserveHeaderBytes: int(nic.MaxHeaderLength()) + header.IPv6FixedHeaderSize + neighborSolicitSize,\n})\npkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber\npacket := header.ICMPv6(pkt.TransportHeader().Push(neighborSolicitSize))\n@@ -714,20 +727,18 @@ func (p *protocol) LinkAddressRequest(targetAddr, localAddr tcpip.Address, remot\nns := header.NDPNeighborSolicit(packet.MessageBody())\nns.SetTargetAddress(targetAddr)\nns.Options().Serialize(optsSerializer)\n- packet.SetChecksum(header.ICMPv6Checksum(packet, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+ packet.SetChecksum(header.ICMPv6Checksum(packet, localAddr, remoteAddr, buffer.VectorisedView{}))\n- p.mu.Lock()\n- netEP, ok := p.mu.eps[nic.ID()]\n- p.mu.Unlock()\n- if !ok {\n- return tcpip.ErrNotConnected\n+ if err := addIPHeader(localAddr, remoteAddr, pkt, stack.NetworkHeaderParams{\n+ Protocol: header.ICMPv6ProtocolNumber,\n+ TTL: header.NDPHopLimit,\n+ }, header.IPv6ExtHdrSerializer{}); err != nil {\n+ panic(fmt.Sprintf(\"failed to add IP header: %s\", err))\n}\n+\nstat := netEP.stats.icmp.packetsSent\n- if err := r.WritePacket(nil /* gso */, stack.NetworkHeaderParams{\n- Protocol: header.ICMPv6ProtocolNumber,\n- TTL: header.NDPHopLimit,\n- }, pkt); err != nil {\n+ if err := nic.WritePacketToRemote(remoteLinkAddr, nil /* gso */, ProtocolNumber, pkt); err != nil {\nstat.dropped.Increment()\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -23,6 +23,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@@ -1320,13 +1321,13 @@ func TestLinkAddressRequest(t *testing.T) {\nname: \"Unicast with unassigned address\",\nlocalAddr: lladdr1,\nremoteLinkAddr: linkAddr1,\n- expectedErr: tcpip.ErrNetworkUnreachable,\n+ expectedErr: tcpip.ErrBadLocalAddress,\n},\n{\nname: \"Multicast with unassigned address\",\nlocalAddr: lladdr1,\nremoteLinkAddr: \"\",\n- expectedErr: tcpip.ErrNetworkUnreachable,\n+ expectedErr: tcpip.ErrBadLocalAddress,\n},\n{\nname: \"Unicast with no local address available\",\n@@ -1341,6 +1342,7 @@ func TestLinkAddressRequest(t *testing.T) {\n}\nfor _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n})\n@@ -1376,14 +1378,12 @@ func TestLinkAddressRequest(t *testing.T) {\nif !ok {\nt.Fatal(\"expected to send a link address request\")\n}\n- if pkt.Route.RemoteLinkAddress != test.expectedRemoteLinkAddr {\n- t.Errorf(\"got pkt.Route.RemoteLinkAddress = %s, want = %s\", pkt.Route.RemoteLinkAddress, test.expectedRemoteLinkAddr)\n- }\n- if pkt.Route.RemoteAddress != test.expectedRemoteAddr {\n- t.Errorf(\"got pkt.Route.RemoteAddress = %s, want = %s\", pkt.Route.RemoteAddress, test.expectedRemoteAddr)\n- }\n- if pkt.Route.LocalAddress != lladdr1 {\n- t.Errorf(\"got pkt.Route.LocalAddress = %s, want = %s\", pkt.Route.LocalAddress, lladdr1)\n+\n+ var want stack.RouteInfo\n+ want.NetProto = ProtocolNumber\n+ want.RemoteLinkAddress = test.expectedRemoteLinkAddr\n+ if diff := cmp.Diff(want, pkt.Route, cmp.AllowUnexported(want)); diff != \"\" {\n+ t.Errorf(\"route info mismatch (-want +got):\\n%s\", diff)\n}\nchecker.IPv6(t, stack.PayloadSince(pkt.Pkt.NetworkHeader()),\nchecker.SrcAddr(lladdr1),\n@@ -1393,6 +1393,7 @@ func TestLinkAddressRequest(t *testing.T) {\nchecker.NDPNSTargetAddress(lladdr0),\nchecker.NDPNSOptions([]header.NDPOption{header.NDPSourceLinkLayerAddressOption(linkAddr0)}),\n))\n+ })\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -555,7 +555,7 @@ func (e *endpoint) MaxHeaderLength() uint16 {\nreturn e.nic.MaxHeaderLength() + header.IPv6MinimumSize\n}\n-func (e *endpoint) addIPHeader(srcAddr, dstAddr tcpip.Address, pkt *stack.PacketBuffer, params stack.NetworkHeaderParams, extensionHeaders header.IPv6ExtHdrSerializer) *tcpip.Error {\n+func addIPHeader(srcAddr, dstAddr tcpip.Address, pkt *stack.PacketBuffer, params stack.NetworkHeaderParams, extensionHeaders header.IPv6ExtHdrSerializer) *tcpip.Error {\nextHdrsLen := extensionHeaders.Length()\nlength := pkt.Size() + extensionHeaders.Length()\nif length > math.MaxUint16 {\n@@ -625,7 +625,7 @@ func (e *endpoint) handleFragments(r *stack.Route, gso *stack.GSO, networkMTU ui\n// WritePacket writes a packet to the given destination address and protocol.\nfunc (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.NetworkHeaderParams, pkt *stack.PacketBuffer) *tcpip.Error {\n- if err := e.addIPHeader(r.LocalAddress, r.RemoteAddress, pkt, params, nil /* extensionHeaders */); err != nil {\n+ if err := addIPHeader(r.LocalAddress, r.RemoteAddress, pkt, params, nil /* extensionHeaders */); err != nil {\nreturn err\n}\n@@ -718,7 +718,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\nstats := e.stats.ip\nlinkMTU := e.nic.MTU()\nfor pb := pkts.Front(); pb != nil; pb = pb.Next() {\n- if err := e.addIPHeader(r.LocalAddress, r.RemoteAddress, pb, params, nil /* extensionHeaders */); err != nil {\n+ if err := addIPHeader(r.LocalAddress, r.RemoteAddress, pb, params, nil /* extensionHeaders */); err != nil {\nreturn 0, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/mld.go", "new_path": "pkg/tcpip/network/ipv6/mld.go", "diff": "@@ -249,7 +249,7 @@ func (mld *mldState) writePacket(destAddress, groupAddress tcpip.Address, mldTyp\nData: buffer.View(icmp).ToVectorisedView(),\n})\n- if err := mld.ep.addIPHeader(localAddress, destAddress, pkt, stack.NetworkHeaderParams{\n+ if err := addIPHeader(localAddress, destAddress, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.MLDHopLimit,\n}, extensionHeaders); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -732,7 +732,7 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address, addressEndpoint stack.Add\n})\nsent := ndp.ep.stats.icmp.packetsSent\n- if err := ndp.ep.addIPHeader(header.IPv6Any, snmc, pkt, stack.NetworkHeaderParams{\n+ if err := addIPHeader(header.IPv6Any, snmc, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n}, nil /* extensionHeaders */); err != nil {\n@@ -1857,7 +1857,7 @@ func (ndp *ndpState) startSolicitingRouters() {\n})\nsent := ndp.ep.stats.icmp.packetsSent\n- if err := ndp.ep.addIPHeader(localAddr, header.IPv6AllRoutersMulticastAddress, pkt, stack.NetworkHeaderParams{\n+ if err := addIPHeader(localAddr, header.IPv6AllRoutersMulticastAddress, pkt, stack.NetworkHeaderParams{\nProtocol: header.ICMPv6ProtocolNumber,\nTTL: header.NDPHopLimit,\n}, nil /* extensionHeaders */); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -638,18 +638,12 @@ func TestNeighorSolicitationResponse(t *testing.T) {\nt.Fatal(\"expected an NDP NS response\")\n}\n- if p.Route.LocalAddress != nicAddr {\n- t.Errorf(\"got p.Route.LocalAddress = %s, want = %s\", p.Route.LocalAddress, nicAddr)\n- }\n- if p.Route.LocalLinkAddress != nicLinkAddr {\n- t.Errorf(\"p.Route.LocalLinkAddress = %s, want = %s\", p.Route.LocalLinkAddress, nicLinkAddr)\n- }\nrespNSDst := header.SolicitedNodeAddr(test.nsSrc)\n- if p.Route.RemoteAddress != respNSDst {\n- t.Errorf(\"got p.Route.RemoteAddress = %s, want = %s\", p.Route.RemoteAddress, respNSDst)\n- }\n- if want := header.EthernetAddressFromMulticastIPv6Address(respNSDst); p.Route.RemoteLinkAddress != want {\n- t.Errorf(\"got p.Route.RemoteLinkAddress = %s, want = %s\", p.Route.RemoteLinkAddress, want)\n+ var want stack.RouteInfo\n+ want.NetProto = ProtocolNumber\n+ want.RemoteLinkAddress = header.EthernetAddressFromMulticastIPv6Address(respNSDst)\n+ if diff := cmp.Diff(want, p.Route, cmp.AllowUnexported(want)); diff != \"\" {\n+ t.Errorf(\"route info mismatch (-want +got):\\n%s\", diff)\n}\nchecker.IPv6(t, stack.PayloadSince(p.Pkt.NetworkHeader()),\n" } ]
Go
Apache License 2.0
google/gvisor
Do not use stack.Route to send NDP NS When sending packets through a stack.Route, we attempt to perform link resolution. Neighbor Solicitation messages do not need link resolution to be performed so send the packets out the interface directly instead. PiperOrigin-RevId: 353967435
259,896
26.01.2021 18:02:53
28,800
8e660447410117edd49f41f7aa758e49254ae2d5
Initialize the send buffer handler in endpoint creation. This CL will initialize the function handler used for getting the send buffer size limits during endpoint creation and does not require the caller of SetSendBufferSize(..) to know the endpoint type(tcp/udp/..)
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1615,20 +1615,15 @@ func setSockOptSocket(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, nam\nreturn syserr.ErrInvalidArgument\n}\n- family, skType, skProto := s.Type()\n+ family, _, _ := s.Type()\n// TODO(gvisor.dev/issue/5132): We currently do not support\n// setting this option for unix sockets.\nif family == linux.AF_UNIX {\nreturn nil\n}\n- getBufferLimits := tcpip.GetStackSendBufferLimits\n- if isTCPSocket(skType, skProto) {\n- getBufferLimits = tcp.GetTCPSendBufferLimits\n- }\n-\nv := usermem.ByteOrder.Uint32(optVal)\n- ep.SocketOptions().SetSendBufferSize(int64(v), true, getBufferLimits)\n+ ep.SocketOptions().SetSendBufferSize(int64(v), true)\nreturn nil\ncase linux.SO_RCVBUF:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/connectioned.go", "new_path": "pkg/sentry/socket/unix/transport/connectioned.go", "diff": "@@ -128,7 +128,7 @@ func newConnectioned(ctx context.Context, stype linux.SockType, uid UniqueIDProv\nidGenerator: uid,\nstype: stype,\n}\n- ep.ops.InitHandler(ep, nil)\n+ ep.ops.InitHandler(ep, nil, nil)\nreturn ep\n}\n@@ -173,7 +173,7 @@ func NewExternal(ctx context.Context, stype linux.SockType, uid UniqueIDProvider\nidGenerator: uid,\nstype: stype,\n}\n- ep.ops.InitHandler(ep, nil)\n+ ep.ops.InitHandler(ep, nil, nil)\nreturn ep\n}\n@@ -296,7 +296,7 @@ func (e *connectionedEndpoint) BidirectionalConnect(ctx context.Context, ce Conn\nidGenerator: e.idGenerator,\nstype: e.stype,\n}\n- ne.ops.InitHandler(ne, nil)\n+ ne.ops.InitHandler(ne, nil, nil)\nreadQueue := &queue{ReaderQueue: ce.WaiterQueue(), WriterQueue: ne.Queue, limit: initialLimit}\nreadQueue.InitRefs()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/connectionless.go", "new_path": "pkg/sentry/socket/unix/transport/connectionless.go", "diff": "@@ -44,7 +44,7 @@ func NewConnectionless(ctx context.Context) Endpoint {\nq := queue{ReaderQueue: ep.Queue, WriterQueue: &waiter.Queue{}, limit: initialLimit}\nq.InitRefs()\nep.receiver = &queueReceiver{readQueue: &q}\n- ep.ops.InitHandler(ep, nil)\n+ ep.ops.InitHandler(ep, nil, nil)\nreturn ep\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/socketops.go", "new_path": "pkg/tcpip/socketops.go", "diff": "@@ -205,6 +205,11 @@ type SocketOptions struct {\n// bindToDevice determines the device to which the socket is bound.\nbindToDevice int32\n+ // getSendBufferLimits provides the handler to get the min, default and\n+ // max size for send buffer. It is initialized at the creation time and\n+ // will not change.\n+ getSendBufferLimits GetSendBufferLimits `state:\"manual\"`\n+\n// sendBufferSize determines the send buffer size for this socket.\nsendBufferSize int64\n@@ -218,9 +223,10 @@ type SocketOptions struct {\n// InitHandler initializes the handler. This must be called before using the\n// socket options utility.\n-func (so *SocketOptions) InitHandler(handler SocketOptionsHandler, stack StackHandler) {\n+func (so *SocketOptions) InitHandler(handler SocketOptionsHandler, stack StackHandler, getSendBufferLimits GetSendBufferLimits) {\nso.handler = handler\nso.stackHandler = stack\n+ so.getSendBufferLimits = getSendBufferLimits\n}\nfunc storeAtomicBool(addr *uint32, v bool) {\n@@ -568,14 +574,17 @@ func (so *SocketOptions) GetSendBufferSize() (int64, *Error) {\n// SetSendBufferSize sets value for SO_SNDBUF option. notify indicates if the\n// stack handler should be invoked to set the send buffer size.\n-func (so *SocketOptions) SetSendBufferSize(sendBufferSize int64, notify bool, getBufferLimits GetSendBufferLimits) {\n- v := sendBufferSize\n- ss := getBufferLimits(so.stackHandler)\n+func (so *SocketOptions) SetSendBufferSize(sendBufferSize int64, notify bool) {\n+ if so.handler.IsUnixSocket() {\n+ return\n+ }\n+ v := sendBufferSize\nif notify {\n// TODO(b/176170271): Notify waiters after size has grown.\n// Make sure the send buffer size is within the min and max\n// allowed.\n+ ss := so.getSendBufferLimits(so.stackHandler)\nmin := int64(ss.Min)\nmax := int64(ss.Max)\n// Validate the send buffer size with min and max values.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_test.go", "new_path": "pkg/tcpip/stack/transport_test.go", "diff": "@@ -70,7 +70,7 @@ func (f *fakeTransportEndpoint) SocketOptions() *tcpip.SocketOptions {\nfunc newFakeTransportEndpoint(proto *fakeTransportProtocol, netProto tcpip.NetworkProtocolNumber, s *stack.Stack) tcpip.Endpoint {\nep := &fakeTransportEndpoint{TransportEndpointInfo: stack.TransportEndpointInfo{NetProto: netProto}, proto: proto, uniqueID: s.UniqueID()}\n- ep.ops.InitHandler(ep, s)\n+ ep.ops.InitHandler(ep, s, tcpip.GetStackSendBufferLimits)\nreturn ep\n}\n@@ -233,7 +233,7 @@ func (f *fakeTransportEndpoint) HandlePacket(id stack.TransportEndpointID, pkt *\npeerAddr: route.RemoteAddress,\nroute: route,\n}\n- ep.ops.InitHandler(ep, f.proto.stack)\n+ ep.ops.InitHandler(ep, f.proto.stack, tcpip.GetStackSendBufferLimits)\nf.acceptQueue = append(f.acceptQueue, ep)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint.go", "new_path": "pkg/tcpip/transport/icmp/endpoint.go", "diff": "@@ -96,13 +96,13 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nstate: stateInitial,\nuniqueID: s.UniqueID(),\n}\n- ep.ops.InitHandler(ep, ep.stack)\n- ep.ops.SetSendBufferSize(32*1024, false /* notify */, tcpip.GetStackSendBufferLimits)\n+ ep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits)\n+ ep.ops.SetSendBufferSize(32*1024, false /* notify */)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\nif err := s.Option(&ss); err == nil {\n- ep.ops.SetSendBufferSize(int64(ss.Default), false /* notify */, tcpip.GetStackSendBufferLimits)\n+ ep.ops.SetSendBufferSize(int64(ss.Default), false /* notify */)\n}\nreturn ep, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/icmp/endpoint_state.go", "new_path": "pkg/tcpip/transport/icmp/endpoint_state.go", "diff": "@@ -69,7 +69,7 @@ func (e *endpoint) afterLoad() {\n// Resume implements tcpip.ResumableEndpoint.Resume.\nfunc (e *endpoint) Resume(s *stack.Stack) {\ne.stack = s\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits)\nif e.state != stateBound && e.state != stateConnected {\nreturn\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint.go", "new_path": "pkg/tcpip/transport/packet/endpoint.go", "diff": "@@ -105,12 +105,12 @@ func NewEndpoint(s *stack.Stack, cooked bool, netProto tcpip.NetworkProtocolNumb\nwaiterQueue: waiterQueue,\nrcvBufSizeMax: 32 * 1024,\n}\n- ep.ops.InitHandler(ep, ep.stack)\n+ ep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\nif err := s.Option(&ss); err == nil {\n- ep.ops.SetSendBufferSize(int64(ss.Default), false /* notify */, tcpip.GetStackSendBufferLimits)\n+ ep.ops.SetSendBufferSize(int64(ss.Default), false /* notify */)\n}\nvar rs stack.ReceiveBufferSizeOption\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/packet/endpoint_state.go", "new_path": "pkg/tcpip/transport/packet/endpoint_state.go", "diff": "@@ -64,7 +64,7 @@ func (ep *endpoint) loadRcvBufSizeMax(max int) {\n// afterLoad is invoked by stateify.\nfunc (ep *endpoint) afterLoad() {\nep.stack = stack.StackFromEnv\n- ep.ops.InitHandler(ep, ep.stack)\n+ ep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits)\n// TODO(gvisor.dev/173): Once bind is supported, choose the right NIC.\nif err := ep.stack.RegisterPacketEndpoint(0, ep.netProto, ep); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint.go", "new_path": "pkg/tcpip/transport/raw/endpoint.go", "diff": "@@ -112,14 +112,14 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProt\nrcvBufSizeMax: 32 * 1024,\nassociated: associated,\n}\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits)\ne.ops.SetHeaderIncluded(!associated)\n- e.ops.SetSendBufferSize(32*1024, false /* notify */, tcpip.GetStackSendBufferLimits)\n+ e.ops.SetSendBufferSize(32*1024, false /* notify */)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\nif err := s.Option(&ss); err == nil {\n- e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */, tcpip.GetStackSendBufferLimits)\n+ e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */)\n}\nvar rs stack.ReceiveBufferSizeOption\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/raw/endpoint_state.go", "new_path": "pkg/tcpip/transport/raw/endpoint_state.go", "diff": "@@ -69,7 +69,7 @@ func (e *endpoint) afterLoad() {\n// Resume implements tcpip.ResumableEndpoint.Resume.\nfunc (e *endpoint) Resume(s *stack.Stack) {\ne.stack = s\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits)\n// If the endpoint is connected, re-connect.\nif e.connected {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -880,14 +880,14 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\nwindowClamp: DefaultReceiveBufferSize,\nmaxSynRetries: DefaultSynRetries,\n}\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, GetTCPSendBufferLimits)\ne.ops.SetMulticastLoop(true)\ne.ops.SetQuickAck(true)\n- e.ops.SetSendBufferSize(DefaultSendBufferSize, false /* notify */, GetTCPSendBufferLimits)\n+ e.ops.SetSendBufferSize(DefaultSendBufferSize, false /* notify */)\nvar ss tcpip.TCPSendBufferSizeRangeOption\nif err := s.TransportProtocolOption(ProtocolNumber, &ss); err == nil {\n- e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */, GetTCPSendBufferLimits)\n+ e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */)\n}\nvar rs tcpip.TCPReceiveBufferSizeRangeOption\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "new_path": "pkg/tcpip/transport/tcp/endpoint_state.go", "diff": "@@ -181,7 +181,7 @@ func (e *endpoint) afterLoad() {\n// Resume implements tcpip.ResumableEndpoint.Resume.\nfunc (e *endpoint) Resume(s *stack.Stack) {\ne.stack = s\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, GetTCPSendBufferLimits)\ne.segmentQueue.thaw()\nepState := e.origEndpointState\nswitch epState {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -4473,7 +4473,7 @@ func TestMinMaxBufferSizes(t *testing.T) {\ncheckRecvBufferSize(t, ep, 200)\n- ep.SocketOptions().SetSendBufferSize(149, true, tcp.GetTCPSendBufferLimits)\n+ ep.SocketOptions().SetSendBufferSize(149, true)\ncheckSendBufferSize(t, ep, 300)\n@@ -4485,7 +4485,7 @@ func TestMinMaxBufferSizes(t *testing.T) {\n// Values above max are capped at max and then doubled.\ncheckRecvBufferSize(t, ep, tcp.DefaultReceiveBufferSize*20*2)\n- ep.SocketOptions().SetSendBufferSize(1+tcp.DefaultSendBufferSize*30, true, tcp.GetTCPSendBufferLimits)\n+ ep.SocketOptions().SetSendBufferSize(1+tcp.DefaultSendBufferSize*30, true)\n// Values above max are capped at max and then doubled.\ncheckSendBufferSize(t, ep, tcp.DefaultSendBufferSize*30*2)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -178,14 +178,14 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\nstate: StateInitial,\nuniqueID: s.UniqueID(),\n}\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits)\ne.ops.SetMulticastLoop(true)\n- e.ops.SetSendBufferSize(32*1024, false /* notify */, tcpip.GetStackSendBufferLimits)\n+ e.ops.SetSendBufferSize(32*1024, false /* notify */)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\nif err := s.Option(&ss); err == nil {\n- e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */, tcpip.GetStackSendBufferLimits)\n+ e.ops.SetSendBufferSize(int64(ss.Default), false /* notify */)\n}\nvar rs stack.ReceiveBufferSizeOption\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint_state.go", "new_path": "pkg/tcpip/transport/udp/endpoint_state.go", "diff": "@@ -91,7 +91,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\ndefer e.mu.Unlock()\ne.stack = s\n- e.ops.InitHandler(e, e.stack)\n+ e.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits)\nfor m := range e.multicastMemberships {\nif err := e.stack.JoinGroup(e.NetProto, m.nicID, m.multicastAddr); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Initialize the send buffer handler in endpoint creation. - This CL will initialize the function handler used for getting the send buffer size limits during endpoint creation and does not require the caller of SetSendBufferSize(..) to know the endpoint type(tcp/udp/..) PiperOrigin-RevId: 353992634
260,023
27.01.2021 12:25:20
28,800
de3c63cd9dd536cf36e29aad381096b7cd061af9
Deflake tcp_zero_window_probe_retransmit_test Fix the test to rely on more deterministic retransmission interval computations by skipping the initial probe transmission time as that can be non-deterministic given arbitrary time taken for the DUT to receive a send command and initiate a send. Fixes
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go", "new_path": "test/packetimpact/tests/tcp_zero_window_probe_retransmit_test.go", "diff": "@@ -66,33 +66,39 @@ func TestZeroWindowProbeRetransmit(t *testing.T) {\nprobeSeq := testbench.Uint32(uint32(*conn.RemoteSeqNum(t) - 1))\nackProbe := testbench.Uint32(uint32(*conn.RemoteSeqNum(t)))\n- startProbeDuration := time.Second\n- current := startProbeDuration\n- first := time.Now()\n// Ask the dut to send out data.\ndut.Send(t, acceptFd, sampleData, 0)\n+\n+ var prev time.Duration\n// Expect the dut to keep the connection alive as long as the remote is\n// acknowledging the zero-window probes.\n- for i := 0; i < 5; i++ {\n+ for i := 1; i <= 5; i++ {\nstart := time.Now()\n// Expect zero-window probe with a timeout which is a function of the typical\n// first retransmission time. The retransmission times is supposed to\n// exponentially increase.\n- if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: probeSeq}, nil, 2*current); err != nil {\n+ if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: probeSeq}, nil, time.Duration(i)*time.Second); err != nil {\nt.Fatalf(\"expected a probe with sequence number %d: loop %d\", probeSeq, i)\n}\n- if i == 0 {\n- startProbeDuration = time.Now().Sub(first)\n- current = 2 * startProbeDuration\n+ if i == 1 {\n+ // Skip the first probe as computing transmit time for that is\n+ // non-deterministic because of the arbitrary time taken for\n+ // the dut to receive a send command and issue a send.\ncontinue\n}\n- // Check if the probes came at exponentially increasing intervals.\n- if got, want := time.Since(start), current-startProbeDuration; got < want {\n+\n+ // Check if the time taken to receive the probe from the dut is\n+ // increasing exponentially. To avoid flakes, use a correction\n+ // factor for the expected duration which accounts for any\n+ // scheduling non-determinism.\n+ const timeCorrection = 200 * time.Millisecond\n+ got := time.Since(start)\n+ if want := (2 * prev) - timeCorrection; prev != 0 && got < want {\nt.Errorf(\"got zero probe %d after %s, want >= %s\", i, got, want)\n}\n+ prev = got\n// Acknowledge the zero-window probes from the dut.\nconn.Send(t, testbench.TCP{AckNum: ackProbe, Flags: testbench.Uint8(header.TCPFlagAck), WindowSize: testbench.Uint16(0)})\n- current *= 2\n}\n// Advertize non-zero window.\nconn.Send(t, testbench.TCP{AckNum: ackProbe, Flags: testbench.Uint8(header.TCPFlagAck)})\n" } ]
Go
Apache License 2.0
google/gvisor
Deflake tcp_zero_window_probe_retransmit_test Fix the test to rely on more deterministic retransmission interval computations by skipping the initial probe transmission time as that can be non-deterministic given arbitrary time taken for the DUT to receive a send command and initiate a send. Fixes #5080 PiperOrigin-RevId: 354146256
259,896
27.01.2021 16:11:49
28,800
99988e45ed651f64e16e2f2663b06b4a1eee50d4
Add support for more fields in netstack for TCP_INFO This CL adds support for the following fields: RTT, RTTVar, RTO send congestion window (sndCwnd) and send slow start threshold (sndSsthresh) congestion control state(CaState) ReorderSeen
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/socket.go", "new_path": "pkg/abi/linux/socket.go", "diff": "@@ -416,6 +416,18 @@ type TCPInfo struct {\nRwndLimited uint64\n// SndBufLimited is the time in microseconds limited by send buffer.\nSndBufLimited uint64\n+\n+ Delievered uint32\n+ DelieveredCe uint32\n+\n+ // BytesSent is RFC4898 tcpEStatsPerfHCDataOctetsOut.\n+ BytesSent uint64\n+ // BytesRetrans is RFC4898 tcpEStatsPerfOctetsRetrans.\n+ BytesRetrans uint64\n+ // DSACKDups is RFC4898 tcpEStatsStackDSACKDups.\n+ DSACKDups uint32\n+ // ReordSeen is the number of reordering events seen.\n+ ReordSeen uint32\n}\n// SizeOfTCPInfo is the binary size of a TCPInfo struct.\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/tcp.go", "new_path": "pkg/abi/linux/tcp.go", "diff": "@@ -59,3 +59,12 @@ const (\nMAX_TCP_KEEPINTVL = 32767\nMAX_TCP_KEEPCNT = 127\n)\n+\n+// Congestion control states from include/uapi/linux/tcp.h.\n+const (\n+ TCP_CA_Open = 0\n+ TCP_CA_Disorder = 1\n+ TCP_CA_CWR = 2\n+ TCP_CA_Recovery = 3\n+ TCP_CA_Loss = 4\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1098,6 +1098,29 @@ func getSockOptTCP(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name,\n// TODO(b/64800844): Translate fields once they are added to\n// tcpip.TCPInfoOption.\ninfo := linux.TCPInfo{}\n+ switch v.CcState {\n+ case tcpip.RTORecovery:\n+ info.CaState = linux.TCP_CA_Loss\n+ case tcpip.FastRecovery, tcpip.SACKRecovery:\n+ info.CaState = linux.TCP_CA_Recovery\n+ case tcpip.Disorder:\n+ info.CaState = linux.TCP_CA_Disorder\n+ case tcpip.Open:\n+ info.CaState = linux.TCP_CA_Open\n+ }\n+ info.RTO = uint32(v.RTO / time.Microsecond)\n+ info.RTT = uint32(v.RTT / time.Microsecond)\n+ info.RTTVar = uint32(v.RTTVar / time.Microsecond)\n+ info.SndSsthresh = v.SndSsthresh\n+ info.SndCwnd = v.SndCwnd\n+\n+ // In netstack reorderSeen is updated only when RACK is enabled.\n+ // We only track whether the reordering is seen, which is\n+ // different than Linux where reorderSeen is not specific to\n+ // RACK and is incremented when a reordering event is seen.\n+ if v.ReorderSeen {\n+ info.ReordSeen = 1\n+ }\n// Linux truncates the output binary to outLen.\nbuf := t.CopyScratchBuffer(info.SizeBytes())\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -993,12 +993,54 @@ type SettableSocketOption interface {\nisSettableSocketOption()\n}\n+// CongestionControlState indicates the current congestion control state for\n+// TCP sender.\n+type CongestionControlState int\n+\n+const (\n+ // Open indicates that the sender is receiving acks in order and\n+ // no loss or dupACK's etc have been detected.\n+ Open CongestionControlState = iota\n+ // RTORecovery indicates that an RTO has occurred and the sender\n+ // has entered an RTO based recovery phase.\n+ RTORecovery\n+ // FastRecovery indicates that the sender has entered FastRecovery\n+ // based on receiving nDupAck's. This state is entered only when\n+ // SACK is not in use.\n+ FastRecovery\n+ // SACKRecovery indicates that the sender has entered SACK based\n+ // recovery.\n+ SACKRecovery\n+ // Disorder indicates the sender either received some SACK blocks\n+ // or dupACK's.\n+ Disorder\n+)\n+\n// TCPInfoOption is used by GetSockOpt to expose TCP statistics.\n//\n// TODO(b/64800844): Add and populate stat fields.\ntype TCPInfoOption struct {\n+ // RTT is the smoothed round trip time.\nRTT time.Duration\n+\n+ // RTTVar is the round trip time variation.\nRTTVar time.Duration\n+\n+ // RTO is the retransmission timeout for the endpoint.\n+ RTO time.Duration\n+\n+ // CcState is the congestion control state.\n+ CcState CongestionControlState\n+\n+ // SndCwnd is the congestion window, in packets.\n+ SndCwnd uint32\n+\n+ // SndSsthresh is the threshold between slow start and congestion\n+ // avoidance.\n+ SndSsthresh uint32\n+\n+ // ReorderSeen indicates if reordering is seen in the endpoint.\n+ ReorderSeen bool\n}\nfunc (*TCPInfoOption) isGettableSocketOption() {}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -2011,20 +2011,34 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\n}\n}\n-// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n- switch o := opt.(type) {\n- case *tcpip.TCPInfoOption:\n- *o = tcpip.TCPInfoOption{}\n+func (e *endpoint) getTCPInfo() tcpip.TCPInfoOption {\n+ info := tcpip.TCPInfoOption{}\ne.LockUser()\nsnd := e.snd\n- e.UnlockUser()\nif snd != nil {\n+ // We do not calculate RTT before sending the data packets. If\n+ // the connection did not send and receive data, then RTT will\n+ // be zero.\nsnd.rtt.Lock()\n- o.RTT = snd.rtt.srtt\n- o.RTTVar = snd.rtt.rttvar\n+ info.RTT = snd.rtt.srtt\n+ info.RTTVar = snd.rtt.rttvar\nsnd.rtt.Unlock()\n+\n+ info.RTO = snd.rto\n+ info.CcState = snd.state\n+ info.SndSsthresh = uint32(snd.sndSsthresh)\n+ info.SndCwnd = uint32(snd.sndCwnd)\n+ info.ReorderSeen = snd.rc.reorderSeen\n}\n+ e.UnlockUser()\n+ return info\n+}\n+\n+// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n+func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) *tcpip.Error {\n+ switch o := opt.(type) {\n+ case *tcpip.TCPInfoOption:\n+ *o = e.getTCPInfo()\ncase *tcpip.KeepaliveIdleOption:\ne.keepalive.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack.go", "new_path": "pkg/tcpip/transport/tcp/rack.go", "diff": "@@ -162,7 +162,7 @@ func (s *sender) shouldSchedulePTO() bool {\n// The connection supports SACK.\ns.ep.sackPermitted &&\n// The connection is not in loss recovery.\n- (s.state != RTORecovery && s.state != SACKRecovery) &&\n+ (s.state != tcpip.RTORecovery && s.state != tcpip.SACKRecovery) &&\n// The connection has no SACKed sequences in the SACK scoreboard.\ns.ep.scoreboard.Sacked() == 0\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -48,28 +48,6 @@ const (\nMaxRetries = 15\n)\n-// ccState indicates the current congestion control state for this sender.\n-type ccState int\n-\n-const (\n- // Open indicates that the sender is receiving acks in order and\n- // no loss or dupACK's etc have been detected.\n- Open ccState = iota\n- // RTORecovery indicates that an RTO has occurred and the sender\n- // has entered an RTO based recovery phase.\n- RTORecovery\n- // FastRecovery indicates that the sender has entered FastRecovery\n- // based on receiving nDupAck's. This state is entered only when\n- // SACK is not in use.\n- FastRecovery\n- // SACKRecovery indicates that the sender has entered SACK based\n- // recovery.\n- SACKRecovery\n- // Disorder indicates the sender either received some SACK blocks\n- // or dupACK's.\n- Disorder\n-)\n-\n// congestionControl is an interface that must be implemented by any supported\n// congestion control algorithm.\ntype congestionControl interface {\n@@ -204,7 +182,7 @@ type sender struct {\nmaxSentAck seqnum.Value\n// state is the current state of congestion control for this endpoint.\n- state ccState\n+ state tcpip.CongestionControlState\n// cc is the congestion control algorithm in use for this sender.\ncc congestionControl\n@@ -593,7 +571,7 @@ func (s *sender) retransmitTimerExpired() bool {\ns.leaveRecovery()\n}\n- s.state = RTORecovery\n+ s.state = tcpip.RTORecovery\ns.cc.HandleRTOExpired()\n// Mark the next segment to be sent as the first unacknowledged one and\n@@ -1018,7 +996,7 @@ func (s *sender) sendData() {\n// \"A TCP SHOULD set cwnd to no more than RW before beginning\n// transmission if the TCP has not sent data in the interval exceeding\n// the retrasmission timeout.\"\n- if !s.fr.active && s.state != RTORecovery && time.Now().Sub(s.lastSendTime) > s.rto {\n+ if !s.fr.active && s.state != tcpip.RTORecovery && time.Now().Sub(s.lastSendTime) > s.rto {\nif s.sndCwnd > InitialCwnd {\ns.sndCwnd = InitialCwnd\n}\n@@ -1062,14 +1040,14 @@ func (s *sender) enterRecovery() {\ns.fr.highRxt = s.sndUna\ns.fr.rescueRxt = s.sndUna\nif s.ep.sackPermitted {\n- s.state = SACKRecovery\n+ s.state = tcpip.SACKRecovery\ns.ep.stack.Stats().TCP.SACKRecovery.Increment()\n// Set TLPRxtOut to false according to\n// https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.6.1.\ns.rc.tlpRxtOut = false\nreturn\n}\n- s.state = FastRecovery\n+ s.state = tcpip.FastRecovery\ns.ep.stack.Stats().TCP.FastRecovery.Increment()\n}\n@@ -1166,7 +1144,7 @@ func (s *sender) detectLoss(seg *segment) (fastRetransmit bool) {\ns.fr.highRxt = s.sndUna - 1\n// Do run SetPipe() to calculate the outstanding segments.\ns.SetPipe()\n- s.state = Disorder\n+ s.state = tcpip.Disorder\nreturn false\n}\n@@ -1464,7 +1442,7 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\nif !s.fr.active {\ns.cc.Update(originalOutstanding - s.outstanding)\nif s.fr.last.LessThan(s.sndUna) {\n- s.state = Open\n+ s.state = tcpip.Open\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/defs.bzl", "new_path": "test/packetimpact/runner/defs.bzl", "diff": "@@ -281,6 +281,9 @@ ALL_TESTS = [\nname = \"tcp_rack\",\nexpect_netstack_failure = True,\n),\n+ PacketimpactTestInfo(\n+ name = \"tcp_info\",\n+ ),\n]\ndef validate_all_tests():\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -390,6 +390,19 @@ packetimpact_testbench(\n],\n)\n+packetimpact_testbench(\n+ name = \"tcp_info\",\n+ srcs = [\"tcp_info_test.go\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/usermem\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\nvalidate_all_tests()\n[packetimpact_go_test(\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetimpact/tests/tcp_info_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 tcp_info_test\n+\n+import (\n+ \"flag\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+ \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func init() {\n+ testbench.Initialize(flag.CommandLine)\n+}\n+\n+func TestTCPInfo(t *testing.T) {\n+ // Create a socket, listen, TCP connect, and accept.\n+ dut := testbench.NewDUT(t)\n+ listenFD, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ defer dut.Close(t, listenFD)\n+\n+ conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\n+ defer conn.Close(t)\n+ conn.Connect(t)\n+\n+ acceptFD, _ := dut.Accept(t, listenFD)\n+ defer dut.Close(t, acceptFD)\n+\n+ // Send and receive sample data.\n+ sampleData := []byte(\"Sample Data\")\n+ samplePayload := &testbench.Payload{Bytes: sampleData}\n+ dut.Send(t, acceptFD, sampleData, 0)\n+ if _, err := conn.ExpectData(t, &testbench.TCP{}, samplePayload, time.Second); err != nil {\n+ t.Fatalf(\"expected a packet with payload %v: %s\", samplePayload, err)\n+ }\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck)})\n+\n+ info := linux.TCPInfo{}\n+ infoBytes := dut.GetSockOpt(t, acceptFD, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ binary.Unmarshal(infoBytes, usermem.ByteOrder, &info)\n+\n+ rtt := time.Duration(info.RTT) * time.Microsecond\n+ rttvar := time.Duration(info.RTTVar) * time.Microsecond\n+ rto := time.Duration(info.RTO) * time.Microsecond\n+ if rtt == 0 || rttvar == 0 || rto == 0 {\n+ t.Errorf(\"expected rtt(%v), rttvar(%v) and rto(%v) to be greater than zero\", rtt, rttvar, rto)\n+ }\n+ if info.ReordSeen != 0 {\n+ t.Errorf(\"expected the connection to not have any reordering, got: %v want: 0\", info.ReordSeen)\n+ }\n+ if info.SndCwnd == 0 {\n+ t.Errorf(\"expected send congestion window to be greater than zero\")\n+ }\n+ if info.CaState != linux.TCP_CA_Open {\n+ t.Errorf(\"expected the connection to be in open state, got: %v want: %v\", info.CaState, linux.TCP_CA_Open)\n+ }\n+\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ // Check the congestion control state and send congestion window after\n+ // retransmission timeout.\n+ seq := testbench.Uint32(uint32(*conn.RemoteSeqNum(t)))\n+ dut.Send(t, acceptFD, sampleData, 0)\n+ if _, err := conn.ExpectData(t, &testbench.TCP{}, samplePayload, time.Second); err != nil {\n+ t.Fatalf(\"expected a packet with payload %v: %s\", samplePayload, err)\n+ }\n+\n+ // Expect retransmission of the packet within 1.5*RTO.\n+ timeout := time.Duration(float64(info.RTO)*1.5) * time.Microsecond\n+ if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: seq}, samplePayload, timeout); err != nil {\n+ t.Fatalf(\"expected a packet with payload %v: %s\", samplePayload, err)\n+ }\n+\n+ info = linux.TCPInfo{}\n+ infoBytes = dut.GetSockOpt(t, acceptFD, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ binary.Unmarshal(infoBytes, usermem.ByteOrder, &info)\n+ if info.CaState != linux.TCP_CA_Loss {\n+ t.Errorf(\"expected the connection to be in loss recovery, got: %v want: %v\", info.CaState, linux.TCP_CA_Loss)\n+ }\n+ if info.SndCwnd != 1 {\n+ t.Errorf(\"expected send congestion window to be 1, got: %v %v\", info.SndCwnd)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "diff": "@@ -65,6 +65,33 @@ TEST_P(TCPSocketPairTest, ZeroTcpInfoSucceeds) {\nSyscallSucceeds());\n}\n+TEST_P(TCPSocketPairTest, CheckTcpInfoFields) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char buf[10] = {};\n+ ASSERT_THAT(RetryEINTR(send)(sockets->first_fd(), buf, sizeof(buf), 0),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ // Wait until second_fd sees the data and then recv it.\n+ struct pollfd poll_fd = {sockets->second_fd(), POLLIN, 0};\n+ constexpr int kPollTimeoutMs = 2000; // Wait up to 2 seconds for the data.\n+ ASSERT_THAT(RetryEINTR(poll)(&poll_fd, 1, kPollTimeoutMs),\n+ SyscallSucceedsWithValue(1));\n+\n+ ASSERT_THAT(RetryEINTR(recv)(sockets->second_fd(), buf, sizeof(buf), 0),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ struct tcp_info opt = {};\n+ socklen_t optLen = sizeof(opt);\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), SOL_TCP, TCP_INFO, &opt, &optLen),\n+ SyscallSucceeds());\n+\n+ // Validates the received tcp_info fields.\n+ EXPECT_EQ(opt.tcpi_ca_state, 0);\n+ EXPECT_GT(opt.tcpi_snd_cwnd, 0);\n+ EXPECT_GT(opt.tcpi_rto, 0);\n+}\n+\n// This test validates that an RST is sent instead of a FIN when data is\n// unread on calls to close(2).\nTEST_P(TCPSocketPairTest, RSTSentOnCloseWithUnreadData) {\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for more fields in netstack for TCP_INFO This CL adds support for the following fields: - RTT, RTTVar, RTO - send congestion window (sndCwnd) and send slow start threshold (sndSsthresh) - congestion control state(CaState) - ReorderSeen PiperOrigin-RevId: 354195361
259,898
28.01.2021 12:29:18
28,800
bc4039353d5b744871ee61cf4d76b3fe6f783ba7
Make tcp_noaccept_close_rst more robust There used to be a race condition where we may call Close before the connection is established. Adding poll support so that we can eliminate this kind of race. Startblock: has LGTM from iyerm and then add reviewer tamird
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/dut/BUILD", "new_path": "test/packetimpact/dut/BUILD", "diff": "@@ -14,6 +14,7 @@ cc_binary(\ngrpcpp,\n\"//test/packetimpact/proto:posix_server_cc_grpc_proto\",\n\"//test/packetimpact/proto:posix_server_cc_proto\",\n+ \"@com_google_absl//absl/strings:str_format\",\n],\n)\n@@ -24,5 +25,6 @@ cc_binary(\ngrpcpp,\n\"//test/packetimpact/proto:posix_server_cc_grpc_proto\",\n\"//test/packetimpact/proto:posix_server_cc_proto\",\n+ \"@com_google_absl//absl/strings:str_format\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/dut/posix_server.cc", "new_path": "test/packetimpact/dut/posix_server.cc", "diff": "#include <getopt.h>\n#include <netdb.h>\n#include <netinet/in.h>\n+#include <poll.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"include/grpcpp/security/server_credentials.h\"\n#include \"include/grpcpp/server_builder.h\"\n#include \"include/grpcpp/server_context.h\"\n+#include \"absl/strings/str_format.h\"\n#include \"test/packetimpact/proto/posix_server.grpc.pb.h\"\n#include \"test/packetimpact/proto/posix_server.pb.h\"\n@@ -256,6 +258,44 @@ class PosixImpl final : public posix_server::Posix::Service {\nreturn ::grpc::Status::OK;\n}\n+ ::grpc::Status Poll(::grpc::ServerContext *context,\n+ const ::posix_server::PollRequest *request,\n+ ::posix_server::PollResponse *response) override {\n+ std::vector<struct pollfd> pfds;\n+ pfds.reserve(request->pfds_size());\n+ for (const auto &pfd : request->pfds()) {\n+ pfds.push_back({\n+ .fd = pfd.fd(),\n+ .events = static_cast<short>(pfd.events()),\n+ });\n+ }\n+ int ret = ::poll(pfds.data(), pfds.size(), request->timeout_millis());\n+\n+ response->set_ret(ret);\n+ if (ret < 0) {\n+ response->set_errno_(errno);\n+ } else {\n+ // Only pollfds that have non-empty revents are returned, the client can't\n+ // rely on indexes of the request array.\n+ for (const auto &pfd : pfds) {\n+ if (pfd.revents) {\n+ auto *proto_pfd = response->add_pfds();\n+ proto_pfd->set_fd(pfd.fd);\n+ proto_pfd->set_events(pfd.revents);\n+ }\n+ }\n+ if (int ready = response->pfds_size(); ret != ready) {\n+ return ::grpc::Status(\n+ ::grpc::StatusCode::INTERNAL,\n+ absl::StrFormat(\n+ \"poll's return value(%d) doesn't match the number of \"\n+ \"file descriptors that are actually ready(%d)\",\n+ ret, ready));\n+ }\n+ }\n+ return ::grpc::Status::OK;\n+ }\n+\n::grpc::Status Send(::grpc::ServerContext *context,\nconst ::posix_server::SendRequest *request,\n::posix_server::SendResponse *response) override {\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/proto/posix_server.proto", "new_path": "test/packetimpact/proto/posix_server.proto", "diff": "@@ -142,6 +142,25 @@ message ListenResponse {\nint32 errno_ = 2; // \"errno\" may fail to compile in c++.\n}\n+// The events field is overloaded: when used for request, it is copied into the\n+// events field of posix struct pollfd; when used for response, it is filled by\n+// the revents field from the posix struct pollfd.\n+message PollFd {\n+ int32 fd = 1;\n+ uint32 events = 2;\n+}\n+\n+message PollRequest {\n+ repeated PollFd pfds = 1;\n+ int32 timeout_millis = 2;\n+}\n+\n+message PollResponse {\n+ int32 ret = 1;\n+ int32 errno_ = 2; // \"errno\" may fail to compile in c++.\n+ repeated PollFd pfds = 3;\n+}\n+\nmessage SendRequest {\nint32 sockfd = 1;\nbytes buf = 2;\n@@ -226,6 +245,10 @@ service Posix {\nrpc GetSockOpt(GetSockOptRequest) returns (GetSockOptResponse);\n// Call listen() on the DUT.\nrpc Listen(ListenRequest) returns (ListenResponse);\n+ // Call poll() on the DUT. Only pollfds that have non-empty revents are\n+ // returned, the only way to tie the response back to the original request\n+ // is using the fd number.\n+ rpc Poll(PollRequest) returns (PollResponse);\n// Call send() on the DUT.\nrpc Send(SendRequest) returns (SendResponse);\n// Call sendto() on the DUT.\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/testbench/dut.go", "new_path": "test/packetimpact/testbench/dut.go", "diff": "@@ -486,6 +486,56 @@ func (dut *DUT) ListenWithErrno(ctx context.Context, t *testing.T, sockfd, backl\nreturn resp.GetRet(), syscall.Errno(resp.GetErrno_())\n}\n+// Poll calls poll on the DUT and causes a fatal test failure if it doesn't\n+// succeed. If more control over error handling is needed, use PollWithErrno.\n+// Only pollfds with non-empty revents are returned, the only way to tie the\n+// response back to the original request is using the fd number.\n+func (dut *DUT) Poll(t *testing.T, pfds []unix.PollFd, timeout time.Duration) []unix.PollFd {\n+ t.Helper()\n+\n+ ctx := context.Background()\n+ var cancel context.CancelFunc\n+ if timeout >= 0 {\n+ ctx, cancel = context.WithTimeout(ctx, timeout+RPCTimeout)\n+ defer cancel()\n+ }\n+ ret, result, err := dut.PollWithErrno(ctx, t, pfds, timeout)\n+ if ret < 0 {\n+ t.Fatalf(\"failed to poll: %s\", err)\n+ }\n+ return result\n+}\n+\n+// PollWithErrno calls poll on the DUT.\n+func (dut *DUT) PollWithErrno(ctx context.Context, t *testing.T, pfds []unix.PollFd, timeout time.Duration) (int32, []unix.PollFd, error) {\n+ t.Helper()\n+\n+ req := pb.PollRequest{\n+ TimeoutMillis: int32(timeout.Milliseconds()),\n+ }\n+ for _, pfd := range pfds {\n+ req.Pfds = append(req.Pfds, &pb.PollFd{\n+ Fd: pfd.Fd,\n+ Events: uint32(pfd.Events),\n+ })\n+ }\n+ resp, err := dut.posixServer.Poll(ctx, &req)\n+ if err != nil {\n+ t.Fatalf(\"failed to call Poll: %s\", err)\n+ }\n+ if ret, npfds := resp.GetRet(), len(resp.GetPfds()); ret >= 0 && int(ret) != npfds {\n+ t.Fatalf(\"nonsensical poll response: ret(%d) != len(pfds)(%d)\", ret, npfds)\n+ }\n+ var result []unix.PollFd\n+ for _, protoPfd := range resp.GetPfds() {\n+ result = append(result, unix.PollFd{\n+ Fd: protoPfd.GetFd(),\n+ Revents: int16(protoPfd.GetEvents()),\n+ })\n+ }\n+ return resp.GetRet(), result, syscall.Errno(resp.GetErrno_())\n+}\n+\n// Send calls send on the DUT and causes a fatal test failure if it doesn't\n// succeed. If more control over the timeout or error handling is needed, use\n// SendWithErrno.\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_noaccept_close_rst_test.go", "new_path": "test/packetimpact/tests/tcp_noaccept_close_rst_test.go", "diff": "@@ -34,6 +34,21 @@ func TestTcpNoAcceptCloseReset(t *testing.T) {\nconn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\nconn.Connect(t)\ndefer conn.Close(t)\n+ // We need to wait for POLLIN event on listenFd to know the connection is\n+ // established. Otherwise there could be a race when we issue the Close\n+ // command prior to the DUT receiving the last ack of the handshake and\n+ // it will only respond RST instead of RST+ACK.\n+ timeout := time.Second\n+ pfds := dut.Poll(t, []unix.PollFd{{Fd: listenFd, Events: unix.POLLIN}}, timeout)\n+ if n := len(pfds); n != 1 {\n+ t.Fatalf(\"poll returned %d ready file descriptors, expected 1\", n)\n+ }\n+ if readyFd := pfds[0].Fd; readyFd != listenFd {\n+ t.Fatalf(\"poll returned an fd %d that was not requested (%d)\", readyFd, listenFd)\n+ }\n+ if got, want := pfds[0].Revents, int16(unix.POLLIN); got&want == 0 {\n+ t.Fatalf(\"poll returned no events in our interest, got: %#b, want: %#b\", got, want)\n+ }\ndut.Close(t, listenFd)\nif _, err := conn.Expect(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagRst | header.TCPFlagAck)}, 1*time.Second); err != nil {\nt.Fatalf(\"expected a RST-ACK packet but got none: %s\", err)\n" } ]
Go
Apache License 2.0
google/gvisor
Make tcp_noaccept_close_rst more robust There used to be a race condition where we may call Close before the connection is established. Adding poll support so that we can eliminate this kind of race. Startblock: has LGTM from iyerm and then add reviewer tamird PiperOrigin-RevId: 354369130
259,907
28.01.2021 13:51:38
28,800
62a37034f0185979d71f15bae38815309bd07f03
[vfs] Fix rename implementation in OrderedChildren. Fixes as there is just 1 writable user using OrderedChildren's rename, unlink and rmdir (kernfs.syntheticDirectory) but it doesn't support the sticky bit yet. Fuse which is the other writable user implements its own Inode operations.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -371,6 +371,8 @@ type OrderedChildrenOptions struct {\n// OrderedChildren may modify the tracked children. This applies to\n// operations related to rename, unlink and rmdir. If an OrderedChildren is\n// not writable, these operations all fail with EPERM.\n+ //\n+ // Note that writable users must implement the sticky bit (I_SVTX).\nWritable bool\n}\n@@ -556,7 +558,6 @@ func (o *OrderedChildren) Unlink(ctx context.Context, name string, child Inode)\nreturn err\n}\n- // TODO(gvisor.dev/issue/3027): Check sticky bit before removing.\no.removeLocked(name)\nreturn nil\n}\n@@ -603,8 +604,8 @@ func (o *OrderedChildren) Rename(ctx context.Context, oldname, newname string, c\nif err := o.checkExistingLocked(oldname, child); err != nil {\nreturn err\n}\n+ o.removeLocked(oldname)\n- // TODO(gvisor.dev/issue/3027): Check sticky bit before removing.\ndst.replaceChildLocked(ctx, newname, child)\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[vfs] Fix rename implementation in OrderedChildren. Fixes #3027 as there is just 1 writable user using OrderedChildren's rename, unlink and rmdir (kernfs.syntheticDirectory) but it doesn't support the sticky bit yet. Fuse which is the other writable user implements its own Inode operations. PiperOrigin-RevId: 354386522
260,004
28.01.2021 17:05:44
28,800
56fb2ec1194bff7c57c7bbb84b7b74f63142b915
Do not use clockwork for faketime Clockwork does not support timers being reset/stopped from different goroutines. Our current use of clockwork causes data races and gotsan complains about clockwork. This change uses our own implementation of faketime, avoiding data races.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/faketime/BUILD", "new_path": "pkg/tcpip/faketime/BUILD", "diff": "@@ -6,10 +6,7 @@ go_library(\nname = \"faketime\",\nsrcs = [\"faketime.go\"],\nvisibility = [\"//visibility:public\"],\n- deps = [\n- \"//pkg/tcpip\",\n- \"@com_github_dpjacques_clockwork//:go_default_library\",\n- ],\n+ deps = [\"//pkg/tcpip\"],\n)\ngo_test(\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/faketime/faketime.go", "new_path": "pkg/tcpip/faketime/faketime.go", "diff": "@@ -17,10 +17,10 @@ package faketime\nimport (\n\"container/heap\"\n+ \"fmt\"\n\"sync\"\n\"time\"\n- \"github.com/dpjacques/clockwork\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n@@ -44,38 +44,85 @@ func (*NullClock) AfterFunc(time.Duration, func()) tcpip.Timer {\nreturn nil\n}\n+type notificationChannels struct {\n+ mu struct {\n+ sync.Mutex\n+\n+ ch []<-chan struct{}\n+ }\n+}\n+\n+func (n *notificationChannels) add(ch <-chan struct{}) {\n+ n.mu.Lock()\n+ defer n.mu.Unlock()\n+ n.mu.ch = append(n.mu.ch, ch)\n+}\n+\n+// wait returns once all the notification channels are readable.\n+//\n+// Channels that are added while waiting on existing channels will be waited on\n+// as well.\n+func (n *notificationChannels) wait() {\n+ for {\n+ n.mu.Lock()\n+ ch := n.mu.ch\n+ n.mu.ch = nil\n+ n.mu.Unlock()\n+\n+ if len(ch) == 0 {\n+ break\n+ }\n+\n+ for _, c := range ch {\n+ <-c\n+ }\n+ }\n+}\n+\n// ManualClock implements tcpip.Clock and only advances manually with Advance\n// method.\ntype ManualClock struct {\n- clock clockwork.FakeClock\n+ // runningTimers tracks the completion of timer callbacks that began running\n+ // immediately upon their scheduling. It is used to ensure the proper ordering\n+ // of timer callback dispatch.\n+ runningTimers notificationChannels\n+\n+ mu struct {\n+ sync.RWMutex\n- // mu protects the fields below.\n- mu sync.RWMutex\n+ // now is the current (fake) time of the clock.\n+ now time.Time\n- // times is min-heap of times. A heap is used for quick retrieval of the next\n- // upcoming time of scheduled work.\n- times *timeHeap\n+ // times is min-heap of times.\n+ times timeHeap\n- // waitGroups stores one WaitGroup for all work scheduled to execute at the\n- // same time via AfterFunc. This allows parallel execution of all functions\n- // passed to AfterFunc scheduled for the same time.\n- waitGroups map[time.Time]*sync.WaitGroup\n+ // timers holds the timers scheduled for each time.\n+ timers map[time.Time]map[*manualTimer]struct{}\n+ }\n}\n// NewManualClock creates a new ManualClock instance.\nfunc NewManualClock() *ManualClock {\n- return &ManualClock{\n- clock: clockwork.NewFakeClock(),\n- times: &timeHeap{},\n- waitGroups: make(map[time.Time]*sync.WaitGroup),\n- }\n+ c := &ManualClock{}\n+\n+ c.mu.Lock()\n+ defer c.mu.Unlock()\n+\n+ // Set the initial time to a non-zero value since the zero value is used to\n+ // detect inactive timers.\n+ c.mu.now = time.Unix(0, 0)\n+ c.mu.timers = make(map[time.Time]map[*manualTimer]struct{})\n+\n+ return c\n}\nvar _ tcpip.Clock = (*ManualClock)(nil)\n// NowNanoseconds implements tcpip.Clock.NowNanoseconds.\nfunc (mc *ManualClock) NowNanoseconds() int64 {\n- return mc.clock.Now().UnixNano()\n+ mc.mu.RLock()\n+ defer mc.mu.RUnlock()\n+ return mc.mu.now.UnixNano()\n}\n// NowMonotonic implements tcpip.Clock.NowMonotonic.\n@@ -85,128 +132,203 @@ func (mc *ManualClock) NowMonotonic() int64 {\n// AfterFunc implements tcpip.Clock.AfterFunc.\nfunc (mc *ManualClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {\n- until := mc.clock.Now().Add(d)\n- wg := mc.addWait(until)\n- return &manualTimer{\n+ mt := &manualTimer{\nclock: mc,\n- until: until,\n- timer: mc.clock.AfterFunc(d, func() {\n- defer wg.Done()\n- f()\n- }),\n+ f: f,\n}\n+\n+ mc.mu.Lock()\n+ defer mc.mu.Unlock()\n+\n+ mt.mu.Lock()\n+ defer mt.mu.Unlock()\n+\n+ mc.resetTimerLocked(mt, d)\n+ return mt\n}\n-// addWait adds an additional wait to the WaitGroup for parallel execution of\n-// all work scheduled for t. Returns a reference to the WaitGroup modified.\n-func (mc *ManualClock) addWait(t time.Time) *sync.WaitGroup {\n- mc.mu.RLock()\n- wg, ok := mc.waitGroups[t]\n- mc.mu.RUnlock()\n+// resetTimerLocked schedules a timer to be fired after the given duration.\n+//\n+// Precondition: mc.mu and mt.mu must be locked.\n+func (mc *ManualClock) resetTimerLocked(mt *manualTimer, d time.Duration) {\n+ if !mt.mu.firesAt.IsZero() {\n+ panic(\"tried to reset an active timer\")\n+ }\n+\n+ t := mc.mu.now.Add(d)\n+\n+ if !mc.mu.now.Before(t) {\n+ // If the timer is scheduled to fire immediately, call its callback\n+ // in a new goroutine immediately.\n+ //\n+ // It needs to be called in its own goroutine to escape its current\n+ // execution context - like an actual timer.\n+ ch := make(chan struct{})\n+ mc.runningTimers.add(ch)\n+\n+ go func() {\n+ defer close(ch)\n+\n+ mt.f()\n+ }()\n- if ok {\n- wg.Add(1)\n- return wg\n+ return\n}\n- mc.mu.Lock()\n- heap.Push(mc.times, t)\n- mc.mu.Unlock()\n+ mt.mu.firesAt = t\n- wg = &sync.WaitGroup{}\n- wg.Add(1)\n+ timers, ok := mc.mu.timers[t]\n+ if !ok {\n+ timers = make(map[*manualTimer]struct{})\n+ mc.mu.timers[t] = timers\n+ heap.Push(&mc.mu.times, t)\n+ }\n- mc.mu.Lock()\n- mc.waitGroups[t] = wg\n- mc.mu.Unlock()\n+ timers[mt] = struct{}{}\n+}\n+\n+// stopTimerLocked stops a timer from firing.\n+//\n+// Precondition: mc.mu and mt.mu must be locked.\n+func (mc *ManualClock) stopTimerLocked(mt *manualTimer) {\n+ t := mt.mu.firesAt\n+ mt.mu.firesAt = time.Time{}\n- return wg\n+ if t.IsZero() {\n+ panic(\"tried to stop an inactive timer\")\n}\n-// removeWait removes a wait from the WaitGroup for parallel execution of all\n-// work scheduled for t.\n-func (mc *ManualClock) removeWait(t time.Time) {\n- mc.mu.RLock()\n- defer mc.mu.RUnlock()\n+ timers, ok := mc.mu.timers[t]\n+ if !ok {\n+ err := fmt.Sprintf(\"tried to stop an active timer but the clock does not have anything scheduled for the timer @ t = %s %p\\nScheduled timers @:\", t.UTC(), mt)\n+ for t := range mc.mu.timers {\n+ err += fmt.Sprintf(\"%s\\n\", t.UTC())\n+ }\n+ panic(err)\n+ }\n+\n+ if _, ok := timers[mt]; !ok {\n+ panic(fmt.Sprintf(\"did not have an entry in timers for an active timer @ t = %s\", t.UTC()))\n+ }\n+\n+ delete(timers, mt)\n- wg := mc.waitGroups[t]\n- wg.Done()\n+ if len(timers) == 0 {\n+ delete(mc.mu.timers, t)\n+ }\n}\n// Advance executes all work that have been scheduled to execute within d from\n// the current time. Blocks until all work has completed execution.\nfunc (mc *ManualClock) Advance(d time.Duration) {\n- // Block until all the work is done\n- until := mc.clock.Now().Add(d)\n- for {\n+ // We spawn goroutines for timers that were scheduled to fire at the time of\n+ // being reset. Wait for those goroutines to complete before proceeding so\n+ // that timer callbacks are called in the right order.\n+ mc.runningTimers.wait()\n+\nmc.mu.Lock()\n- if mc.times.Len() == 0 {\n- mc.mu.Unlock()\n- break\n- }\n+ defer mc.mu.Unlock()\n- t := heap.Pop(mc.times).(time.Time)\n+ until := mc.mu.now.Add(d)\n+ for mc.mu.times.Len() > 0 {\n+ t := heap.Pop(&mc.mu.times).(time.Time)\nif t.After(until) {\n// No work to do\n- heap.Push(mc.times, t)\n- mc.mu.Unlock()\n+ heap.Push(&mc.mu.times, t)\nbreak\n}\n+\n+ timers := mc.mu.timers[t]\n+ delete(mc.mu.timers, t)\n+\n+ mc.mu.now = t\n+\n+ // Mark the timers as inactive since they will be fired.\n+ //\n+ // This needs to be done while holding mc's lock because we remove the entry\n+ // in the map of timers for the current time. If an attempt to stop a\n+ // timer is made after mc's lock was dropped but before the timer is\n+ // marked inactive, we would panic since no entry exists for the time when\n+ // the timer was expected to fire.\n+ for mt := range timers {\n+ mt.mu.Lock()\n+ mt.mu.firesAt = time.Time{}\n+ mt.mu.Unlock()\n+ }\n+\n+ // Release the lock before calling the timer's callback fn since the\n+ // callback fn might try to schedule a timer which requires obtaining\n+ // mc's lock.\nmc.mu.Unlock()\n- diff := t.Sub(mc.clock.Now())\n- mc.clock.Advance(diff)\n+ for mt := range timers {\n+ mt.f()\n+ }\n- mc.mu.RLock()\n- wg := mc.waitGroups[t]\n- mc.mu.RUnlock()\n+ // The timer callbacks may have scheduled a timer to fire immediately.\n+ // We spawn goroutines for these timers and need to wait for them to\n+ // finish before proceeding so that timer callbacks are called in the\n+ // right order.\n+ mc.runningTimers.wait()\n+ mc.mu.Lock()\n+ }\n- wg.Wait()\n+ mc.mu.now = until\n+}\n+func (mc *ManualClock) resetTimer(mt *manualTimer, d time.Duration) {\nmc.mu.Lock()\n- delete(mc.waitGroups, t)\n- mc.mu.Unlock()\n+ defer mc.mu.Unlock()\n+\n+ mt.mu.Lock()\n+ defer mt.mu.Unlock()\n+\n+ if !mt.mu.firesAt.IsZero() {\n+ mc.stopTimerLocked(mt)\n+ }\n+\n+ mc.resetTimerLocked(mt, d)\n}\n- if now := mc.clock.Now(); until.After(now) {\n- mc.clock.Advance(until.Sub(now))\n+\n+func (mc *ManualClock) stopTimer(mt *manualTimer) bool {\n+ mc.mu.Lock()\n+ defer mc.mu.Unlock()\n+\n+ mt.mu.Lock()\n+ defer mt.mu.Unlock()\n+\n+ if mt.mu.firesAt.IsZero() {\n+ return false\n}\n+\n+ mc.stopTimerLocked(mt)\n+ return true\n}\ntype manualTimer struct {\nclock *ManualClock\n- timer clockwork.Timer\n+ f func()\n+\n+ mu struct {\n+ sync.Mutex\n- mu sync.RWMutex\n- until time.Time\n+ // firesAt is the time when the timer will fire.\n+ //\n+ // Zero only when the timer is not active.\n+ firesAt time.Time\n+ }\n}\nvar _ tcpip.Timer = (*manualTimer)(nil)\n// Reset implements tcpip.Timer.Reset.\n-func (t *manualTimer) Reset(d time.Duration) {\n- if !t.timer.Reset(d) {\n- return\n- }\n-\n- t.mu.Lock()\n- defer t.mu.Unlock()\n-\n- t.clock.removeWait(t.until)\n- t.until = t.clock.clock.Now().Add(d)\n- t.clock.addWait(t.until)\n+func (mt *manualTimer) Reset(d time.Duration) {\n+ mt.clock.resetTimer(mt, d)\n}\n// Stop implements tcpip.Timer.Stop.\n-func (t *manualTimer) Stop() bool {\n- if !t.timer.Stop() {\n- return false\n- }\n-\n- t.mu.RLock()\n- defer t.mu.RUnlock()\n-\n- t.clock.removeWait(t.until)\n- return true\n+func (mt *manualTimer) Stop() bool {\n+ return mt.clock.stopTimer(mt)\n}\ntype timeHeap []time.Time\n" } ]
Go
Apache License 2.0
google/gvisor
Do not use clockwork for faketime Clockwork does not support timers being reset/stopped from different goroutines. Our current use of clockwork causes data races and gotsan complains about clockwork. This change uses our own implementation of faketime, avoiding data races. PiperOrigin-RevId: 354428208
259,992
28.01.2021 18:22:54
28,800
9cc2570ea74c678238ed82d044cfecbfe62c5981
Change EXPECT/ASSERT to TEST_CHECK inside InForkedProcess
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/madvise.cc", "new_path": "test/syscalls/linux/madvise.cc", "diff": "@@ -179,9 +179,9 @@ TEST(MadviseDontforkTest, DontforkShared) {\n// First page is mapped in child and modifications are visible to parent\n// via the shared mapping.\nTEST_CHECK(IsMapped(ms1.addr()));\n- ExpectAllMappingBytes(ms1, 2);\n+ CheckAllMappingBytes(ms1, 2);\nmemset(ms1.ptr(), 1, kPageSize);\n- ExpectAllMappingBytes(ms1, 1);\n+ CheckAllMappingBytes(ms1, 1);\n// Second page must not be mapped in child.\nTEST_CHECK(!IsMapped(ms2.addr()));\n@@ -222,9 +222,9 @@ TEST(MadviseDontforkTest, DontforkAnonPrivate) {\n// page. The mapping is private so the modifications are not visible to\n// the parent.\nTEST_CHECK(IsMapped(mp1.addr()));\n- ExpectAllMappingBytes(mp1, 1);\n+ CheckAllMappingBytes(mp1, 1);\nmemset(mp1.ptr(), 11, kPageSize);\n- ExpectAllMappingBytes(mp1, 11);\n+ CheckAllMappingBytes(mp1, 11);\n// Verify second page is not mapped.\nTEST_CHECK(!IsMapped(mp2.addr()));\n@@ -233,9 +233,9 @@ TEST(MadviseDontforkTest, DontforkAnonPrivate) {\n// page. The mapping is private so the modifications are not visible to\n// the parent.\nTEST_CHECK(IsMapped(mp3.addr()));\n- ExpectAllMappingBytes(mp3, 3);\n+ CheckAllMappingBytes(mp3, 3);\nmemset(mp3.ptr(), 13, kPageSize);\n- ExpectAllMappingBytes(mp3, 13);\n+ CheckAllMappingBytes(mp3, 13);\n};\nEXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pty.cc", "new_path": "test/syscalls/linux/pty.cc", "diff": "@@ -1338,6 +1338,7 @@ TEST_F(JobControlTest, SetTTYDifferentSession) {\nTEST_PCHECK(waitpid(grandchild, &gcwstatus, 0) == grandchild);\nTEST_PCHECK(gcwstatus == 0);\n});\n+ ASSERT_NO_ERRNO(res);\n}\nTEST_F(JobControlTest, ReleaseTTY) {\n@@ -1515,7 +1516,8 @@ TEST_F(JobControlTest, GetForegroundProcessGroupNonControlling) {\n// - creates a child process in a new process group\n// - sets that child as the foreground process group\n// - kills its child and sets itself as the foreground process group.\n-TEST_F(JobControlTest, SetForegroundProcessGroup) {\n+// TODO(gvisor.dev/issue/5357): Fix and enable.\n+TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroup) {\nauto res = RunInChild([=]() {\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n@@ -1557,6 +1559,7 @@ TEST_F(JobControlTest, SetForegroundProcessGroup) {\nTEST_PCHECK(pgid = getpgid(0) == 0);\nTEST_PCHECK(!tcsetpgrp(replica_.get(), pgid));\n});\n+ ASSERT_NO_ERRNO(res);\n}\nTEST_F(JobControlTest, SetForegroundProcessGroupWrongTTY) {\n@@ -1576,8 +1579,9 @@ TEST_F(JobControlTest, SetForegroundProcessGroupNegPgid) {\nASSERT_NO_ERRNO(ret);\n}\n-TEST_F(JobControlTest, SetForegroundProcessGroupEmptyProcessGroup) {\n- auto ret = RunInChild([=]() {\n+// TODO(gvisor.dev/issue/5357): Fix and enable.\n+TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroupEmptyProcessGroup) {\n+ auto res = RunInChild([=]() {\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n// Create a new process, put it in a new process group, make that group the\n@@ -1595,6 +1599,7 @@ TEST_F(JobControlTest, SetForegroundProcessGroupEmptyProcessGroup) {\nTEST_PCHECK(ioctl(replica_.get(), TIOCSPGRP, &grandchild) != 0 &&\nerrno == ESRCH);\n});\n+ ASSERT_NO_ERRNO(res);\n}\nTEST_F(JobControlTest, SetForegroundProcessGroupDifferentSession) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/shm.cc", "new_path": "test/syscalls/linux/shm.cc", "diff": "@@ -372,18 +372,18 @@ TEST(ShmDeathTest, SegmentNotAccessibleAfterDetach) {\nSetupGvisorDeathTest();\nconst auto rest = [&] {\n- ShmSegment shm = ASSERT_NO_ERRNO_AND_VALUE(\n+ ShmSegment shm = TEST_CHECK_NO_ERRNO_AND_VALUE(\nShmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));\n- char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(shm.id(), nullptr, 0));\n+ char* addr = TEST_CHECK_NO_ERRNO_AND_VALUE(Shmat(shm.id(), nullptr, 0));\n// Mark the segment as destroyed so it's automatically cleaned up when we\n// crash below. We can't rely on the standard cleanup since the destructor\n// will not run after the SIGSEGV. Note that this doesn't destroy the\n// segment immediately since we're still attached to it.\n- ASSERT_NO_ERRNO(shm.Rmid());\n+ TEST_CHECK_NO_ERRNO(shm.Rmid());\naddr[0] = 'x';\n- ASSERT_NO_ERRNO(Shmdt(addr));\n+ TEST_CHECK_NO_ERRNO(Shmdt(addr));\n// This access should cause a SIGSEGV.\naddr[0] = 'x';\n" }, { "change_type": "MODIFY", "old_path": "test/util/logging.cc", "new_path": "test/util/logging.cc", "diff": "@@ -69,9 +69,7 @@ int WriteNumber(int fd, uint32_t val) {\n} // namespace\nvoid CheckFailure(const char* cond, size_t cond_size, const char* msg,\n- size_t msg_size, bool include_errno) {\n- int saved_errno = errno;\n-\n+ size_t msg_size, int errno_value) {\nconstexpr char kCheckFailure[] = \"Check failed: \";\nWrite(2, kCheckFailure, sizeof(kCheckFailure) - 1);\nWrite(2, cond, cond_size);\n@@ -81,10 +79,10 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\nWrite(2, msg, msg_size);\n}\n- if (include_errno) {\n+ if (errno_value != 0) {\nconstexpr char kErrnoMessage[] = \" (errno \";\nWrite(2, kErrnoMessage, sizeof(kErrnoMessage) - 1);\n- WriteNumber(2, saved_errno);\n+ WriteNumber(2, errno_value);\nWrite(2, \")\", 1);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/logging.h", "new_path": "test/util/logging.h", "diff": "@@ -21,7 +21,7 @@ namespace gvisor {\nnamespace testing {\nvoid CheckFailure(const char* cond, size_t cond_size, const char* msg,\n- size_t msg_size, bool include_errno);\n+ size_t msg_size, int errno_value);\n// If cond is false, aborts the current process.\n//\n@@ -30,7 +30,7 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\ndo { \\\nif (!(cond)) { \\\n::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, nullptr, \\\n- 0, false); \\\n+ 0, 0); \\\n} \\\n} while (0)\n@@ -41,7 +41,7 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\ndo { \\\nif (!(cond)) { \\\n::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, msg, \\\n- sizeof(msg) - 1, false); \\\n+ sizeof(msg) - 1, 0); \\\n} \\\n} while (0)\n@@ -52,7 +52,7 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\ndo { \\\nif (!(cond)) { \\\n::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, nullptr, \\\n- 0, true); \\\n+ 0, errno); \\\n} \\\n} while (0)\n@@ -63,10 +63,39 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\ndo { \\\nif (!(cond)) { \\\n::gvisor::testing::CheckFailure(#cond, sizeof(#cond) - 1, msg, \\\n- sizeof(msg) - 1, true); \\\n+ sizeof(msg) - 1, errno); \\\n} \\\n} while (0)\n+// expr must return PosixErrorOr<T>. The current process is aborted if\n+// !PosixError<T>.ok().\n+//\n+// This macro is async-signal-safe.\n+#define TEST_CHECK_NO_ERRNO(expr) \\\n+ ({ \\\n+ auto _expr_result = (expr); \\\n+ if (!_expr_result.ok()) { \\\n+ ::gvisor::testing::CheckFailure( \\\n+ #expr, sizeof(#expr) - 1, nullptr, 0, \\\n+ _expr_result.error().errno_value()); \\\n+ } \\\n+ })\n+\n+// expr must return PosixErrorOr<T>. The current process is aborted if\n+// !PosixError<T>.ok(). Otherwise, PosixErrorOr<T> value is returned.\n+//\n+// This macro is async-signal-safe.\n+#define TEST_CHECK_NO_ERRNO_AND_VALUE(expr) \\\n+ ({ \\\n+ auto _expr_result = (expr); \\\n+ if (!_expr_result.ok()) { \\\n+ ::gvisor::testing::CheckFailure( \\\n+ #expr, sizeof(#expr) - 1, nullptr, 0, \\\n+ _expr_result.error().errno_value()); \\\n+ } \\\n+ std::move(_expr_result).ValueOrDie(); \\\n+ })\n+\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/util/multiprocess_util.h", "new_path": "test/util/multiprocess_util.h", "diff": "@@ -123,7 +123,8 @@ inline PosixErrorOr<Cleanup> ForkAndExecveat(int32_t dirfd,\n// Calls fn in a forked subprocess and returns the exit status of the\n// subprocess.\n//\n-// fn must be async-signal-safe.\n+// fn must be async-signal-safe. Use of ASSERT/EXPECT functions is prohibited.\n+// Use TEST_CHECK variants instead.\nPosixErrorOr<int> InForkedProcess(const std::function<void()>& fn);\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error.cc", "new_path": "test/util/posix_error.cc", "diff": "@@ -50,7 +50,7 @@ std::string PosixError::ToString() const {\nret = absl::StrCat(\"PosixError(errno=\", errno_, \" \", res, \")\");\n#endif\n- if (!msg_.empty()) {\n+ if (strnlen(msg_, sizeof(msg_)) > 0) {\nret.append(\" \");\nret.append(msg_);\n}\n" }, { "change_type": "MODIFY", "old_path": "test/util/posix_error.h", "new_path": "test/util/posix_error.h", "diff": "namespace gvisor {\nnamespace testing {\n+// PosixError must be async-signal-safe.\nclass ABSL_MUST_USE_RESULT PosixError {\npublic:\nPosixError() {}\n+\nexplicit PosixError(int errno_value) : errno_(errno_value) {}\n- PosixError(int errno_value, std::string msg)\n- : errno_(errno_value), msg_(std::move(msg)) {}\n+\n+ PosixError(int errno_value, std::string_view msg) : errno_(errno_value) {\n+ // Check that `msg` will fit, leaving room for '\\0' at the end.\n+ TEST_CHECK(msg.size() < sizeof(msg_));\n+ msg.copy(msg_, msg.size());\n+ }\nPosixError(PosixError&& other) = default;\nPosixError& operator=(PosixError&& other) = default;\n@@ -45,7 +51,7 @@ class ABSL_MUST_USE_RESULT PosixError {\nconst PosixError& error() const { return *this; }\nint errno_value() const { return errno_; }\n- std::string message() const { return msg_; }\n+ const char* message() const { return msg_; }\n// ToString produces a full string representation of this posix error\n// including the printable representation of the errno and the error message.\n@@ -58,7 +64,7 @@ class ABSL_MUST_USE_RESULT PosixError {\nprivate:\nint errno_ = 0;\n- std::string msg_;\n+ char msg_[1024] = {};\n};\ntemplate <typename T>\n" } ]
Go
Apache License 2.0
google/gvisor
Change EXPECT/ASSERT to TEST_CHECK inside InForkedProcess PiperOrigin-RevId: 354441239
260,004
28.01.2021 20:30:02
28,800
d6a39734c4934aa98141074c67389e80ed130a94
Avoid locking when route doesn't require resolution When a route does not need to resolve a remote link address to send a packet, avoid having to obtain the pending packets queue's lock.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -309,7 +309,26 @@ func (n *NIC) WritePacket(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumb\nreturn err\n}\n+func (n *NIC) writePacketBuffer(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\n+ switch pkt := pkt.(type) {\n+ case *PacketBuffer:\n+ if err := n.writePacket(r, gso, protocol, pkt); err != nil {\n+ return 0, err\n+ }\n+ return 1, nil\n+ case *PacketBufferList:\n+ return n.writePackets(r, gso, protocol, *pkt)\n+ default:\n+ panic(fmt.Sprintf(\"unrecognized pending packet buffer type = %T\", pkt))\n+ }\n+}\n+\nfunc (n *NIC) enqueuePacketBuffer(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\n+ routeInfo, _, err := r.resolvedFields(nil)\n+ switch err.(type) {\n+ case nil:\n+ return n.writePacketBuffer(routeInfo, gso, protocol, pkt)\n+ case *tcpip.ErrWouldBlock:\n// As per relevant RFCs, we should queue packets while we wait for link\n// resolution to complete.\n//\n@@ -322,12 +341,15 @@ func (n *NIC) enqueuePacketBuffer(r *Route, gso *GSO, protocol tcpip.NetworkProt\n// RFC 4861 section 7.2.2 (for IPv6):\n// While waiting for address resolution to complete, the sender MUST, for\n// each neighbor, retain a small queue of packets waiting for address\n- // resolution to complete. The queue MUST hold at least one packet, and MAY\n- // contain more. However, the number of queued packets per neighbor SHOULD\n- // be limited to some small value. When a queue overflows, the new arrival\n- // SHOULD replace the oldest entry. Once address resolution completes, the\n- // node transmits any queued packets.\n+ // resolution to complete. The queue MUST hold at least one packet, and\n+ // MAY contain more. However, the number of queued packets per neighbor\n+ // SHOULD be limited to some small value. When a queue overflows, the new\n+ // arrival SHOULD replace the oldest entry. Once address resolution\n+ // completes, the node transmits any queued packets.\nreturn n.linkResQueue.enqueue(r, gso, protocol, pkt)\n+ default:\n+ return 0, err\n+ }\n}\n// WritePacketToRemote implements NetworkInterface.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/pending_packets.go", "new_path": "pkg/tcpip/stack/pending_packets.go", "diff": "@@ -114,20 +114,6 @@ func (f *packetsPendingLinkResolution) dequeue(ch <-chan struct{}, linkAddr tcpi\n}\n}\n-func (f *packetsPendingLinkResolution) writePacketBuffer(r RouteInfo, gso *GSO, proto tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\n- switch pkt := pkt.(type) {\n- case *PacketBuffer:\n- if err := f.nic.writePacket(r, gso, proto, pkt); err != nil {\n- return 0, err\n- }\n- return 1, nil\n- case *PacketBufferList:\n- return f.nic.writePackets(r, gso, proto, *pkt)\n- default:\n- panic(fmt.Sprintf(\"unrecognized pending packet buffer type = %T\", pkt))\n- }\n-}\n-\n// enqueue a packet to be sent once link resolution completes.\n//\n// If the maximum number of pending resolutions is reached, the packets\n@@ -151,7 +137,7 @@ func (f *packetsPendingLinkResolution) enqueue(r *Route, gso *GSO, proto tcpip.N\n// The route resolved immediately, so we don't need to wait for link\n// resolution to send the packet.\nf.mu.Unlock()\n- return f.writePacketBuffer(routeInfo, gso, proto, pkt)\n+ return f.nic.writePacketBuffer(routeInfo, gso, proto, pkt)\ncase *tcpip.ErrWouldBlock:\n// We need to wait for link resolution to complete.\ndefault:\n@@ -225,7 +211,7 @@ func (f *packetsPendingLinkResolution) dequeuePackets(packets []pendingPacket, l\nfor _, p := range packets {\nif success {\np.routeInfo.RemoteLinkAddress = linkAddr\n- _, _ = f.writePacketBuffer(p.routeInfo, p.gso, p.proto, p.pkt)\n+ _, _ = f.nic.writePacketBuffer(p.routeInfo, p.gso, p.proto, p.pkt)\n} else {\nf.incrementOutgoingPacketErrors(p.proto, p.pkt)\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid locking when route doesn't require resolution When a route does not need to resolve a remote link address to send a packet, avoid having to obtain the pending packets queue's lock. PiperOrigin-RevId: 354456280
259,986
29.01.2021 08:34:45
28,800
71623e40680c79e82390016a10376e73ff2370db
Discard invalid Neighbor Advertisements ...per RFC 4861 s7.1.2. Startblock: has LGTM from sbalana and then add reviewer ghanan
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -445,6 +445,17 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool) {\nreturn\n}\n+ // As per RFC 4861 section 7.1.2:\n+ // A node MUST silently discard any received Neighbor Advertisement\n+ // messages that do not satisfy all of the following validity checks:\n+ // ...\n+ // - If the IP Destination Address is a multicast address the\n+ // Solicited flag is zero.\n+ if header.IsV6MulticastAddress(dstAddr) && na.SolicitedFlag() {\n+ received.invalid.Increment()\n+ return\n+ }\n+\n// If the NA message has the target link layer option, update the link\n// address cache with the link address for the target of the message.\nif e.nud == nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -167,10 +167,10 @@ type linkResolutionResult struct {\nok bool\n}\n-// TestNeighorSolicitationWithSourceLinkLayerOption tests that receiving a\n+// TestNeighborSolicitationWithSourceLinkLayerOption tests that receiving a\n// valid NDP NS message with the Source Link Layer Address option results in a\n// new entry in the link address cache for the sender of the message.\n-func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\n+func TestNeighborSolicitationWithSourceLinkLayerOption(t *testing.T) {\nconst nicID = 1\ntests := []struct {\n@@ -265,11 +265,11 @@ func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\n}\n}\n-// TestNeighorSolicitationWithSourceLinkLayerOptionUsingNeighborCache tests\n+// TestNeighborSolicitationWithSourceLinkLayerOptionUsingNeighborCache tests\n// that receiving a valid NDP NS message with the Source Link Layer Address\n// option results in a new entry in the link address cache for the sender of\n// the message.\n-func TestNeighorSolicitationWithSourceLinkLayerOptionUsingNeighborCache(t *testing.T) {\n+func TestNeighborSolicitationWithSourceLinkLayerOptionUsingNeighborCache(t *testing.T) {\nconst nicID = 1\ntests := []struct {\n@@ -382,7 +382,7 @@ func TestNeighorSolicitationWithSourceLinkLayerOptionUsingNeighborCache(t *testi\n}\n}\n-func TestNeighorSolicitationResponse(t *testing.T) {\n+func TestNeighborSolicitationResponse(t *testing.T) {\nconst nicID = 1\nnicAddr := lladdr0\nremoteAddr := lladdr1\n@@ -721,10 +721,10 @@ func TestNeighorSolicitationResponse(t *testing.T) {\n}\n}\n-// TestNeighorAdvertisementWithTargetLinkLayerOption tests that receiving a\n+// TestNeighborAdvertisementWithTargetLinkLayerOption tests that receiving a\n// valid NDP NA message with the Target Link Layer Address option results in a\n// new entry in the link address cache for the target of the message.\n-func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\n+func TestNeighborAdvertisementWithTargetLinkLayerOption(t *testing.T) {\nconst nicID = 1\ntests := []struct {\n@@ -826,11 +826,11 @@ func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\n}\n}\n-// TestNeighorAdvertisementWithTargetLinkLayerOptionUsingNeighborCache tests\n+// TestNeighborAdvertisementWithTargetLinkLayerOptionUsingNeighborCache tests\n// that receiving a valid NDP NA message with the Target Link Layer Address\n// option does not result in a new entry in the neighbor cache for the target\n// of the message.\n-func TestNeighorAdvertisementWithTargetLinkLayerOptionUsingNeighborCache(t *testing.T) {\n+func TestNeighborAdvertisementWithTargetLinkLayerOptionUsingNeighborCache(t *testing.T) {\nconst nicID = 1\ntests := []struct {\n@@ -1172,6 +1172,118 @@ func TestNDPValidation(t *testing.T) {\n}\n+// TestNeighborAdvertisementValidation tests that the NIC validates received\n+// Neighbor Advertisements.\n+//\n+// In particular, if the IP Destination Address is a multicast address, and the\n+// Solicited flag is not zero, the Neighbor Advertisement is invalid and should\n+// be discarded.\n+func TestNeighborAdvertisementValidation(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ ipDstAddr tcpip.Address\n+ solicitedFlag bool\n+ valid bool\n+ }{\n+ {\n+ name: \"Multicast IP destination address with Solicited flag set\",\n+ ipDstAddr: header.IPv6AllNodesMulticastAddress,\n+ solicitedFlag: true,\n+ valid: false,\n+ },\n+ {\n+ name: \"Multicast IP destination address with Solicited flag unset\",\n+ ipDstAddr: header.IPv6AllNodesMulticastAddress,\n+ solicitedFlag: false,\n+ valid: true,\n+ },\n+ {\n+ name: \"Unicast IP destination address with Solicited flag set\",\n+ ipDstAddr: lladdr0,\n+ solicitedFlag: true,\n+ valid: true,\n+ },\n+ {\n+ name: \"Unicast IP destination address with Solicited flag unset\",\n+ ipDstAddr: lladdr0,\n+ solicitedFlag: false,\n+ valid: true,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\n+ UseNeighborCache: true,\n+ })\n+ e := channel.New(0, header.IPv6MinimumMTU, linkAddr0)\n+ e.LinkEPCapabilities |= stack.CapabilityResolutionRequired\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n+ }\n+ if err := s.AddAddress(nicID, ProtocolNumber, lladdr0); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, ProtocolNumber, lladdr0, err)\n+ }\n+\n+ ndpNASize := header.ICMPv6NeighborAdvertMinimumSize\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNASize)\n+ pkt := header.ICMPv6(hdr.Prepend(ndpNASize))\n+ pkt.SetType(header.ICMPv6NeighborAdvert)\n+ na := header.NDPNeighborAdvert(pkt.MessageBody())\n+ na.SetTargetAddress(lladdr1)\n+ na.SetSolicitedFlag(test.solicitedFlag)\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, test.ipDstAddr, buffer.VectorisedView{}))\n+ payloadLength := hdr.UsedLength()\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLength),\n+ TransportProtocol: header.ICMPv6ProtocolNumber,\n+ HopLimit: 255,\n+ SrcAddr: lladdr1,\n+ DstAddr: test.ipDstAddr,\n+ })\n+\n+ stats := s.Stats().ICMP.V6.PacketsReceived\n+ invalid := stats.Invalid\n+ rxNA := stats.NeighborAdvert\n+\n+ if got := rxNA.Value(); got != 0 {\n+ t.Fatalf(\"got rxNA = %d, want = 0\", got)\n+ }\n+ if got := invalid.Value(); got != 0 {\n+ t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ }\n+\n+ e.InjectInbound(header.IPv6ProtocolNumber, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: hdr.View().ToVectorisedView(),\n+ }))\n+\n+ if got := rxNA.Value(); got != 1 {\n+ t.Fatalf(\"got rxNA = %d, want = 1\", got)\n+ }\n+ var wantInvalid uint64 = 1\n+ if test.valid {\n+ wantInvalid = 0\n+ }\n+ if got := invalid.Value(); got != wantInvalid {\n+ t.Fatalf(\"got invalid = %d, want = %d\", got, wantInvalid)\n+ }\n+ // As per RFC 4861 section 7.2.5:\n+ // When a valid Neighbor Advertisement is received ...\n+ // If no entry exists, the advertisement SHOULD be silently discarded.\n+ // There is no need to create an entry if none exists, since the\n+ // recipient has apparently not initiated any communication with the\n+ // target.\n+ if neighbors, err := s.Neighbors(nicID); err != nil {\n+ t.Fatalf(\"s.Neighbors(%d): %s\", nicID, err)\n+ } else if len(neighbors) != 0 {\n+ t.Fatalf(\"got len(neighbors) = %d, want = 0; neighbors = %#v\", len(neighbors), neighbors)\n+ }\n+ })\n+ }\n+}\n+\n// TestRouterAdvertValidation tests that when the NIC is configured to handle\n// NDP Router Advertisement packets, it validates the Router Advertisement\n// properly before handling them.\n" } ]
Go
Apache License 2.0
google/gvisor
Discard invalid Neighbor Advertisements ...per RFC 4861 s7.1.2. Startblock: has LGTM from sbalana and then add reviewer ghanan PiperOrigin-RevId: 354539026
259,992
29.01.2021 12:16:55
28,800
0fa534f1164f2bf6cf50a37d4dce584b6fc8ec07
Fix deadlock in specialFileFD.pwrite When file is regular and metadata cache is authoritative, metadata lock is taken. The code deadlocks trying to acquire the metadata lock again to update time stampts.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/special_file.go", "new_path": "pkg/sentry/fsimpl/gofer/special_file.go", "diff": "@@ -299,10 +299,15 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nsrc = src.TakeFirst64(limit)\n}\n- // Do a buffered write. See rationale in PRead.\nif d.cachedMetadataAuthoritative() {\n+ if fd.isRegularFile {\n+ d.touchCMtimeLocked()\n+ } else {\nd.touchCMtime()\n}\n+ }\n+\n+ // Do a buffered write. See rationale in PRead.\nbuf := make([]byte, src.NumBytes())\ncopied, copyErr := src.CopyIn(ctx, buf)\nif copied == 0 && copyErr != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix deadlock in specialFileFD.pwrite When file is regular and metadata cache is authoritative, metadata lock is taken. The code deadlocks trying to acquire the metadata lock again to update time stampts. PiperOrigin-RevId: 354584594
259,896
29.01.2021 13:13:46
28,800
0a52b647945e557c446b173309644458cd0a2ec3
Add more comments for the TCP_INFO struct fields.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/socket.go", "new_path": "pkg/abi/linux/socket.go", "diff": "@@ -347,26 +347,57 @@ const SizeOfLinger = 8\n//\n// +marshal\ntype TCPInfo struct {\n+ // State is the state of the connection.\nState uint8\n+\n+ // CaState is the congestion control state.\nCaState uint8\n+\n+ // Retransmits is the number of retransmissions triggered by RTO.\nRetransmits uint8\n+\n+ // Probes is the number of unanswered zero window probes.\nProbes uint8\n+\n+ // BackOff indicates exponential backoff.\nBackoff uint8\n+\n+ // Options indicates the options enabled for the connection.\nOptions uint8\n- // WindowScale is the combination of snd_wscale (first 4 bits) and rcv_wscale (second 4 bits)\n+\n+ // WindowScale is the combination of snd_wscale (first 4 bits) and\n+ // rcv_wscale (second 4 bits)\nWindowScale uint8\n- // DeliveryRateAppLimited is a boolean and only the first bit is meaningful.\n+\n+ // DeliveryRateAppLimited is a boolean and only the first bit is\n+ // meaningful.\nDeliveryRateAppLimited uint8\n+ // RTO is the retransmission timeout.\nRTO uint32\n+\n+ // ATO is the acknowledgement timeout interval.\nATO uint32\n+\n+ // SndMss is the send maximum segment size.\nSndMss uint32\n+\n+ // RcvMss is the receive maximum segment size.\nRcvMss uint32\n+ // Unacked is the number of packets sent but not acknowledged.\nUnacked uint32\n+\n+ // Sacked is the number of packets which are selectively acknowledged.\nSacked uint32\n+\n+ // Lost is the number of packets marked as lost.\nLost uint32\n+\n+ // Retrans is the number of retransmitted packets.\nRetrans uint32\n+\n+ // Fackets is not used and is always zero.\nFackets uint32\n// Times.\n@@ -385,48 +416,77 @@ type TCPInfo struct {\nAdvmss uint32\nReordering uint32\n+ // RcvRTT is the receiver round trip time.\nRcvRTT uint32\n+\n+ // RcvSpace is the current buffer space available for receiving data.\nRcvSpace uint32\n+ // TotalRetrans is the total number of retransmits seen since the start\n+ // of the connection.\nTotalRetrans uint32\n+ // PacingRate is the pacing rate in bytes per second.\nPacingRate uint64\n+\n+ // MaxPacingRate is the maximum pacing rate.\nMaxPacingRate uint64\n+\n// BytesAcked is RFC4898 tcpEStatsAppHCThruOctetsAcked.\nBytesAcked uint64\n+\n// BytesReceived is RFC4898 tcpEStatsAppHCThruOctetsReceived.\nBytesReceived uint64\n+\n// SegsOut is RFC4898 tcpEStatsPerfSegsOut.\nSegsOut uint32\n+\n// SegsIn is RFC4898 tcpEStatsPerfSegsIn.\nSegsIn uint32\n+ // NotSentBytes is the amount of bytes in the write queue that are not\n+ // yet sent.\nNotSentBytes uint32\n+\n+ // MinRTT is the minimum round trip time seen in the connection.\nMinRTT uint32\n+\n// DataSegsIn is RFC4898 tcpEStatsDataSegsIn.\nDataSegsIn uint32\n+\n// DataSegsOut is RFC4898 tcpEStatsDataSegsOut.\nDataSegsOut uint32\n+ // DeliveryRate is the most recent delivery rate in bytes per second.\nDeliveryRate uint64\n// BusyTime is the time in microseconds busy sending data.\nBusyTime uint64\n+\n// RwndLimited is the time in microseconds limited by receive window.\nRwndLimited uint64\n+\n// SndBufLimited is the time in microseconds limited by send buffer.\nSndBufLimited uint64\n- Delievered uint32\n- DelieveredCe uint32\n+ // Delivered is the total data packets delivered including retransmits.\n+ Delivered uint32\n+\n+ // DeliveredCE is the total ECE marked data packets delivered including\n+ // retransmits.\n+ DeliveredCE uint32\n// BytesSent is RFC4898 tcpEStatsPerfHCDataOctetsOut.\nBytesSent uint64\n+\n// BytesRetrans is RFC4898 tcpEStatsPerfOctetsRetrans.\nBytesRetrans uint64\n+\n// DSACKDups is RFC4898 tcpEStatsStackDSACKDups.\nDSACKDups uint32\n- // ReordSeen is the number of reordering events seen.\n+\n+ // ReordSeen is the number of reordering events seen since the start of\n+ // the connection.\nReordSeen uint32\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc", "diff": "@@ -65,6 +65,9 @@ TEST_P(TCPSocketPairTest, ZeroTcpInfoSucceeds) {\nSyscallSucceeds());\n}\n+// Copied from include/net/tcp.h.\n+constexpr int TCP_CA_OPEN = 0;\n+\nTEST_P(TCPSocketPairTest, CheckTcpInfoFields) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n@@ -87,7 +90,7 @@ TEST_P(TCPSocketPairTest, CheckTcpInfoFields) {\nSyscallSucceeds());\n// Validates the received tcp_info fields.\n- EXPECT_EQ(opt.tcpi_ca_state, 0);\n+ EXPECT_EQ(opt.tcpi_ca_state, TCP_CA_OPEN);\nEXPECT_GT(opt.tcpi_snd_cwnd, 0);\nEXPECT_GT(opt.tcpi_rto, 0);\n}\n" } ]
Go
Apache License 2.0
google/gvisor
- Add more comments for the TCP_INFO struct fields. PiperOrigin-RevId: 354595623
260,004
29.01.2021 13:47:58
28,800
5e2edfb8726ddb255a02352e2f68ea028f543e4b
Refresh delayed report timers on query messages ...as per As per RFC 2236 section 3 page 3 (for IGMPv2) and RFC 2710 section 4 page 5 (for MLDv1). See comments in code for more details. Test: ip_test.TestHandleQuery
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "new_path": "pkg/tcpip/network/ip/generic_multicast_protocol.go", "diff": "@@ -126,6 +126,16 @@ type multicastGroupState struct {\n//\n// Must not be nil.\ndelayedReportJob *tcpip.Job\n+\n+ // delyedReportJobFiresAt is the time when the delayed report job will fire.\n+ //\n+ // A zero value indicates that the job is not scheduled.\n+ delayedReportJobFiresAt time.Time\n+}\n+\n+func (m *multicastGroupState) cancelDelayedReportJob() {\n+ m.delayedReportJob.Cancel()\n+ m.delayedReportJobFiresAt = time.Time{}\n}\n// GenericMulticastProtocolOptions holds options for the generic multicast\n@@ -428,7 +438,7 @@ func (g *GenericMulticastProtocolState) HandleReportLocked(groupAddress tcpip.Ad\n// on that interface, it stops its timer and does not send a Report for\n// that address, thus suppressing duplicate reports on the link.\nif info, ok := g.memberships[groupAddress]; ok && info.state.isDelayingMember() {\n- info.delayedReportJob.Cancel()\n+ info.cancelDelayedReportJob()\ninfo.lastToSendReport = false\ninfo.state = idleMember\ng.memberships[groupAddress] = info\n@@ -603,7 +613,7 @@ func (g *GenericMulticastProtocolState) transitionToNonMemberLocked(groupAddress\nreturn\n}\n- info.delayedReportJob.Cancel()\n+ info.cancelDelayedReportJob()\ng.maybeSendLeave(groupAddress, info.lastToSendReport)\ninfo.lastToSendReport = false\ninfo.state = nonMember\n@@ -645,14 +655,24 @@ func (g *GenericMulticastProtocolState) setDelayTimerForAddressRLocked(groupAddr\n// If a timer for any address is already running, it is reset to the new\n// random value only if the requested Maximum Response Delay is less than\n// the remaining value of the running timer.\n+ now := time.Unix(0 /* seconds */, g.opts.Clock.NowNanoseconds())\nif info.state == delayingMember {\n- // TODO: Reset the timer if time remaining is greater than maxResponseTime.\n+ if info.delayedReportJobFiresAt.IsZero() {\n+ panic(fmt.Sprintf(\"delayed report unscheduled while in the delaying member state; group = %s\", groupAddress))\n+ }\n+\n+ if info.delayedReportJobFiresAt.Sub(now) <= maxResponseTime {\n+ // The timer is scheduled to fire before the maximum response time so we\n+ // leave our timer as is.\nreturn\n}\n+ }\ninfo.state = delayingMember\n- info.delayedReportJob.Cancel()\n- info.delayedReportJob.Schedule(g.calculateDelayTimerDuration(maxResponseTime))\n+ info.cancelDelayedReportJob()\n+ maxResponseTime = g.calculateDelayTimerDuration(maxResponseTime)\n+ info.delayedReportJob.Schedule(maxResponseTime)\n+ info.delayedReportJobFiresAt = now.Add(maxResponseTime)\n}\n// calculateDelayTimerDuration returns a random time between (0, maxRespTime].\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": "@@ -411,37 +411,43 @@ func TestHandleQuery(t *testing.T) {\nname string\nqueryAddr tcpip.Address\nmaxDelay time.Duration\n- expectReportsFor []tcpip.Address\n+ expectQueriedReportsFor []tcpip.Address\n+ expectDelayedReportsFor []tcpip.Address\n}{\n{\nname: \"Unpecified empty\",\nqueryAddr: \"\",\nmaxDelay: 0,\n- expectReportsFor: []tcpip.Address{addr1, addr2},\n+ expectQueriedReportsFor: []tcpip.Address{addr1, addr2},\n+ expectDelayedReportsFor: nil,\n},\n{\nname: \"Unpecified any\",\nqueryAddr: \"\\x00\",\nmaxDelay: 1,\n- expectReportsFor: []tcpip.Address{addr1, addr2},\n+ expectQueriedReportsFor: []tcpip.Address{addr1, addr2},\n+ expectDelayedReportsFor: nil,\n},\n{\nname: \"Specified\",\nqueryAddr: addr1,\nmaxDelay: 2,\n- expectReportsFor: []tcpip.Address{addr1},\n+ expectQueriedReportsFor: []tcpip.Address{addr1},\n+ expectDelayedReportsFor: []tcpip.Address{addr2},\n},\n{\nname: \"Specified all-nodes\",\nqueryAddr: addr3,\nmaxDelay: 3,\n- expectReportsFor: nil,\n+ expectQueriedReportsFor: nil,\n+ expectDelayedReportsFor: []tcpip.Address{addr1, addr2},\n},\n{\nname: \"Specified other\",\nqueryAddr: addr4,\nmaxDelay: 4,\n- expectReportsFor: nil,\n+ expectQueriedReportsFor: nil,\n+ expectDelayedReportsFor: []tcpip.Address{addr1, addr2},\n},\n}\n@@ -469,20 +475,20 @@ func TestHandleQuery(t *testing.T) {\nif diff := mgp.check(nil /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n- // Generic multicast protocol timers are expected to take the job mutex.\n- clock.Advance(maxUnsolicitedReportDelay)\n- if diff := mgp.check([]tcpip.Address{addr1, addr2} /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n- t.Fatalf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n- }\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+ // Receiving a query should make us reschedule our delayed report timer\n+ // to some time within the new max response delay.\nmgp.handleQuery(test.queryAddr, test.maxDelay)\n- if len(test.expectReportsFor) != 0 {\nclock.Advance(test.maxDelay)\n- if diff := mgp.check(test.expectReportsFor /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n+ if diff := mgp.check(test.expectQueriedReportsFor /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\nt.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n+\n+ // The groups that were not affected by the query should still send a\n+ // report after the max unsolicited report delay.\n+ clock.Advance(maxUnsolicitedReportDelay)\n+ if diff := mgp.check(test.expectDelayedReportsFor /* sendReportGroupAddresses */, nil /* sendLeaveGroupAddresses */); diff != \"\" {\n+ t.Errorf(\"mockMulticastGroupProtocol mismatch (-want +got):\\n%s\", diff)\n}\n// Should have no more messages to send.\n" } ]
Go
Apache License 2.0
google/gvisor
Refresh delayed report timers on query messages ...as per As per RFC 2236 section 3 page 3 (for IGMPv2) and RFC 2710 section 4 page 5 (for MLDv1). See comments in code for more details. Test: ip_test.TestHandleQuery PiperOrigin-RevId: 354603068
259,992
29.01.2021 13:54:34
28,800
fdbfd447a02e52296f48a5cb1020030756ed8da6
Remove side effect from test cases Individual test cases must not rely on being executed in a clean environment.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -482,7 +482,9 @@ cc_binary(\n\"//test/util:fs_util\",\n\"@com_google_absl//absl/strings\",\ngtest,\n+ \"//test/util:logging\",\n\"//test/util:mount_util\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:temp_path\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n@@ -672,6 +674,7 @@ cc_binary(\ngtest,\n\"//test/util:logging\",\n\"//test/util:memory_util\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:signal_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n@@ -3827,6 +3830,8 @@ cc_binary(\n\"@com_google_absl//absl/flags:flag\",\n\"@com_google_absl//absl/strings\",\ngtest,\n+ \"//test/util:cleanup\",\n+ \"//test/util:multiprocess_util\",\n\"//test/util:posix_error\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n@@ -4082,6 +4087,7 @@ cc_binary(\n\"@com_google_absl//absl/strings\",\n\"@com_google_absl//absl/strings:str_format\",\ngtest,\n+ \"//test/util:cleanup\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/chroot.cc", "new_path": "test/syscalls/linux/chroot.cc", "diff": "#include \"test/util/cleanup.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n+#include \"test/util/logging.h\"\n#include \"test/util/mount_util.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -47,17 +49,20 @@ namespace {\nTEST(ChrootTest, Success) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n+ const auto rest = [] {\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- EXPECT_THAT(chroot(temp_dir.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(temp_dir.path().c_str()));\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\nTEST(ChrootTest, PermissionDenied) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n- // CAP_DAC_READ_SEARCH and CAP_DAC_OVERRIDE may override Execute permission on\n- // directories.\n- ASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\n- ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n+ // CAP_DAC_READ_SEARCH and CAP_DAC_OVERRIDE may override Execute permission\n+ // on directories.\n+ AutoCapability cap_search(CAP_DAC_READ_SEARCH, false);\n+ AutoCapability cap_override(CAP_DAC_OVERRIDE, false);\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(\nTempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0666 /* mode */));\n@@ -78,8 +83,10 @@ TEST(ChrootTest, NotExist) {\n}\nTEST(ChrootTest, WithoutCapability) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETPCAP)));\n+\n// Unset CAP_SYS_CHROOT.\n- ASSERT_NO_ERRNO(SetCapability(CAP_SYS_CHROOT, false));\n+ AutoCapability cap(CAP_SYS_CHROOT, false);\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nEXPECT_THAT(chroot(temp_dir.path().c_str()), SyscallFailsWithErrno(EPERM));\n@@ -97,51 +104,53 @@ TEST(ChrootTest, CreatesNewRoot) {\nauto file_in_new_root =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(new_root.path()));\n+ const auto rest = [&] {\n// chroot into new_root.\n- ASSERT_THAT(chroot(new_root.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(new_root.path().c_str()));\n// getcwd should return \"(unreachable)\" followed by the initial_cwd.\nchar cwd[1024];\n- ASSERT_THAT(syscall(__NR_getcwd, cwd, sizeof(cwd)), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(syscall(__NR_getcwd, cwd, sizeof(cwd)));\nstd::string expected_cwd = \"(unreachable)\";\nexpected_cwd += initial_cwd;\n- EXPECT_STREQ(cwd, expected_cwd.c_str());\n+ TEST_CHECK(strcmp(cwd, expected_cwd.c_str()) == 0);\n// Should not be able to stat file by its full path.\nstruct stat statbuf;\n- EXPECT_THAT(stat(file_in_new_root.path().c_str(), &statbuf),\n- SyscallFailsWithErrno(ENOENT));\n+ TEST_CHECK_ERRNO(stat(file_in_new_root.path().c_str(), &statbuf), ENOENT);\n// Should be able to stat file at new rooted path.\nauto basename = std::string(Basename(file_in_new_root.path()));\nauto rootedFile = \"/\" + basename;\n- ASSERT_THAT(stat(rootedFile.c_str(), &statbuf), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(stat(rootedFile.c_str(), &statbuf));\n// Should be able to stat cwd at '.' even though it's outside root.\n- ASSERT_THAT(stat(\".\", &statbuf), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(stat(\".\", &statbuf));\n// chdir into new root.\n- ASSERT_THAT(chdir(\"/\"), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chdir(\"/\"));\n// getcwd should return \"/\".\n- EXPECT_THAT(syscall(__NR_getcwd, cwd, sizeof(cwd)), SyscallSucceeds());\n- EXPECT_STREQ(cwd, \"/\");\n+ TEST_CHECK_SUCCESS(syscall(__NR_getcwd, cwd, sizeof(cwd)));\n+ TEST_CHECK_SUCCESS(strcmp(cwd, \"/\") == 0);\n// Statting '.', '..', '/', and '/..' all return the same dev and inode.\nstruct stat statbuf_dot;\n- ASSERT_THAT(stat(\".\", &statbuf_dot), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(stat(\".\", &statbuf_dot));\nstruct stat statbuf_dotdot;\n- ASSERT_THAT(stat(\"..\", &statbuf_dotdot), SyscallSucceeds());\n- EXPECT_EQ(statbuf_dot.st_dev, statbuf_dotdot.st_dev);\n- EXPECT_EQ(statbuf_dot.st_ino, statbuf_dotdot.st_ino);\n+ TEST_CHECK_SUCCESS(stat(\"..\", &statbuf_dotdot));\n+ TEST_CHECK(statbuf_dot.st_dev == statbuf_dotdot.st_dev);\n+ TEST_CHECK(statbuf_dot.st_ino == statbuf_dotdot.st_ino);\nstruct stat statbuf_slash;\n- ASSERT_THAT(stat(\"/\", &statbuf_slash), SyscallSucceeds());\n- EXPECT_EQ(statbuf_dot.st_dev, statbuf_slash.st_dev);\n- EXPECT_EQ(statbuf_dot.st_ino, statbuf_slash.st_ino);\n+ TEST_CHECK_SUCCESS(stat(\"/\", &statbuf_slash));\n+ TEST_CHECK(statbuf_dot.st_dev == statbuf_slash.st_dev);\n+ TEST_CHECK(statbuf_dot.st_ino == statbuf_slash.st_ino);\nstruct stat statbuf_slashdotdot;\n- ASSERT_THAT(stat(\"/..\", &statbuf_slashdotdot), SyscallSucceeds());\n- EXPECT_EQ(statbuf_dot.st_dev, statbuf_slashdotdot.st_dev);\n- EXPECT_EQ(statbuf_dot.st_ino, statbuf_slashdotdot.st_ino);\n+ TEST_CHECK_SUCCESS(stat(\"/..\", &statbuf_slashdotdot));\n+ TEST_CHECK(statbuf_dot.st_dev == statbuf_slashdotdot.st_dev);\n+ TEST_CHECK(statbuf_dot.st_ino == statbuf_slashdotdot.st_ino);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\nTEST(ChrootTest, DotDotFromOpenFD) {\n@@ -152,18 +161,20 @@ TEST(ChrootTest, DotDotFromOpenFD) {\nOpen(dir_outside_root.path(), O_RDONLY | O_DIRECTORY));\nauto new_root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ const auto rest = [&] {\n// chroot into new_root.\n- ASSERT_THAT(chroot(new_root.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(new_root.path().c_str()));\n// openat on fd with path .. will succeed.\nint other_fd;\n- ASSERT_THAT(other_fd = openat(fd.get(), \"..\", O_RDONLY), SyscallSucceeds());\n- EXPECT_THAT(close(other_fd), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(other_fd = openat(fd.get(), \"..\", O_RDONLY));\n+ TEST_CHECK_SUCCESS(close(other_fd));\n// getdents on fd should not error.\nchar buf[1024];\n- ASSERT_THAT(syscall(SYS_getdents64, fd.get(), buf, sizeof(buf)),\n- SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(syscall(SYS_getdents64, fd.get(), buf, sizeof(buf)));\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// Test that link resolution in a chroot can escape the root by following an\n@@ -179,24 +190,27 @@ TEST(ChrootTest, ProcFdLinkResolutionInChroot) {\nconst FileDescriptor proc_fd = ASSERT_NO_ERRNO_AND_VALUE(\nOpen(\"/proc\", O_DIRECTORY | O_RDONLY | O_CLOEXEC));\n+ const auto rest = [&] {\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- ASSERT_THAT(chroot(temp_dir.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(temp_dir.path().c_str()));\n- // Opening relative to an already open fd to a node outside the chroot works.\n- const FileDescriptor proc_self_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ // Opening relative to an already open fd to a node outside the chroot\n+ // works.\n+ const FileDescriptor proc_self_fd = TEST_CHECK_NO_ERRNO_AND_VALUE(\nOpenAt(proc_fd.get(), \"self/fd\", O_DIRECTORY | O_RDONLY | O_CLOEXEC));\n// Proc fd symlinks can escape the chroot if the fd the symlink refers to\n// refers to an object outside the chroot.\nstruct stat s = {};\n- EXPECT_THAT(\n- fstatat(proc_self_fd.get(), absl::StrCat(fd.get()).c_str(), &s, 0),\n- SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(\n+ fstatat(proc_self_fd.get(), absl::StrCat(fd.get()).c_str(), &s, 0));\n// Try to stat the stdin fd. Internally, this is handled differently from a\n// proc fd entry pointing to a file, since stdin is backed by a host fd, and\n// isn't a walkable path on the filesystem inside the sandbox.\n- EXPECT_THAT(fstatat(proc_self_fd.get(), \"0\", &s, 0), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(fstatat(proc_self_fd.get(), \"0\", &s, 0));\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// This test will verify that when you hold a fd to proc before entering\n@@ -209,28 +223,30 @@ TEST(ChrootTest, ProcMemSelfFdsNoEscapeProcOpen) {\nconst FileDescriptor proc =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc\", O_RDONLY));\n+ const auto rest = [&] {\n// Create and enter a chroot directory.\nconst auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- ASSERT_THAT(chroot(temp_dir.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(temp_dir.path().c_str()));\n// Open a file inside the chroot at /foo.\nconst FileDescriptor foo =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/foo\", O_CREAT | O_RDONLY, 0644));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(Open(\"/foo\", O_CREAT | O_RDONLY, 0644));\n// Examine /proc/self/fd/{foo_fd} to see if it exposes the fact that we're\n// inside a chroot, the path should be /foo and NOT {chroot_dir}/foo.\nconst std::string fd_path = absl::StrCat(\"self/fd/\", foo.get());\nchar buf[1024] = {};\nsize_t bytes_read = 0;\n- ASSERT_THAT(bytes_read =\n- readlinkat(proc.get(), fd_path.c_str(), buf, sizeof(buf) - 1),\n- SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(bytes_read = readlinkat(proc.get(), fd_path.c_str(), buf,\n+ sizeof(buf) - 1));\n// The link should resolve to something.\n- ASSERT_GT(bytes_read, 0);\n+ TEST_CHECK(bytes_read > 0);\n// Assert that the link doesn't contain the chroot path and is only /foo.\n- EXPECT_STREQ(buf, \"/foo\");\n+ TEST_CHECK(strcmp(buf, \"/foo\") == 0);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// This test will verify that a file inside a chroot when mmapped will not\n@@ -242,39 +258,41 @@ TEST(ChrootTest, ProcMemSelfMapsNoEscapeProcOpen) {\nconst FileDescriptor proc =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc\", O_RDONLY));\n+ const auto rest = [&] {\n// Create and enter a chroot directory.\n- const auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- ASSERT_THAT(chroot(temp_dir.path().c_str()), SyscallSucceeds());\n+ const auto temp_dir = TEST_CHECK_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TEST_CHECK_SUCCESS(chroot(temp_dir.path().c_str()));\n// Open a file inside the chroot at /foo.\nconst FileDescriptor foo =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/foo\", O_CREAT | O_RDONLY, 0644));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(Open(\"/foo\", O_CREAT | O_RDONLY, 0644));\n// Mmap the newly created file.\n- void* foo_map = mmap(nullptr, kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE,\n- foo.get(), 0);\n- ASSERT_THAT(reinterpret_cast<int64_t>(foo_map), SyscallSucceeds());\n+ void* foo_map = mmap(nullptr, kPageSize, PROT_READ | PROT_WRITE,\n+ MAP_PRIVATE, foo.get(), 0);\n+ TEST_CHECK_SUCCESS(reinterpret_cast<int64_t>(foo_map));\n// Always unmap.\n- auto cleanup_map = Cleanup(\n- [&] { EXPECT_THAT(munmap(foo_map, kPageSize), SyscallSucceeds()); });\n+ auto cleanup_map =\n+ Cleanup([&] { TEST_CHECK_SUCCESS(munmap(foo_map, kPageSize)); });\n// Examine /proc/self/maps to be sure that /foo doesn't appear to be\n// mapped with the full chroot path.\n- const FileDescriptor maps =\n- ASSERT_NO_ERRNO_AND_VALUE(OpenAt(proc.get(), \"self/maps\", O_RDONLY));\n+ const FileDescriptor maps = TEST_CHECK_NO_ERRNO_AND_VALUE(\n+ OpenAt(proc.get(), \"self/maps\", O_RDONLY));\nsize_t bytes_read = 0;\nchar buf[8 * 1024] = {};\n- ASSERT_THAT(bytes_read = ReadFd(maps.get(), buf, sizeof(buf)),\n- SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(bytes_read = ReadFd(maps.get(), buf, sizeof(buf)));\n// The maps file should have something.\n- ASSERT_GT(bytes_read, 0);\n+ TEST_CHECK(bytes_read > 0);\n// Finally we want to make sure the maps don't contain the chroot path\n- ASSERT_EQ(std::string(buf, bytes_read).find(temp_dir.path()),\n+ TEST_CHECK(std::string(buf, bytes_read).find(temp_dir.path()) ==\nstd::string::npos);\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// Test that mounts outside the chroot will not appear in /proc/self/mounts or\n@@ -283,81 +301,76 @@ TEST(ChrootTest, ProcMountsMountinfoNoEscape) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_CHROOT)));\n- // We are going to create some mounts and then chroot. In order to be able to\n- // unmount the mounts after the test run, we must chdir to the root and use\n- // relative paths for all mounts. That way, as long as we never chdir into\n- // the new root, we can access the mounts via relative paths and unmount them.\n- ASSERT_THAT(chdir(\"/\"), SyscallSucceeds());\n-\n- // Create nested tmpfs mounts. Note the use of relative paths in Mount calls.\n+ // Create nested tmpfs mounts.\nauto const outer_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- auto const outer_mount = ASSERT_NO_ERRNO_AND_VALUE(Mount(\n- \"none\", JoinPath(\".\", outer_dir.path()), \"tmpfs\", 0, \"mode=0700\", 0));\n+ auto const outer_mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"none\", outer_dir.path(), \"tmpfs\", 0, \"mode=0700\", 0));\nauto const inner_dir =\nASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(outer_dir.path()));\n- auto const inner_mount = ASSERT_NO_ERRNO_AND_VALUE(Mount(\n- \"none\", JoinPath(\".\", inner_dir.path()), \"tmpfs\", 0, \"mode=0700\", 0));\n+ auto const inner_mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"none\", inner_dir.path(), \"tmpfs\", 0, \"mode=0700\", 0));\n+ const auto rest = [&outer_dir, &inner_dir] {\n// Filenames that will be checked for mounts, all relative to /proc dir.\nstd::string paths[3] = {\"mounts\", \"self/mounts\", \"self/mountinfo\"};\nfor (const std::string& path : paths) {\n// We should have both inner and outer mounts.\nconst std::string contents =\n- ASSERT_NO_ERRNO_AND_VALUE(GetContents(JoinPath(\"/proc\", path)));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(GetContents(JoinPath(\"/proc\", path)));\nEXPECT_THAT(contents, AllOf(HasSubstr(outer_dir.path()),\nHasSubstr(inner_dir.path())));\n- // We better have at least two mounts: the mounts we created plus the root.\n+ // We better have at least two mounts: the mounts we created plus the\n+ // root.\nstd::vector<absl::string_view> submounts =\nabsl::StrSplit(contents, '\\n', absl::SkipWhitespace());\n- EXPECT_GT(submounts.size(), 2);\n+ TEST_CHECK(submounts.size() > 2);\n}\n// Get a FD to /proc before we enter the chroot.\nconst FileDescriptor proc =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc\", O_RDONLY));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(Open(\"/proc\", O_RDONLY));\n// Chroot to outer mount.\n- ASSERT_THAT(chroot(outer_dir.path().c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(outer_dir.path().c_str()));\nfor (const std::string& path : paths) {\nconst FileDescriptor proc_file =\n- ASSERT_NO_ERRNO_AND_VALUE(OpenAt(proc.get(), path, O_RDONLY));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(OpenAt(proc.get(), path, O_RDONLY));\n// Only two mounts visible from this chroot: the inner and outer. Both\n// paths should be relative to the new chroot.\nconst std::string contents =\n- ASSERT_NO_ERRNO_AND_VALUE(GetContentsFD(proc_file.get()));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(GetContentsFD(proc_file.get()));\nEXPECT_THAT(contents,\nAllOf(HasSubstr(absl::StrCat(Basename(inner_dir.path()))),\nNot(HasSubstr(outer_dir.path())),\nNot(HasSubstr(inner_dir.path()))));\nstd::vector<absl::string_view> submounts =\nabsl::StrSplit(contents, '\\n', absl::SkipWhitespace());\n- EXPECT_EQ(submounts.size(), 2);\n+ TEST_CHECK(submounts.size() == 2);\n}\n// Chroot to inner mount. We must use an absolute path accessible to our\n// chroot.\nconst std::string inner_dir_basename =\nabsl::StrCat(\"/\", Basename(inner_dir.path()));\n- ASSERT_THAT(chroot(inner_dir_basename.c_str()), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(chroot(inner_dir_basename.c_str()));\nfor (const std::string& path : paths) {\nconst FileDescriptor proc_file =\n- ASSERT_NO_ERRNO_AND_VALUE(OpenAt(proc.get(), path, O_RDONLY));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(OpenAt(proc.get(), path, O_RDONLY));\nconst std::string contents =\n- ASSERT_NO_ERRNO_AND_VALUE(GetContentsFD(proc_file.get()));\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(GetContentsFD(proc_file.get()));\n// Only the inner mount visible from this chroot.\nstd::vector<absl::string_view> submounts =\nabsl::StrSplit(contents, '\\n', absl::SkipWhitespace());\n- EXPECT_EQ(submounts.size(), 1);\n+ TEST_CHECK(submounts.size() == 1);\n}\n-\n- // Chroot back to \".\".\n- ASSERT_THAT(chroot(\".\"), SyscallSucceeds());\n+ };\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n} // namespace\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/getrusage.cc", "new_path": "test/syscalls/linux/getrusage.cc", "diff": "#include \"absl/time/time.h\"\n#include \"test/util/logging.h\"\n#include \"test/util/memory_util.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/signal_util.h\"\n#include \"test/util/test_util.h\"\n@@ -93,10 +94,11 @@ TEST(GetrusageTest, Grandchild) {\n// Verifies that processes ignoring SIGCHLD do not have updated child maxrss\n// updated.\nTEST(GetrusageTest, IgnoreSIGCHLD) {\n+ const auto rest = [] {\nstruct sigaction sa;\nsa.sa_handler = SIG_IGN;\nsa.sa_flags = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGCHLD, sa));\n+ auto cleanup = TEST_CHECK_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGCHLD, sa));\npid_t pid = fork();\nif (pid == 0) {\nstruct rusage rusage_self;\n@@ -105,23 +107,26 @@ TEST(GetrusageTest, IgnoreSIGCHLD) {\nTEST_CHECK(rusage_self.ru_maxrss != 0);\n_exit(0);\n}\n- ASSERT_THAT(pid, SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(pid);\nint status;\n- ASSERT_THAT(RetryEINTR(waitpid)(pid, &status, 0),\n- SyscallFailsWithErrno(ECHILD));\n+ TEST_CHECK_ERRNO(RetryEINTR(waitpid)(pid, &status, 0), ECHILD);\nstruct rusage rusage_self;\n- ASSERT_THAT(getrusage(RUSAGE_SELF, &rusage_self), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(getrusage(RUSAGE_SELF, &rusage_self));\nstruct rusage rusage_children;\n- ASSERT_THAT(getrusage(RUSAGE_CHILDREN, &rusage_children), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(getrusage(RUSAGE_CHILDREN, &rusage_children));\n// The parent has consumed some memory.\n- EXPECT_GT(rusage_self.ru_maxrss, 0);\n+ TEST_CHECK(rusage_self.ru_maxrss > 0);\n// The child's maxrss should not have propagated up.\n- EXPECT_EQ(rusage_children.ru_maxrss, 0);\n+ TEST_CHECK(rusage_children.ru_maxrss == 0);\n+ };\n+ // Execute inside a forked process so that rusage_children is clean.\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\n// Verifies that zombie processes do not update their parent's maxrss. Only\n// reaped processes should do this.\nTEST(GetrusageTest, IgnoreZombie) {\n+ const auto rest = [] {\npid_t pid = fork();\nif (pid == 0) {\nstruct rusage rusage_self;\n@@ -134,18 +139,21 @@ TEST(GetrusageTest, IgnoreZombie) {\nTEST_CHECK(rusage_children.ru_maxrss == 0);\n_exit(0);\n}\n- ASSERT_THAT(pid, SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(pid);\n// Give the child time to exit. Because we don't call wait, the child should\n// remain a zombie.\nabsl::SleepFor(absl::Seconds(5));\nstruct rusage rusage_self;\n- ASSERT_THAT(getrusage(RUSAGE_SELF, &rusage_self), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(getrusage(RUSAGE_SELF, &rusage_self));\nstruct rusage rusage_children;\n- ASSERT_THAT(getrusage(RUSAGE_CHILDREN, &rusage_children), SyscallSucceeds());\n+ TEST_CHECK_SUCCESS(getrusage(RUSAGE_CHILDREN, &rusage_children));\n// The parent has consumed some memory.\n- EXPECT_GT(rusage_self.ru_maxrss, 0);\n+ TEST_CHECK(rusage_self.ru_maxrss > 0);\n// The child has consumed some memory, but hasn't been reaped.\n- EXPECT_EQ(rusage_children.ru_maxrss, 0);\n+ TEST_CHECK(rusage_children.ru_maxrss == 0);\n+ };\n+ // Execute inside a forked process so that rusage_children is clean.\n+ EXPECT_THAT(InForkedProcess(rest), IsPosixErrorOkAndHolds(0));\n}\nTEST(GetrusageTest, Wait4) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc_net_unix.cc", "new_path": "test/syscalls/linux/proc_net_unix.cc", "diff": "#include \"absl/strings/str_join.h\"\n#include \"absl/strings/str_split.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/cleanup.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/test_util.h\"\n@@ -341,6 +342,8 @@ TEST(ProcNetUnix, StreamSocketStateStateConnectedOnAccept) {\nint clientfd;\nASSERT_THAT(clientfd = accept(sockets->first_fd(), nullptr, nullptr),\nSyscallSucceeds());\n+ auto cleanup = Cleanup(\n+ [clientfd]() { ASSERT_THAT(close(clientfd), SyscallSucceeds()); });\n// Find the entry for the accepted socket. UDS proc entries don't have a\n// remote address, so we distinguish the accepted socket from the listen\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/uidgid.cc", "new_path": "test/syscalls/linux/uidgid.cc", "diff": "#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_join.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -33,6 +35,16 @@ ABSL_FLAG(int32_t, scratch_uid2, 65533, \"second scratch UID\");\nABSL_FLAG(int32_t, scratch_gid1, 65534, \"first scratch GID\");\nABSL_FLAG(int32_t, scratch_gid2, 65533, \"second scratch GID\");\n+// Force use of syscall instead of glibc set*id() wrappers because we want to\n+// apply to the current task only. libc sets all threads in a process because\n+// \"POSIX requires that all threads in a process share the same credentials.\"\n+#define setuid USE_SYSCALL_INSTEAD\n+#define setgid USE_SYSCALL_INSTEAD\n+#define setreuid USE_SYSCALL_INSTEAD\n+#define setregid USE_SYSCALL_INSTEAD\n+#define setresuid USE_SYSCALL_INSTEAD\n+#define setresgid USE_SYSCALL_INSTEAD\n+\nusing ::testing::UnorderedElementsAreArray;\nnamespace gvisor {\n@@ -137,21 +149,31 @@ TEST(UidGidRootTest, Setuid) {\nTEST(UidGidRootTest, Setgid) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n- EXPECT_THAT(setgid(-1), SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(syscall(SYS_setgid, -1), SyscallFailsWithErrno(EINVAL));\n+ ScopedThread([&] {\nconst gid_t gid = absl::GetFlag(FLAGS_scratch_gid1);\n- ASSERT_THAT(setgid(gid), SyscallSucceeds());\n+ EXPECT_THAT(syscall(SYS_setgid, gid), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckGIDs(gid, gid, gid));\n+ });\n}\nTEST(UidGidRootTest, SetgidNotFromThreadGroupLeader) {\n+#pragma push_macro(\"allow_setgid\")\n+#undef setgid\n+\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n+ int old_gid = getgid();\n+ auto clean = Cleanup([old_gid] { setgid(old_gid); });\n+\nconst gid_t gid = absl::GetFlag(FLAGS_scratch_gid1);\n// NOTE(b/64676707): Do setgid in a separate thread so that we can test if\n// info.si_pid is set correctly.\nScopedThread([gid] { ASSERT_THAT(setgid(gid), SyscallSucceeds()); });\nEXPECT_NO_ERRNO(CheckGIDs(gid, gid, gid));\n+\n+#pragma pop_macro(\"allow_setgid\")\n}\nTEST(UidGidRootTest, Setreuid) {\n@@ -159,27 +181,25 @@ TEST(UidGidRootTest, Setreuid) {\n// \"Supplying a value of -1 for either the real or effective user ID forces\n// the system to leave that ID unchanged.\" - setreuid(2)\n- EXPECT_THAT(setreuid(-1, -1), SyscallSucceeds());\n+ EXPECT_THAT(syscall(SYS_setreuid, -1, -1), SyscallSucceeds());\n+\nEXPECT_NO_ERRNO(CheckUIDs(0, 0, 0));\n// Do setuid in a separate thread so that after finishing this test, the\n- // process can still open files the test harness created before starting this\n- // test. Otherwise, the files are created by root (UID before the test), but\n- // cannot be opened by the `uid` set below after the test. After calling\n- // setuid(non-zero-UID), there is no way to get root privileges back.\n+ // process can still open files the test harness created before starting\n+ // this test. Otherwise, the files are created by root (UID before the\n+ // test), but cannot be opened by the `uid` set below after the test. After\n+ // calling setuid(non-zero-UID), there is no way to get root privileges\n+ // back.\nScopedThread([&] {\nconst uid_t ruid = absl::GetFlag(FLAGS_scratch_uid1);\nconst uid_t euid = absl::GetFlag(FLAGS_scratch_uid2);\n- // Use syscall instead of glibc setuid wrapper because we want this setuid\n- // call to only apply to this task. posix threads, however, require that all\n- // threads have the same UIDs, so using the setuid wrapper sets all threads'\n- // real UID.\nEXPECT_THAT(syscall(SYS_setreuid, ruid, euid), SyscallSucceeds());\n// \"If the real user ID is set or the effective user ID is set to a value\n- // not equal to the previous real user ID, the saved set-user-ID will be set\n- // to the new effective user ID.\" - setreuid(2)\n+ // not equal to the previous real user ID, the saved set-user-ID will be\n+ // set to the new effective user ID.\" - setreuid(2)\nEXPECT_NO_ERRNO(CheckUIDs(ruid, euid, euid));\n});\n}\n@@ -187,13 +207,15 @@ TEST(UidGidRootTest, Setreuid) {\nTEST(UidGidRootTest, Setregid) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n- EXPECT_THAT(setregid(-1, -1), SyscallSucceeds());\n+ EXPECT_THAT(syscall(SYS_setregid, -1, -1), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckGIDs(0, 0, 0));\n+ ScopedThread([&] {\nconst gid_t rgid = absl::GetFlag(FLAGS_scratch_gid1);\nconst gid_t egid = absl::GetFlag(FLAGS_scratch_gid2);\n- ASSERT_THAT(setregid(rgid, egid), SyscallSucceeds());\n+ ASSERT_THAT(syscall(SYS_setregid, rgid, egid), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckGIDs(rgid, egid, egid));\n+ });\n}\nTEST(UidGidRootTest, Setresuid) {\n@@ -201,23 +223,24 @@ TEST(UidGidRootTest, Setresuid) {\n// \"If one of the arguments equals -1, the corresponding value is not\n// changed.\" - setresuid(2)\n- EXPECT_THAT(setresuid(-1, -1, -1), SyscallSucceeds());\n+ EXPECT_THAT(syscall(SYS_setresuid, -1, -1, -1), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckUIDs(0, 0, 0));\n// Do setuid in a separate thread so that after finishing this test, the\n- // process can still open files the test harness created before starting this\n- // test. Otherwise, the files are created by root (UID before the test), but\n- // cannot be opened by the `uid` set below after the test. After calling\n- // setuid(non-zero-UID), there is no way to get root privileges back.\n+ // process can still open files the test harness created before starting\n+ // this test. Otherwise, the files are created by root (UID before the\n+ // test), but cannot be opened by the `uid` set below after the test. After\n+ // calling setuid(non-zero-UID), there is no way to get root privileges\n+ // back.\nScopedThread([&] {\nconst uid_t ruid = 12345;\nconst uid_t euid = 23456;\nconst uid_t suid = 34567;\n// Use syscall instead of glibc setuid wrapper because we want this setuid\n- // call to only apply to this task. posix threads, however, require that all\n- // threads have the same UIDs, so using the setuid wrapper sets all threads'\n- // real UID.\n+ // call to only apply to this task. posix threads, however, require that\n+ // all threads have the same UIDs, so using the setuid wrapper sets all\n+ // threads' real UID.\nEXPECT_THAT(syscall(SYS_setresuid, ruid, euid, suid), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckUIDs(ruid, euid, suid));\n});\n@@ -226,14 +249,16 @@ TEST(UidGidRootTest, Setresuid) {\nTEST(UidGidRootTest, Setresgid) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n- EXPECT_THAT(setresgid(-1, -1, -1), SyscallSucceeds());\n+ EXPECT_THAT(syscall(SYS_setresgid, -1, -1, -1), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckGIDs(0, 0, 0));\n+ ScopedThread([&] {\nconst gid_t rgid = 12345;\nconst gid_t egid = 23456;\nconst gid_t sgid = 34567;\n- ASSERT_THAT(setresgid(rgid, egid, sgid), SyscallSucceeds());\n+ ASSERT_THAT(syscall(SYS_setresgid, rgid, egid, sgid), SyscallSucceeds());\nEXPECT_NO_ERRNO(CheckGIDs(rgid, egid, sgid));\n+ });\n}\nTEST(UidGidRootTest, Setgroups) {\n@@ -254,14 +279,14 @@ TEST(UidGidRootTest, Setuid_prlimit) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(IsRoot()));\n// Do seteuid in a separate thread so that after finishing this test, the\n- // process can still open files the test harness created before starting this\n- // test. Otherwise, the files are created by root (UID before the test), but\n- // cannot be opened by the `uid` set below after the test.\n+ // process can still open files the test harness created before starting\n+ // this test. Otherwise, the files are created by root (UID before the\n+ // test), but cannot be opened by the `uid` set below after the test.\nScopedThread([&] {\n- // Use syscall instead of glibc setuid wrapper because we want this seteuid\n- // call to only apply to this task. POSIX threads, however, require that all\n- // threads have the same UIDs, so using the seteuid wrapper sets all\n- // threads' UID.\n+ // Use syscall instead of glibc setuid wrapper because we want this\n+ // seteuid call to only apply to this task. POSIX threads, however,\n+ // require that all threads have the same UIDs, so using the seteuid\n+ // wrapper sets all threads' UID.\nEXPECT_THAT(syscall(SYS_setreuid, -1, 65534), SyscallSucceeds());\n// Despite the UID change, we should be able to get our own limits.\n" }, { "change_type": "MODIFY", "old_path": "test/util/capability_util.h", "new_path": "test/util/capability_util.h", "diff": "@@ -96,6 +96,19 @@ inline PosixError DropPermittedCapability(int cap) {\nPosixErrorOr<bool> CanCreateUserNamespace();\n+class AutoCapability {\n+ public:\n+ AutoCapability(int cap, bool set) : cap_(cap), set_(set) {\n+ EXPECT_NO_ERRNO(SetCapability(cap_, set_));\n+ }\n+\n+ ~AutoCapability() { EXPECT_NO_ERRNO(SetCapability(cap_, !set_)); }\n+\n+ private:\n+ int cap_;\n+ bool set_;\n+};\n+\n} // namespace testing\n} // namespace gvisor\n#endif // GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_\n" }, { "change_type": "MODIFY", "old_path": "test/util/logging.h", "new_path": "test/util/logging.h", "diff": "@@ -96,6 +96,21 @@ void CheckFailure(const char* cond, size_t cond_size, const char* msg,\nstd::move(_expr_result).ValueOrDie(); \\\n})\n+// cond must be greater or equal than 0. Used to test result of syscalls.\n+//\n+// This macro is async-signal-safe.\n+#define TEST_CHECK_SUCCESS(cond) TEST_PCHECK((cond) >= 0)\n+\n+// cond must be -1 and errno must match errno_value. Used to test errors from\n+// syscalls.\n+//\n+// This macro is async-signal-safe.\n+#define TEST_CHECK_ERRNO(cond, errno_value) \\\n+ do { \\\n+ TEST_PCHECK((cond) == -1); \\\n+ TEST_PCHECK_MSG(errno == (errno_value), #cond \" expected \" #errno_value); \\\n+ } while (0)\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
Remove side effect from test cases Individual test cases must not rely on being executed in a clean environment. PiperOrigin-RevId: 354604389
259,891
29.01.2021 14:46:41
28,800
66aa6f3d4fb148145ab1b91c49f483d501185ff8
setgid directory syscall tests
[ { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -556,6 +556,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:sendfile_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:setgid_test\",\n+)\n+\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:splice_test\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2145,6 +2145,24 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"setgid_test\",\n+ testonly = 1,\n+ srcs = [\"setgid.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ \"//test/util:cleanup\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:posix_error\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/strings\",\n+ gtest,\n+ ],\n+)\n+\ncc_binary(\nname = \"splice_test\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/setgid.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 <limits.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/posix_error.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+constexpr int kDirmodeMask = 07777;\n+constexpr int kDirmodeSgid = S_ISGID | 0777;\n+constexpr int kDirmodeNoExec = S_ISGID | 0767;\n+constexpr int kDirmodeNoSgid = 0777;\n+\n+// Sets effective GID and returns a Cleanup that restores the original.\n+PosixErrorOr<Cleanup> Setegid(gid_t egid) {\n+ gid_t old_gid = getegid();\n+ if (setegid(egid) < 0) {\n+ return PosixError(errno, absl::StrFormat(\"setegid(%d)\", egid));\n+ }\n+ return Cleanup(\n+ [old_gid]() { EXPECT_THAT(setegid(old_gid), SyscallSucceeds()); });\n+}\n+\n+// Returns a pair of groups that the user is a member of.\n+PosixErrorOr<std::pair<gid_t, gid_t>> Groups() {\n+ // See whether the user is a member of at least 2 groups.\n+ std::vector<gid_t> groups(64);\n+ for (; groups.size() <= NGROUPS_MAX; groups.resize(groups.size() * 2)) {\n+ int ngroups = getgroups(groups.size(), groups.data());\n+ if (ngroups < 0 && errno == EINVAL) {\n+ // Need a larger list.\n+ continue;\n+ }\n+ if (ngroups < 0) {\n+ return PosixError(errno, absl::StrFormat(\"getgroups(%d, %p)\",\n+ groups.size(), groups.data()));\n+ }\n+ if (ngroups >= 2) {\n+ return std::pair<gid_t, gid_t>(groups[0], groups[1]);\n+ }\n+ // There aren't enough groups.\n+ break;\n+ }\n+\n+ // If we're root in the root user namespace, we can set our GID to whatever we\n+ // want. Try that before giving up.\n+ constexpr gid_t kGID1 = 1111;\n+ constexpr gid_t kGID2 = 2222;\n+ auto cleanup1 = Setegid(kGID1);\n+ if (!cleanup1.ok()) {\n+ return cleanup1.error();\n+ }\n+ auto cleanup2 = Setegid(kGID2);\n+ if (!cleanup2.ok()) {\n+ return cleanup2.error();\n+ }\n+ return std::pair<gid_t, gid_t>(kGID1, kGID2);\n+}\n+\n+class SetgidDirTest : public ::testing::Test {\n+ protected:\n+ void SetUp() override {\n+ original_gid_ = getegid();\n+\n+ // TODO(b/175325250): Enable when setgid directories are supported.\n+ SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETGID)));\n+\n+ temp_dir_ = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0777 /* mode */));\n+ groups_ = ASSERT_NO_ERRNO_AND_VALUE(Groups());\n+ }\n+\n+ void TearDown() override {\n+ ASSERT_THAT(setegid(original_gid_), SyscallSucceeds());\n+ }\n+\n+ void MkdirAsGid(gid_t gid, const std::string& path, mode_t mode) {\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(Setegid(gid));\n+ ASSERT_THAT(mkdir(path.c_str(), mode), SyscallSucceeds());\n+ }\n+\n+ PosixErrorOr<struct stat> Stat(const std::string& path) {\n+ struct stat stats;\n+ if (stat(path.c_str(), &stats) < 0) {\n+ return PosixError(errno, absl::StrFormat(\"stat(%s, _)\", path));\n+ }\n+ return stats;\n+ }\n+\n+ PosixErrorOr<struct stat> Stat(const FileDescriptor& fd) {\n+ struct stat stats;\n+ if (fstat(fd.get(), &stats) < 0) {\n+ return PosixError(errno, \"fstat(_, _)\");\n+ }\n+ return stats;\n+ }\n+\n+ TempPath temp_dir_;\n+ std::pair<gid_t, gid_t> groups_;\n+ gid_t original_gid_;\n+};\n+\n+// The control test. Files created with a given GID are owned by that group.\n+TEST_F(SetgidDirTest, Control) {\n+ // Set group to G1 and create a directory.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, 0777));\n+\n+ // Set group to G2, create a file in g1owned, and confirm that G2 owns it.\n+ ASSERT_THAT(setegid(groups_.second), SyscallSucceeds());\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(g1owned, \"g2owned\").c_str(), O_CREAT | O_RDWR, 0777));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+}\n+\n+// Setgid directories cause created files to inherit GID.\n+TEST_F(SetgidDirTest, CreateFile) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeSgid));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeSgid), SyscallSucceeds());\n+\n+ // Set group to G2, create a file, and confirm that G1 owns it.\n+ ASSERT_THAT(setegid(groups_.second), SyscallSucceeds());\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(g1owned, \"g2created\").c_str(), O_CREAT | O_RDWR, 0666));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.first);\n+}\n+\n+// Setgid directories cause created directories to inherit GID.\n+TEST_F(SetgidDirTest, CreateDir) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeSgid));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeSgid), SyscallSucceeds());\n+\n+ // Set group to G2, create a directory, confirm that G1 owns it, and that the\n+ // setgid bit is enabled.\n+ auto g2created = JoinPath(g1owned, \"g2created\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.second, g2created, 0666));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(g2created));\n+ EXPECT_EQ(stats.st_gid, groups_.first);\n+ EXPECT_EQ(stats.st_mode & S_ISGID, S_ISGID);\n+}\n+\n+// Setgid directories with group execution disabled still cause GID inheritance.\n+TEST_F(SetgidDirTest, NoGroupExec) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeNoExec));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeNoExec), SyscallSucceeds());\n+\n+ // Set group to G2, create a directory, confirm that G2 owns it, and that the\n+ // setgid bit is enabled.\n+ auto g2created = JoinPath(g1owned, \"g2created\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.second, g2created, 0666));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(g2created));\n+ EXPECT_EQ(stats.st_gid, groups_.first);\n+ EXPECT_EQ(stats.st_mode & S_ISGID, S_ISGID);\n+}\n+\n+// Setting the setgid bit on directories with an existing file does not change\n+// the file's group.\n+TEST_F(SetgidDirTest, OldFile) {\n+ // Set group to G1 and create a directory.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeNoSgid));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeNoSgid), SyscallSucceeds());\n+\n+ // Set group to G2, create a file, confirm that G2 owns it.\n+ ASSERT_THAT(setegid(groups_.second), SyscallSucceeds());\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(g1owned, \"g2created\").c_str(), O_CREAT | O_RDWR, 0666));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+\n+ // Enable setgid.\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeSgid), SyscallSucceeds());\n+\n+ // Confirm that the file's group is still G2.\n+ stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+}\n+\n+// Setting the setgid bit on directories with an existing subdirectory does not\n+// change the subdirectory's group.\n+TEST_F(SetgidDirTest, OldDir) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeNoSgid));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeNoSgid), SyscallSucceeds());\n+\n+ // Set group to G2, create a directory, confirm that G2 owns it.\n+ ASSERT_THAT(setegid(groups_.second), SyscallSucceeds());\n+ auto g2created = JoinPath(g1owned, \"g2created\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.second, g2created, 0666));\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(g2created));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+\n+ // Enable setgid.\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeSgid), SyscallSucceeds());\n+\n+ // Confirm that the file's group is still G2.\n+ stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(g2created));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+}\n+\n+// Chowning a file clears the setgid and setuid bits.\n+TEST_F(SetgidDirTest, ChownFileClears) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeMask));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeMask), SyscallSucceeds());\n+\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(g1owned, \"newfile\").c_str(), O_CREAT | O_RDWR, 0666));\n+ ASSERT_THAT(fchmod(fd.get(), 0777 | S_ISUID | S_ISGID), SyscallSucceeds());\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.first);\n+ EXPECT_EQ(stats.st_mode & (S_ISUID | S_ISGID), S_ISUID | S_ISGID);\n+\n+ // Change the owning group.\n+ ASSERT_THAT(fchown(fd.get(), -1, groups_.second), SyscallSucceeds());\n+\n+ // The setgid and setuid bits should be cleared.\n+ stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+ EXPECT_EQ(stats.st_mode & (S_ISUID | S_ISGID), 0);\n+}\n+\n+// Chowning a file with setgid enabled, but not the group exec bit, does not\n+// clear the setgid bit. Such files are mandatory locked.\n+TEST_F(SetgidDirTest, ChownNoExecFileDoesNotClear) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeNoExec));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeNoExec), SyscallSucceeds());\n+\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(g1owned, \"newdir\").c_str(), O_CREAT | O_RDWR, 0666));\n+ ASSERT_THAT(fchmod(fd.get(), 0766 | S_ISUID | S_ISGID), SyscallSucceeds());\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.first);\n+ EXPECT_EQ(stats.st_mode & (S_ISUID | S_ISGID), S_ISUID | S_ISGID);\n+\n+ // Change the owning group.\n+ ASSERT_THAT(fchown(fd.get(), -1, groups_.second), SyscallSucceeds());\n+\n+ // Only the setuid bit is cleared.\n+ stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(fd));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+ EXPECT_EQ(stats.st_mode & (S_ISUID | S_ISGID), S_ISGID);\n+}\n+\n+// Chowning a directory with setgid enabled does not clear the bit.\n+TEST_F(SetgidDirTest, ChownDirDoesNotClear) {\n+ // Set group to G1, create a directory, and enable setgid.\n+ auto g1owned = JoinPath(temp_dir_.path(), \"g1owned/\");\n+ ASSERT_NO_FATAL_FAILURE(MkdirAsGid(groups_.first, g1owned, kDirmodeMask));\n+ ASSERT_THAT(chmod(g1owned.c_str(), kDirmodeMask), SyscallSucceeds());\n+\n+ // Change the owning group.\n+ ASSERT_THAT(chown(g1owned.c_str(), -1, groups_.second), SyscallSucceeds());\n+\n+ struct stat stats = ASSERT_NO_ERRNO_AND_VALUE(Stat(g1owned));\n+ EXPECT_EQ(stats.st_gid, groups_.second);\n+ EXPECT_EQ(stats.st_mode & kDirmodeMask, kDirmodeMask);\n+}\n+\n+struct FileModeTestcase {\n+ std::string name;\n+ mode_t mode;\n+ mode_t result_mode;\n+\n+ FileModeTestcase(const std::string& name, mode_t mode, mode_t result_mode)\n+ : name(name), mode(mode), result_mode(result_mode) {}\n+};\n+\n+class FileModeTest : public ::testing::TestWithParam<FileModeTestcase> {};\n+\n+TEST_P(FileModeTest, WriteToFile) {\n+ // TODO(b/175325250): Enable when setgid directories are supported.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0777 /* mode */));\n+ auto path = JoinPath(temp_dir.path(), GetParam().name);\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(path.c_str(), O_CREAT | O_RDWR, 0666));\n+ ASSERT_THAT(fchmod(fd.get(), GetParam().mode), SyscallSucceeds());\n+ struct stat stats;\n+ ASSERT_THAT(fstat(fd.get(), &stats), SyscallSucceeds());\n+ EXPECT_EQ(stats.st_mode & kDirmodeMask, GetParam().mode);\n+\n+ // For security reasons, writing to the file clears the SUID bit, and clears\n+ // the SGID bit when the group executable bit is unset (which is not a true\n+ // SGID binary).\n+ constexpr char kInput = 'M';\n+ ASSERT_THAT(write(fd.get(), &kInput, sizeof(kInput)),\n+ SyscallSucceedsWithValue(sizeof(kInput)));\n+\n+ ASSERT_THAT(fstat(fd.get(), &stats), SyscallSucceeds());\n+ EXPECT_EQ(stats.st_mode & kDirmodeMask, GetParam().result_mode);\n+}\n+\n+TEST_P(FileModeTest, TruncateFile) {\n+ // TODO(b/175325250): Enable when setgid directories are supported.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0777 /* mode */));\n+ auto path = JoinPath(temp_dir.path(), GetParam().name);\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(path.c_str(), O_CREAT | O_RDWR, 0666));\n+ ASSERT_THAT(fchmod(fd.get(), GetParam().mode), SyscallSucceeds());\n+ struct stat stats;\n+ ASSERT_THAT(fstat(fd.get(), &stats), SyscallSucceeds());\n+ EXPECT_EQ(stats.st_mode & kDirmodeMask, GetParam().mode);\n+\n+ // For security reasons, truncating the file clears the SUID bit, and clears\n+ // the SGID bit when the group executable bit is unset (which is not a true\n+ // SGID binary).\n+ ASSERT_THAT(ftruncate(fd.get(), 0), SyscallSucceeds());\n+\n+ ASSERT_THAT(fstat(fd.get(), &stats), SyscallSucceeds());\n+ EXPECT_EQ(stats.st_mode & kDirmodeMask, GetParam().result_mode);\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ FileModes, FileModeTest,\n+ ::testing::ValuesIn<FileModeTestcase>(\n+ {FileModeTestcase(\"normal file\", 0777, 0777),\n+ FileModeTestcase(\"setuid\", S_ISUID | 0777, 00777),\n+ FileModeTestcase(\"setgid\", S_ISGID | 0777, 00777),\n+ FileModeTestcase(\"setuid and setgid\", S_ISUID | S_ISGID | 0777, 00777),\n+ FileModeTestcase(\"setgid without exec\", S_ISGID | 0767,\n+ S_ISGID | 0767),\n+ FileModeTestcase(\"setuid and setgid without exec\",\n+ S_ISGID | S_ISUID | 0767, S_ISGID | 0767)}));\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
setgid directory syscall tests PiperOrigin-RevId: 354615220
260,004
29.01.2021 16:09:14
28,800
45fe9fe9c6fa92954a5017b98835eac5fd8d3987
Clear IGMPv1 present flag on NIC down This is dynamic state that can be re-learned when the NIC comes back up. Test: ipv4_test.TestIgmpV1Present
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp.go", "new_path": "pkg/tcpip/network/ipv4/igmp.go", "diff": "@@ -215,6 +215,11 @@ func (igmp *igmpState) setV1Present(v bool) {\n}\n}\n+func (igmp *igmpState) resetV1Present() {\n+ igmp.igmpV1Job.Cancel()\n+ igmp.setV1Present(false)\n+}\n+\n// handleMembershipQuery handles a membership query.\n//\n// Precondition: igmp.ep.mu must be locked.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/igmp_test.go", "new_path": "pkg/tcpip/network/ipv4/igmp_test.go", "diff": "@@ -101,10 +101,10 @@ func createAndInjectIGMPPacket(e *channel.Endpoint, igmpType header.IGMPType, ma\n})\n}\n-// TestIgmpV1Present tests the handling of the case where an IGMPv1 router is\n-// present on the network. The IGMP stack will then send IGMPv1 Membership\n-// reports for backwards compatibility.\n-func TestIgmpV1Present(t *testing.T) {\n+// TestIGMPV1Present tests the node's ability to fallback to V1 when a V1\n+// router is detected. V1 present status is expected to be reset when the NIC\n+// cycles.\n+func TestIGMPV1Present(t *testing.T) {\ne, s, clock := createStack(t, true)\nif err := s.AddAddress(nicID, ipv4.ProtocolNumber, addr); err != nil {\nt.Fatalf(\"AddAddress(%d, %d, %s): %s\", nicID, ipv4.ProtocolNumber, addr, err)\n@@ -116,6 +116,7 @@ func TestIgmpV1Present(t *testing.T) {\n// This NIC will send an IGMPv2 report immediately, before this test can get\n// the IGMPv1 General Membership Query in.\n+ {\np, ok := e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n@@ -124,6 +125,7 @@ func TestIgmpV1Present(t *testing.T) {\nt.Fatalf(\"got V2MembershipReport messages sent = %d, want = 1\", got)\n}\nvalidateIgmpPacket(t, p, multicastAddr, header.IGMPv2MembershipReport, 0, multicastAddr)\n+ }\nif t.Failed() {\nt.FailNow()\n}\n@@ -145,12 +147,12 @@ func TestIgmpV1Present(t *testing.T) {\n// Verify the solicited Membership Report is sent. Now that this NIC has seen\n// an IGMPv1 query, it should send an IGMPv1 Membership Report.\n- p, ok = e.Read()\n- if ok {\n+ if p, ok := e.Read(); ok {\nt.Fatalf(\"sent unexpected packet, expected V1MembershipReport only after advancing the clock = %+v\", p.Pkt)\n}\nclock.Advance(ipv4.UnsolicitedReportIntervalMax)\n- p, ok = e.Read()\n+ {\n+ p, ok := e.Read()\nif !ok {\nt.Fatal(\"unable to Read IGMP packet, expected V1MembershipReport\")\n}\n@@ -160,6 +162,25 @@ func TestIgmpV1Present(t *testing.T) {\nvalidateIgmpPacket(t, p, multicastAddr, header.IGMPv1MembershipReport, 0, multicastAddr)\n}\n+ // Cycling the interface should reset the V1 present flag.\n+ if err := s.DisableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.DisableNIC(%d): %s\", nicID, err)\n+ }\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n+ }\n+ {\n+ p, ok := e.Read()\n+ if !ok {\n+ t.Fatal(\"unable to Read IGMP packet, expected V2MembershipReport\")\n+ }\n+ if got := s.Stats().IGMP.PacketsSent.V2MembershipReport.Value(); got != 2 {\n+ t.Fatalf(\"got V2MembershipReport messages sent = %d, want = 2\", got)\n+ }\n+ validateIgmpPacket(t, p, multicastAddr, header.IGMPv2MembershipReport, 0, multicastAddr)\n+ }\n+}\n+\nfunc TestSendQueuedIGMPReports(t *testing.T) {\ne, s, clock := createStack(t, true)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -229,6 +229,12 @@ func (e *endpoint) disableLocked() {\npanic(fmt.Sprintf(\"unexpected error when removing address = %s: %s\", ipv4BroadcastAddr.Address, err))\n}\n+ // Reset the IGMP V1 present flag.\n+ //\n+ // If the node comes back up on the same network, it will re-learn that it\n+ // needs to perform IGMPv1.\n+ e.mu.igmp.resetV1Present()\n+\nif !e.setEnabled(false) {\npanic(\"should have only done work to disable the endpoint if it was enabled\")\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Clear IGMPv1 present flag on NIC down This is dynamic state that can be re-learned when the NIC comes back up. Test: ipv4_test.TestIgmpV1Present PiperOrigin-RevId: 354630921
259,992
30.01.2021 13:35:59
28,800
ccf9138e6de27e666129e97b8c2ff9d117f69f60
Remove side effect from open tests Individual test cases must not rely on being executed in a clean environment.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1383,6 +1383,7 @@ cc_binary(\n\"//test/util:file_descriptor\",\n\"//test/util:fs_util\",\ngtest,\n+ \"//test/util:posix_error\",\n\"//test/util:temp_path\",\n\"//test/util:temp_umask\",\n\"//test/util:test_main\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/open.cc", "new_path": "test/syscalls/linux/open.cc", "diff": "@@ -75,55 +75,52 @@ class OpenTest : public FileTest {\n};\nTEST_F(OpenTest, OTrunc) {\n- auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n- ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n- ASSERT_THAT(open(dirpath.c_str(), O_TRUNC, 0666),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(open(dir.path().c_str(), O_TRUNC, 0666),\nSyscallFailsWithErrno(EISDIR));\n}\nTEST_F(OpenTest, OTruncAndReadOnlyDir) {\n- auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n- ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n- ASSERT_THAT(open(dirpath.c_str(), O_TRUNC | O_RDONLY, 0666),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(open(dir.path().c_str(), O_TRUNC | O_RDONLY, 0666),\nSyscallFailsWithErrno(EISDIR));\n}\nTEST_F(OpenTest, OTruncAndReadOnlyFile) {\n- auto dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncfile\");\n- const FileDescriptor existing =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(dirpath.c_str(), O_RDWR | O_CREAT, 0666));\n- const FileDescriptor otrunc = ASSERT_NO_ERRNO_AND_VALUE(\n- Open(dirpath.c_str(), O_TRUNC | O_RDONLY, 0666));\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto path = JoinPath(dir.path(), \"foo\");\n+ EXPECT_NO_ERRNO(Open(path, O_RDWR | O_CREAT, 0666));\n+ EXPECT_NO_ERRNO(Open(path, O_TRUNC | O_RDONLY, 0666));\n}\nTEST_F(OpenTest, OCreateDirectory) {\nSKIP_IF(IsRunningWithVFS1());\n- auto dirpath = GetAbsoluteTestTmpdir();\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n// Normal case: existing directory.\n- ASSERT_THAT(open(dirpath.c_str(), O_RDWR | O_CREAT, 0666),\n+ ASSERT_THAT(open(dir.path().c_str(), O_RDWR | O_CREAT, 0666),\nSyscallFailsWithErrno(EISDIR));\n// Trailing separator on existing directory.\n- ASSERT_THAT(open(dirpath.append(\"/\").c_str(), O_RDWR | O_CREAT, 0666),\n+ ASSERT_THAT(open(dir.path().append(\"/\").c_str(), O_RDWR | O_CREAT, 0666),\nSyscallFailsWithErrno(EISDIR));\n// Trailing separator on non-existing directory.\n- ASSERT_THAT(open(JoinPath(dirpath, \"non-existent\").append(\"/\").c_str(),\n+ ASSERT_THAT(open(JoinPath(dir.path(), \"non-existent\").append(\"/\").c_str(),\nO_RDWR | O_CREAT, 0666),\nSyscallFailsWithErrno(EISDIR));\n// \".\" special case.\n- ASSERT_THAT(open(JoinPath(dirpath, \".\").c_str(), O_RDWR | O_CREAT, 0666),\n+ ASSERT_THAT(open(JoinPath(dir.path(), \".\").c_str(), O_RDWR | O_CREAT, 0666),\nSyscallFailsWithErrno(EISDIR));\n}\nTEST_F(OpenTest, MustCreateExisting) {\n- auto dirPath = GetAbsoluteTestTmpdir();\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n// Existing directory.\n- ASSERT_THAT(open(dirPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0666),\n+ ASSERT_THAT(open(dir.path().c_str(), O_RDWR | O_CREAT | O_EXCL, 0666),\nSyscallFailsWithErrno(EEXIST));\n// Existing file.\n- auto newFile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dirPath));\n+ auto newFile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir.path()));\nASSERT_THAT(open(newFile.path().c_str(), O_RDWR | O_CREAT | O_EXCL, 0666),\nSyscallFailsWithErrno(EEXIST));\n}\n@@ -206,7 +203,8 @@ TEST_F(OpenTest, AtAbsPath) {\n}\nTEST_F(OpenTest, OpenNoFollowSymlink) {\n- const std::string link_path = JoinPath(GetAbsoluteTestTmpdir(), \"link\");\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ const std::string link_path = JoinPath(dir.path().c_str(), \"link\");\nASSERT_THAT(symlink(test_file_name_.c_str(), link_path.c_str()),\nSyscallSucceeds());\nauto cleanup = Cleanup([link_path]() {\n@@ -227,8 +225,7 @@ TEST_F(OpenTest, OpenNoFollowStillFollowsLinksInPath) {\n//\n// We will then open tmp_folder/sym_folder/file with O_NOFOLLOW and it\n// should succeed as O_NOFOLLOW only applies to the final path component.\n- auto tmp_path =\n- ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(GetAbsoluteTestTmpdir()));\n+ auto tmp_path = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nauto sym_path = ASSERT_NO_ERRNO_AND_VALUE(\nTempPath::CreateSymlinkTo(GetAbsoluteTestTmpdir(), tmp_path.path()));\nauto file_path =\n@@ -246,8 +243,7 @@ TEST_F(OpenTest, OpenNoFollowStillFollowsLinksInPath) {\n//\n// open(\"root/child/symlink/root/child/file\")\nTEST_F(OpenTest, SymlinkRecurse) {\n- auto root =\n- ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(GetAbsoluteTestTmpdir()));\n+ auto root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nauto child = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDirIn(root.path()));\nauto symlink = ASSERT_NO_ERRNO_AND_VALUE(\nTempPath::CreateSymlinkTo(child.path(), \"../..\"));\n@@ -481,12 +477,8 @@ TEST_F(OpenTest, CanTruncateWithStrangePermissions) {\nASSERT_NO_ERRNO(SetCapability(CAP_DAC_READ_SEARCH, false));\nconst DisableSave ds; // Permissions are dropped.\nstd::string path = NewTempAbsPath();\n- int fd;\n// Create a file without user permissions.\n- EXPECT_THAT( // SAVE_BELOW\n- fd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 055),\n- SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n+ EXPECT_NO_ERRNO(Open(path, O_CREAT | O_TRUNC | O_WRONLY, 055));\n// Cannot open file because we are owner and have no permissions set.\nEXPECT_THAT(open(path.c_str(), O_RDONLY), SyscallFailsWithErrno(EACCES));\n@@ -495,8 +487,7 @@ TEST_F(OpenTest, CanTruncateWithStrangePermissions) {\nEXPECT_THAT(chmod(path.c_str(), 0755), SyscallSucceeds());\n// Now we can open the file again.\n- EXPECT_THAT(fd = open(path.c_str(), O_RDWR), SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n+ EXPECT_NO_ERRNO(Open(path, O_RDWR));\n}\nTEST_F(OpenTest, OpenNonDirectoryWithTrailingSlash) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/open_create.cc", "new_path": "test/syscalls/linux/open_create.cc", "diff": "#include \"test/util/capability_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n+#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/temp_umask.h\"\n#include \"test/util/test_util.h\"\n@@ -31,85 +32,60 @@ namespace testing {\nnamespace {\nTEST(CreateTest, TmpFile) {\n- int fd;\n- EXPECT_THAT(fd = open(JoinPath(GetAbsoluteTestTmpdir(), \"a\").c_str(),\n- O_RDWR | O_CREAT, 0666),\n- SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ EXPECT_NO_ERRNO(Open(JoinPath(dir.path(), \"a\"), O_RDWR | O_CREAT, 0666));\n}\nTEST(CreateTest, ExistingFile) {\n- int fd;\n- EXPECT_THAT(\n- fd = open(JoinPath(GetAbsoluteTestTmpdir(), \"ExistingFile\").c_str(),\n- O_RDWR | O_CREAT, 0666),\n- SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n-\n- EXPECT_THAT(\n- fd = open(JoinPath(GetAbsoluteTestTmpdir(), \"ExistingFile\").c_str(),\n- O_RDWR | O_CREAT, 0666),\n- SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto path = JoinPath(dir.path(), \"ExistingFile\");\n+ EXPECT_NO_ERRNO(Open(path, O_RDWR | O_CREAT, 0666));\n+ EXPECT_NO_ERRNO(Open(path, O_RDWR | O_CREAT, 0666));\n}\nTEST(CreateTest, CreateAtFile) {\n- int dirfd;\n- EXPECT_THAT(dirfd = open(GetAbsoluteTestTmpdir().c_str(), O_DIRECTORY, 0666),\n- SyscallSucceeds());\n- EXPECT_THAT(openat(dirfd, \"CreateAtFile\", O_RDWR | O_CREAT, 0666),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto dirfd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_DIRECTORY, 0666));\n+ EXPECT_THAT(openat(dirfd.get(), \"CreateAtFile\", O_RDWR | O_CREAT, 0666),\nSyscallSucceeds());\n- EXPECT_THAT(close(dirfd), SyscallSucceeds());\n}\nTEST(CreateTest, HonorsUmask_NoRandomSave) {\nconst DisableSave ds; // file cannot be re-opened as writable.\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nTempUmask mask(0222);\n- int fd;\n- ASSERT_THAT(\n- fd = open(JoinPath(GetAbsoluteTestTmpdir(), \"UmaskedFile\").c_str(),\n- O_RDWR | O_CREAT, 0666),\n- SyscallSucceeds());\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(JoinPath(dir.path(), \"UmaskedFile\"), O_RDWR | O_CREAT, 0666));\nstruct stat statbuf;\n- ASSERT_THAT(fstat(fd, &statbuf), SyscallSucceeds());\n+ ASSERT_THAT(fstat(fd.get(), &statbuf), SyscallSucceeds());\nEXPECT_EQ(0444, statbuf.st_mode & 0777);\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n}\nTEST(CreateTest, CreateExclusively) {\n- std::string filename = NewTempAbsPath();\n-\n- int fd;\n- ASSERT_THAT(fd = open(filename.c_str(), O_CREAT | O_RDWR, 0644),\n- SyscallSucceeds());\n- EXPECT_THAT(close(fd), SyscallSucceeds());\n-\n- EXPECT_THAT(open(filename.c_str(), O_CREAT | O_EXCL | O_RDWR, 0644),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto path = JoinPath(dir.path(), \"foo\");\n+ EXPECT_NO_ERRNO(Open(path, O_CREAT | O_RDWR, 0644));\n+ EXPECT_THAT(open(path.c_str(), O_CREAT | O_EXCL | O_RDWR, 0644),\nSyscallFailsWithErrno(EEXIST));\n}\nTEST(CreateTest, CreatWithOTrunc) {\n- std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n- ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n- ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC, 0666),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(open(dir.path().c_str(), O_CREAT | O_TRUNC, 0666),\nSyscallFailsWithErrno(EISDIR));\n}\nTEST(CreateTest, CreatDirWithOTruncAndReadOnly) {\n- std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncd\");\n- ASSERT_THAT(mkdir(dirpath.c_str(), 0777), SyscallSucceeds());\n- ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC | O_RDONLY, 0666),\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ ASSERT_THAT(open(dir.path().c_str(), O_CREAT | O_TRUNC | O_RDONLY, 0666),\nSyscallFailsWithErrno(EISDIR));\n}\nTEST(CreateTest, CreatFileWithOTruncAndReadOnly) {\n- std::string dirpath = JoinPath(GetAbsoluteTestTmpdir(), \"truncfile\");\n- int dirfd;\n- ASSERT_THAT(dirfd = open(dirpath.c_str(), O_RDWR | O_CREAT, 0666),\n- SyscallSucceeds());\n- ASSERT_THAT(open(dirpath.c_str(), O_CREAT | O_TRUNC | O_RDONLY, 0666),\n- SyscallSucceeds());\n- ASSERT_THAT(close(dirfd), SyscallSucceeds());\n+ auto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ auto path = JoinPath(dir.path(), \"foo\");\n+ ASSERT_NO_ERRNO(Open(path, O_RDWR | O_CREAT, 0666));\n+ ASSERT_NO_ERRNO(Open(path, O_CREAT | O_TRUNC | O_RDONLY, 0666));\n}\nTEST(CreateTest, CreateFailsOnDirWithoutWritePerms) {\n" } ]
Go
Apache License 2.0
google/gvisor
Remove side effect from open tests Individual test cases must not rely on being executed in a clean environment. PiperOrigin-RevId: 354730126
260,004
31.01.2021 13:46:02
28,800
c5e3c1c7bd5b7d1dc389fd93ac0cd56cdb4d9ac9
Use closure for IPv6 testContext cleanup
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -492,8 +492,6 @@ func visitStats(v reflect.Value, f func(string, *tcpip.StatCounter)) {\n}\ntype testContext struct {\n- t *testing.T\n-\ns0 *stack.Stack\ns1 *stack.Stack\n@@ -511,8 +509,6 @@ func (e endpointWithResolutionCapability) Capabilities() stack.LinkEndpointCapab\nfunc newTestContext(t *testing.T) *testContext {\nc := &testContext{\n- t: t,\n-\ns0: stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},\nTransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},\n@@ -566,21 +562,19 @@ func newTestContext(t *testing.T) *testContext {\n}},\n)\n- t.Cleanup(c.cleanup)\n-\n- return c\n-}\n-\n-func (c *testContext) cleanup() {\n+ t.Cleanup(func() {\nif err := c.s0.RemoveNIC(nicID); err != nil {\n- c.t.Errorf(\"c.s0.RemoveNIC(%d): %s\", nicID, err)\n+ t.Errorf(\"c.s0.RemoveNIC(%d): %s\", nicID, err)\n}\nif err := c.s1.RemoveNIC(nicID); err != nil {\n- c.t.Errorf(\"c.s1.RemoveNIC(%d): %s\", nicID, err)\n+ t.Errorf(\"c.s1.RemoveNIC(%d): %s\", nicID, err)\n}\nc.linkEP0.Close()\nc.linkEP1.Close()\n+ })\n+\n+ return c\n}\ntype routeArgs struct {\n" } ]
Go
Apache License 2.0
google/gvisor
Use closure for IPv6 testContext cleanup PiperOrigin-RevId: 354827491
259,907
01.02.2021 11:51:36
28,800
cbcebfea80bd59091e142cc6dad4192915194550
[infra] Fix gazelle target.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -152,7 +152,7 @@ nogo: ## Surfaces all nogo findings.\n.PHONY: nogo\ngazelle: ## Runs gazelle to update WORKSPACE.\n- @$(call run,//:gazelle update-repos -from_file=go.mod -prune)\n+ @$(call run,//:gazelle,update-repos -from_file=go.mod -prune)\n.PHONY: gazelle\n##\n" } ]
Go
Apache License 2.0
google/gvisor
[infra] Fix gazelle target. PiperOrigin-RevId: 354991724
259,858
18.09.2020 20:26:11
0
196c9de99e65a7c794814f26d2f397a27443b255
Add basic VSCode plumbing.
[ { "change_type": "ADD", "old_path": null, "new_path": ".devcontainer.json", "diff": "+{\n+ \"dockerFile\": \"images/default/Dockerfile\",\n+ \"mounts\": [\"source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind\"],\n+ \"overrideCommand\": true,\n+ \"extensions\": [\n+ \"bazelbuild.vscode-bazel\"\n+ ]\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": ".vscode/tasks.json", "diff": "+{\n+ \"version\": \"2.0.0\",\n+ \"tasks\": [\n+ {\n+ \"label\": \"Build\",\n+ \"type\": \"shell\",\n+ \"command\": \"bazel build //...\",\n+ \"group\": {\n+ \"kind\": \"build\",\n+ \"isDefault\": true\n+ },\n+ \"presentation\": {\n+ \"reveal\": \"always\",\n+ \"panel\": \"new\"\n+ }\n+ },\n+ {\n+ \"label\": \"Test\",\n+ \"type\": \"shell\",\n+ \"command\": \"bazel test //...\",\n+ \"group\": {\n+ \"kind\": \"test\",\n+ \"isDefault\": true\n+ },\n+ \"presentation\": {\n+ \"reveal\": \"always\",\n+ \"panel\": \"new\"\n+ }\n+ }\n+ ]\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add basic VSCode plumbing.
259,858
01.02.2021 12:16:48
28,800
4fcf8b2282c2841920cd1c2b10c023e4b7c578e6
Update .devcontainer.json Provide appropriate capabilities and adjust Docker socket.
[ { "change_type": "MODIFY", "old_path": ".devcontainer.json", "new_path": ".devcontainer.json", "diff": "{\n\"dockerFile\": \"images/default/Dockerfile\",\n- \"mounts\": [\"source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind\"],\n\"overrideCommand\": true,\n+ \"mounts\": [\"source=/var/run/docker.sock,target=/var/run/docker-host.sock,type=bind\"],\n+ \"runArgs\": [\"--cap-add=SYS_PTRACE\", \"--security-opt\", \"seccomp=unconfined\"],\n\"extensions\": [\n\"bazelbuild.vscode-bazel\"\n]\n" } ]
Go
Apache License 2.0
google/gvisor
Update .devcontainer.json Provide appropriate capabilities and adjust Docker socket.
259,907
01.02.2021 12:28:31
28,800
0da3c72c9d24c322af8203511142462fab3b1bd9
[infra] Consolidate all ubuntu tests into one image. This makes it easier to add more tests that run on Ubuntu. We can now just add a bash script and call that from integration_test without having to set up another image.
[ { "change_type": "DELETE", "old_path": "images/basic/hostoverlaytest/Dockerfile", "new_path": null, "diff": "-FROM ubuntu:bionic\n-\n-WORKDIR /root\n-COPY . .\n-\n-RUN apt-get update && apt-get install -y gcc\n-RUN gcc -O2 -o test_copy_up test_copy_up.c\n-RUN gcc -O2 -o test_rewinddir test_rewinddir.c\n" }, { "change_type": "ADD", "old_path": null, "new_path": "images/basic/integrationtest/Dockerfile", "diff": "+FROM ubuntu:bionic\n+\n+WORKDIR /root\n+COPY . .\n+RUN chmod +x *.sh\n+\n+RUN apt-get update && apt-get install -y gcc iputils-ping iproute2\n" }, { "change_type": "RENAME", "old_path": "images/basic/hostoverlaytest/copy_up_testfile.txt", "new_path": "images/basic/integrationtest/copy_up_testfile.txt", "diff": "" }, { "change_type": "RENAME", "old_path": "images/basic/linktest/link_test.c", "new_path": "images/basic/integrationtest/link_test.c", "diff": "" }, { "change_type": "RENAME", "old_path": "images/basic/ping4test/ping4.sh", "new_path": "images/basic/integrationtest/ping4.sh", "diff": "" }, { "change_type": "RENAME", "old_path": "images/basic/ping6test/ping6.sh", "new_path": "images/basic/integrationtest/ping6.sh", "diff": "" }, { "change_type": "RENAME", "old_path": "images/basic/hostoverlaytest/test_copy_up.c", "new_path": "images/basic/integrationtest/test_copy_up.c", "diff": "" }, { "change_type": "RENAME", "old_path": "images/basic/hostoverlaytest/test_rewinddir.c", "new_path": "images/basic/integrationtest/test_rewinddir.c", "diff": "" }, { "change_type": "DELETE", "old_path": "images/basic/linktest/Dockerfile", "new_path": null, "diff": "-FROM ubuntu:bionic\n-\n-WORKDIR /root\n-COPY . .\n-\n-RUN apt-get update && apt-get install -y gcc\n-RUN gcc -O2 -o link_test link_test.c\n" }, { "change_type": "DELETE", "old_path": "images/basic/ping4test/Dockerfile", "new_path": null, "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": "DELETE", "old_path": "images/basic/ping6test/Dockerfile", "new_path": null, "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": "MODIFY", "old_path": "test/e2e/integration_test.go", "new_path": "test/e2e/integration_test.go", "diff": "@@ -434,18 +434,7 @@ func TestTmpMount(t *testing.T) {\n// runsc to hide the incoherence of FDs opened before and after overlayfs\n// copy-up on the host.\nfunc TestHostOverlayfsCopyUp(t *testing.T) {\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/hostoverlaytest\",\n- WorkDir: \"/root\",\n- }, \"./test_copy_up\"); err != nil {\n- t.Fatalf(\"docker run failed: %v\", err)\n- } else if got != \"\" {\n- t.Errorf(\"test failed:\\n%s\", got)\n- }\n+ runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o test_copy_up test_copy_up.c && ./test_copy_up\")\n}\n// TestHostOverlayfsRewindDir tests that rewinddir() \"causes the directory\n@@ -460,36 +449,14 @@ func TestHostOverlayfsCopyUp(t *testing.T) {\n// automated tests yield newly-added files from readdir() even if the fsgofer\n// does not explicitly rewinddir(), but overlayfs does not.\nfunc TestHostOverlayfsRewindDir(t *testing.T) {\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/hostoverlaytest\",\n- WorkDir: \"/root\",\n- }, \"./test_rewinddir\"); err != nil {\n- t.Fatalf(\"docker run failed: %v\", err)\n- } else if got != \"\" {\n- t.Errorf(\"test failed:\\n%s\", got)\n- }\n+ runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o test_rewinddir test_rewinddir.c && ./test_rewinddir\")\n}\n// Basic test for linkat(2). Syscall tests requires CAP_DAC_READ_SEARCH and it\n// cannot use tricks like userns as root. For this reason, run a basic link test\n// to ensure some coverage.\nfunc TestLink(t *testing.T) {\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/linktest\",\n- WorkDir: \"/root\",\n- }, \"./link_test\"); err != nil {\n- t.Fatalf(\"docker run failed: %v\", err)\n- } else if got != \"\" {\n- t.Errorf(\"test failed:\\n%s\", got)\n- }\n+ runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o link_test link_test.c && ./link_test\")\n}\n// This test ensures we can run ping without errors.\n@@ -500,17 +467,7 @@ func TestPing4Loopback(t *testing.T) {\nt.Skip(\"hostnet only supports TCP/UDP sockets, so ping is not supported.\")\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+ runIntegrationTest(t, nil, \"./ping4.sh\")\n}\n// This test ensures we can enable ipv6 on loopback and run ping6 without\n@@ -522,20 +479,25 @@ func TestPing6Loopback(t *testing.T) {\nt.Skip(\"hostnet only supports TCP/UDP sockets, so ping6 is not supported.\")\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+ runIntegrationTest(t, []string{\"NET_ADMIN\"}, \"./ping6.sh\")\n+}\n+\n+func runIntegrationTest(t *testing.T, capAdd []string, args ...string) {\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/integrationtest\",\n+ WorkDir: \"/root\",\n+ CapAdd: capAdd,\n+ }, args...); err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n} else if got != \"\" {\nt.Errorf(\"test failed:\\n%s\", got)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[infra] Consolidate all ubuntu tests into one image. This makes it easier to add more tests that run on Ubuntu. We can now just add a bash script and call that from integration_test without having to set up another image. PiperOrigin-RevId: 355000410
259,858
01.02.2021 16:59:01
28,800
5d8054e75a9ce2a4ee3feeb0a6d284967ff3ba46
Remove Go cache on failure. It's unclear why permissions wind up corrupted, but these can be cleared on any failure, similar to the bazel cache itself:
[ { "change_type": "MODIFY", "old_path": ".buildkite/hooks/post-command", "new_path": ".buildkite/hooks/post-command", "diff": "@@ -51,6 +51,9 @@ if test \"${BUILDKITE_COMMAND_EXIT_STATUS}\" -ne \"0\"; then\n# Attempt to clear the cache and shut down.\nmake clean || echo \"make clean failed with code $?\"\nmake bazel-shutdown || echo \"make bazel-shutdown failed with code $?\"\n+ # Attempt to clear any Go cache.\n+ sudo rm -rf \"${HOME}/.cache/go-build\"\n+ sudo rm -rf \"${HOME}/go\"\nfi\n# Kill any running containers (clear state).\n" }, { "change_type": "MODIFY", "old_path": "tools/go_branch.sh", "new_path": "tools/go_branch.sh", "diff": "set -xeou pipefail\n+# Remember our current directory.\n+declare orig_dir\n+orig_dir=$(pwd)\n+readonly orig_dir\n+\n+# Record the current working commit.\n+declare head\n+head=$(git describe --always)\n+readonly head\n+\n# Create a temporary working directory, and ensure that this directory and all\n# subdirectories are cleaned up upon exit.\ndeclare tmp_dir\ntmp_dir=$(mktemp -d)\nreadonly tmp_dir\nfinish() {\n- cd / # Leave tmp_dir.\n- rm -rf \"${tmp_dir}\"\n+ cd \"${orig_dir}\" # Leave tmp_dir.\n+ rm -rf \"${tmp_dir}\" # Remove all contents.\n+ git checkout -f \"${head}\" # Restore commit.\n}\ntrap finish EXIT\n@@ -70,11 +81,6 @@ declare -r go_merged=\"${tmp_dir}/merged\"\nrsync --recursive \"${go_amd64}/\" \"${go_merged}\"\nrsync --recursive \"${go_arm64}/\" \"${go_merged}\"\n-# Record the current working commit.\n-declare head\n-head=$(git describe --always)\n-readonly head\n-\n# We expect to have an existing go branch that we will use as the basis for this\n# commit. That branch may be empty, but it must exist. We search for this branch\n# using the local branch, the \"origin\" branch, and other remotes, in order.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove Go cache on failure. It's unclear why permissions wind up corrupted, but these can be cleared on any failure, similar to the bazel cache itself: https://buildkite.com/gvisor/pipeline/builds/2304#_ PiperOrigin-RevId: 355057421
259,896
01.02.2021 17:58:24
28,800
d3855ad6bddb4680b4dc5de40da1820fc8608f88
Add RACK reorder tests.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_rack_test.go", "new_path": "test/packetimpact/tests/tcp_rack_test.go", "diff": "@@ -70,8 +70,11 @@ func closeSACKConnection(t *testing.T, dut testbench.DUT, conn testbench.TCPIPv4\nfunc getRTTAndRTO(t *testing.T, dut testbench.DUT, acceptFd int32) (rtt, rto time.Duration) {\ninfo := linux.TCPInfo{}\n- ret := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n- binary.Unmarshal(ret, usermem.ByteOrder, &info)\n+ infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n+ t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n+ }\n+ binary.Unmarshal(infoBytes, usermem.ByteOrder, &info)\nreturn time.Duration(info.RTT) * time.Microsecond, time.Duration(info.RTO) * time.Microsecond\n}\n@@ -219,3 +222,200 @@ func TestRACKTLPWithSACK(t *testing.T) {\n}\ncloseSACKConnection(t, dut, conn, acceptFd, listenFd)\n}\n+\n+// TestRACKWithoutReorder tests that without reordering RACK will retransmit the\n+// lost packets after reorder timer expires.\n+func TestRACKWithoutReorder(t *testing.T) {\n+ dut, conn, acceptFd, listenFd := createSACKConnection(t)\n+ seqNum1 := *conn.RemoteSeqNum(t)\n+\n+ // Send ACK for data packets to establish RTT.\n+ sendAndReceive(t, dut, conn, numPktsForRTT, acceptFd, true /* sendACK */)\n+ seqNum1.UpdateForward(seqnum.Size(numPktsForRTT * payloadSize))\n+\n+ // We are not sending ACK for these packets.\n+ const numPkts = 4\n+ sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+\n+ // SACK for [3,4] packets.\n+ sackBlock := make([]byte, 40)\n+ start := seqNum1.Add(seqnum.Size(2 * payloadSize))\n+ end := start.Add(seqnum.Size(2 * payloadSize))\n+ sbOff := 0\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, sackBlock[sbOff:])\n+ time.Sleep(simulatedRTT)\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n+\n+ // RACK marks #1 and #2 packets as lost and retransmits both after\n+ // RTT + reorderWindow. The reorderWindow initially will be a small\n+ // fraction of RTT.\n+ rtt, _ := getRTTAndRTO(t, dut, acceptFd)\n+ timeout := 2 * rtt\n+ for i, sn := 0, seqNum1; i < 2; i++ {\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(sn))}, timeout); err != nil {\n+ t.Fatalf(\"expected payload was not received: %s\", err)\n+ }\n+ sn.UpdateForward(seqnum.Size(payloadSize))\n+ }\n+ closeSACKConnection(t, dut, conn, acceptFd, listenFd)\n+}\n+\n+// TestRACKWithReorder tests that RACK will retransmit segments when there is\n+// reordering in the connection and reorder timer expires.\n+func TestRACKWithReorder(t *testing.T) {\n+ dut, conn, acceptFd, listenFd := createSACKConnection(t)\n+ seqNum1 := *conn.RemoteSeqNum(t)\n+\n+ // Send ACK for data packets to establish RTT.\n+ sendAndReceive(t, dut, conn, numPktsForRTT, acceptFd, true /* sendACK */)\n+ seqNum1.UpdateForward(seqnum.Size(numPktsForRTT * payloadSize))\n+\n+ // We are not sending ACK for these packets.\n+ const numPkts = 4\n+ sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+\n+ time.Sleep(simulatedRTT)\n+ // SACK in reverse order for the connection to detect reorder.\n+ var start seqnum.Value\n+ var end seqnum.Value\n+ for i := 0; i < numPkts-1; i++ {\n+ sackBlock := make([]byte, 40)\n+ sbOff := 0\n+ start = seqNum1.Add(seqnum.Size((numPkts - i - 1) * payloadSize))\n+ end = start.Add(seqnum.Size((i + 1) * payloadSize))\n+ sackBlock = make([]byte, 40)\n+ sbOff = 0\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, sackBlock[sbOff:])\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n+ }\n+\n+ // Send a DSACK block indicating both original and retransmitted\n+ // packets are received, RACK will increase the reordering window on\n+ // every DSACK.\n+ dsackBlock := make([]byte, 40)\n+ dbOff := 0\n+ start = seqNum1\n+ end = start.Add(seqnum.Size(2 * payloadSize))\n+ dbOff += header.EncodeNOP(dsackBlock[dbOff:])\n+ dbOff += header.EncodeNOP(dsackBlock[dbOff:])\n+ dbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, dsackBlock[dbOff:])\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1 + numPkts*payloadSize)), Options: dsackBlock[:dbOff]})\n+\n+ seqNum1.UpdateForward(seqnum.Size(numPkts * payloadSize))\n+ sendTime := time.Now()\n+ sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+\n+ time.Sleep(simulatedRTT)\n+ // Send SACK for [2-5] packets.\n+ sackBlock := make([]byte, 40)\n+ sbOff := 0\n+ start = seqNum1.Add(seqnum.Size(payloadSize))\n+ end = start.Add(seqnum.Size(3 * payloadSize))\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, sackBlock[sbOff:])\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n+\n+ // Expect the retransmission of #1 packet after RTT+ReorderWindow.\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, time.Second); err != nil {\n+ t.Fatalf(\"expected payload was not received: %s\", err)\n+ }\n+ rtt, _ := getRTTAndRTO(t, dut, acceptFd)\n+ diff := time.Now().Sub(sendTime)\n+ if diff < rtt {\n+ t.Fatalf(\"expected payload was received too sonn, within RTT\")\n+ }\n+\n+ closeSACKConnection(t, dut, conn, acceptFd, listenFd)\n+}\n+\n+// TestRACKWithLostRetransmission tests that RACK will not enter RTO when a\n+// retransmitted segment is lost and enters fast recovery.\n+func TestRACKWithLostRetransmission(t *testing.T) {\n+ dut, conn, acceptFd, listenFd := createSACKConnection(t)\n+ seqNum1 := *conn.RemoteSeqNum(t)\n+\n+ // Send ACK for data packets to establish RTT.\n+ sendAndReceive(t, dut, conn, numPktsForRTT, acceptFd, true /* sendACK */)\n+ seqNum1.UpdateForward(seqnum.Size(numPktsForRTT * payloadSize))\n+\n+ // We are not sending ACK for these packets.\n+ const numPkts = 5\n+ sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+\n+ // SACK for [2-5] packets.\n+ sackBlock := make([]byte, 40)\n+ start := seqNum1.Add(seqnum.Size(payloadSize))\n+ end := start.Add(seqnum.Size(4 * payloadSize))\n+ sbOff := 0\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeNOP(sackBlock[sbOff:])\n+ sbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, sackBlock[sbOff:])\n+ time.Sleep(simulatedRTT)\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n+\n+ // RACK marks #1 packet as lost and retransmits it after\n+ // RTT + reorderWindow. The reorderWindow is bounded between a small\n+ // fraction of RTT and 1 RTT.\n+ rtt, _ := getRTTAndRTO(t, dut, acceptFd)\n+ timeout := 2 * rtt\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, timeout); err != nil {\n+ t.Fatalf(\"expected payload was not received: %s\", err)\n+ }\n+\n+ // Send #6 packet.\n+ payload := make([]byte, payloadSize)\n+ dut.Send(t, acceptFd, payload, 0)\n+ gotOne, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1 + 5*payloadSize))}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"Expect #6: %s\", err)\n+ }\n+ if gotOne == nil {\n+ t.Fatalf(\"#6: expected a packet within a second but got none\")\n+ }\n+\n+ // SACK for [2-6] packets.\n+ sackBlock1 := make([]byte, 40)\n+ start = seqNum1.Add(seqnum.Size(payloadSize))\n+ end = start.Add(seqnum.Size(5 * payloadSize))\n+ sbOff1 := 0\n+ sbOff1 += header.EncodeNOP(sackBlock1[sbOff1:])\n+ sbOff1 += header.EncodeNOP(sackBlock1[sbOff1:])\n+ sbOff1 += header.EncodeSACKBlocks([]header.SACKBlock{{\n+ start, end,\n+ }}, sackBlock1[sbOff1:])\n+ time.Sleep(simulatedRTT)\n+ conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock1[:sbOff1]})\n+\n+ // Expect re-retransmission of #1 packet without entering an RTO.\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, timeout); err != nil {\n+ t.Fatalf(\"expected payload was not received: %s\", err)\n+ }\n+\n+ // Check the congestion control state.\n+ info := linux.TCPInfo{}\n+ infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n+ t.Fatalf(\"expected %T, got %d bytes want %d bytes\", info, got, want)\n+ }\n+ binary.Unmarshal(infoBytes, usermem.ByteOrder, &info)\n+ if info.CaState != linux.TCP_CA_Recovery {\n+ t.Fatalf(\"expected connection to be in fast recovery, want: %v got: %v\", linux.TCP_CA_Recovery, info.CaState)\n+ }\n+\n+ closeSACKConnection(t, dut, conn, acceptFd, listenFd)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add RACK reorder tests. PiperOrigin-RevId: 355067082
259,992
01.02.2021 19:26:12
28,800
aae4803808dc7358492db3fa787e8dd8f4a0e97a
Enable container checkpoint/restore tests with VFS2 Updates
[ { "change_type": "MODIFY", "old_path": "runsc/container/console_test.go", "new_path": "runsc/container/console_test.go", "diff": "@@ -122,7 +122,7 @@ func receiveConsolePTY(srv *unet.ServerSocket) (*os.File, error) {\n// Test that an pty FD is sent over the console socket if one is provided.\nfunc TestConsoleSocket(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"true\")\nspec.Process.Terminal = true\n@@ -164,7 +164,7 @@ func TestConsoleSocket(t *testing.T) {\n// Test that an pty FD is sent over the console socket if one is provided.\nfunc TestMultiContainerConsoleSocket(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -495,7 +495,7 @@ func TestJobControlSignalRootContainer(t *testing.T) {\n// Test that terminal works with root and sub-containers.\nfunc TestMultiContainerTerminal(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -312,8 +312,7 @@ var (\nall = append(noOverlay, overlay)\n)\n-// configs generates different configurations to run tests.\n-func configs(t *testing.T, opts ...configOption) map[string]*config.Config {\n+func configsHelper(t *testing.T, opts ...configOption) map[string]*config.Config {\n// Always load the default config.\ncs := make(map[string]*config.Config)\ntestutil.TestConfig(t)\n@@ -339,10 +338,12 @@ func configs(t *testing.T, opts ...configOption) map[string]*config.Config {\nreturn cs\n}\n-// TODO(gvisor.dev/issue/1624): Merge with configs when VFS2 is the default.\n-func configsWithVFS2(t *testing.T, opts ...configOption) map[string]*config.Config {\n- all := configs(t, opts...)\n- for key, value := range configs(t, opts...) {\n+// configs generates different configurations to run tests.\n+//\n+// TODO(gvisor.dev/issue/1624): Remove VFS1 dimension.\n+func configs(t *testing.T, opts ...configOption) map[string]*config.Config {\n+ all := configsHelper(t, opts...)\n+ for key, value := range configsHelper(t, opts...) {\nvalue.VFS2 = true\nall[key+\"VFS2\"] = value\n}\n@@ -358,7 +359,7 @@ func TestLifecycle(t *testing.T) {\nchildReaper.Start()\ndefer childReaper.Stop()\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\n// The container will just sleep for a long time. We will kill it before\n// it finishes sleeping.\n@@ -529,7 +530,7 @@ func TestExePath(t *testing.T) {\nt.Fatalf(\"error making directory: %v\", err)\n}\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nfor _, test := range []struct {\npath string\n@@ -654,7 +655,7 @@ func doAppExitStatus(t *testing.T, vfs2 bool) {\n// TestExec verifies that a container can exec a new program.\nfunc TestExec(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"exec-test\")\nif err != nil {\n@@ -783,7 +784,7 @@ func TestExec(t *testing.T) {\n// TestExecProcList verifies that a container can exec a new program and it\n// shows correcly in the process list.\nfunc TestExecProcList(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nconst uid = 343\nspec := testutil.NewSpecWithArgs(\"sleep\", \"100\")\n@@ -854,7 +855,7 @@ func TestExecProcList(t *testing.T) {\n// TestKillPid verifies that we can signal individual exec'd processes.\nfunc TestKillPid(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\napp, err := testutil.FindFile(\"test/cmd/test_app/test_app\")\nif err != nil {\n@@ -930,7 +931,6 @@ func TestKillPid(t *testing.T) {\n// number after the last number from the checkpointed container.\nfunc TestCheckpointRestore(t *testing.T) {\n// Skip overlay because test requires writing to host file.\n- // TODO(gvisor.dev/issue/1663): Add VFS when S/R support is added.\nfor name, conf := range configs(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"checkpoint-test\")\n@@ -1092,7 +1092,6 @@ func TestCheckpointRestore(t *testing.T) {\n// with filesystem Unix Domain Socket use.\nfunc TestUnixDomainSockets(t *testing.T) {\n// Skip overlay because test requires writing to host file.\n- // TODO(gvisor.dev/issue/1663): Add VFS when S/R support is added.\nfor name, conf := range configs(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\n// UDS path is limited to 108 chars for compatibility with older systems.\n@@ -1230,7 +1229,7 @@ func TestUnixDomainSockets(t *testing.T) {\n// recreated. Then it resumes the container, verify that the file gets created\n// again.\nfunc TestPauseResume(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, noOverlay...) {\n+ for name, conf := range configs(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\ntmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"lock\")\nif err != nil {\n@@ -1373,7 +1372,7 @@ func TestCapabilities(t *testing.T) {\nuid := auth.KUID(os.Getuid() + 1)\ngid := auth.KGID(os.Getgid() + 1)\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"sleep\", \"100\")\nrootDir, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n@@ -1446,7 +1445,7 @@ func TestCapabilities(t *testing.T) {\n// TestRunNonRoot checks that sandbox can be configured when running as\n// non-privileged user.\nfunc TestRunNonRoot(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, noOverlay...) {\n+ for name, conf := range configs(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/true\")\n@@ -1490,7 +1489,7 @@ func TestRunNonRoot(t *testing.T) {\n// TestMountNewDir checks that runsc will create destination directory if it\n// doesn't exit.\nfunc TestMountNewDir(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nroot, err := ioutil.TempDir(testutil.TmpDir(), \"root\")\nif err != nil {\n@@ -1521,7 +1520,7 @@ func TestMountNewDir(t *testing.T) {\n}\nfunc TestReadonlyRoot(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"sleep\", \"100\")\nspec.Root.Readonly = true\n@@ -1569,7 +1568,7 @@ func TestReadonlyRoot(t *testing.T) {\n}\nfunc TestReadonlyMount(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"ro-mount\")\nif err != nil {\n@@ -1628,7 +1627,7 @@ func TestReadonlyMount(t *testing.T) {\n}\nfunc TestUIDMap(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, noOverlay...) {\n+ for name, conf := range configs(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\ntestDir, err := ioutil.TempDir(testutil.TmpDir(), \"test-mount\")\nif err != nil {\n@@ -1916,7 +1915,7 @@ func TestUserLog(t *testing.T) {\n}\nfunc TestWaitOnExitedSandbox(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\n// Run a shell that sleeps for 1 second and then exits with a\n// non-zero code.\n@@ -2058,7 +2057,7 @@ func doDestroyStartingTest(t *testing.T, vfs2 bool) {\n}\nfunc TestCreateWorkingDir(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\ntmpDir, err := ioutil.TempDir(testutil.TmpDir(), \"cwd-create\")\nif err != nil {\n@@ -2173,7 +2172,7 @@ func TestMountPropagation(t *testing.T) {\n}\nfunc TestMountSymlink(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"mount-symlink\")\nif err != nil {\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/multi_container_test.go", "new_path": "runsc/container/multi_container_test.go", "diff": "@@ -132,7 +132,7 @@ func createSharedMount(mount specs.Mount, name string, pod ...*specs.Spec) {\n// TestMultiContainerSanity checks that it is possible to run 2 dead-simple\n// containers in the same sandbox.\nfunc TestMultiContainerSanity(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -170,7 +170,7 @@ func TestMultiContainerSanity(t *testing.T) {\n// TestMultiPIDNS checks that it is possible to run 2 dead-simple\n// containers in the same sandbox with different pidns.\nfunc TestMultiPIDNS(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -215,7 +215,7 @@ func TestMultiPIDNS(t *testing.T) {\n// TestMultiPIDNSPath checks the pidns path.\nfunc TestMultiPIDNSPath(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -448,7 +448,7 @@ func TestMultiContainerMount(t *testing.T) {\n// TestMultiContainerSignal checks that it is possible to signal individual\n// containers without killing the entire sandbox.\nfunc TestMultiContainerSignal(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -548,7 +548,7 @@ func TestMultiContainerDestroy(t *testing.T) {\nt.Fatal(\"error finding test_app:\", err)\n}\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1042,7 +1042,7 @@ func TestMultiContainerContainerDestroyStress(t *testing.T) {\n// Test that pod shared mounts are properly mounted in 2 containers and that\n// changes from one container is reflected in the other.\nfunc TestMultiContainerSharedMount(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1155,7 +1155,7 @@ func TestMultiContainerSharedMount(t *testing.T) {\n// Test that pod mounts are mounted as readonly when requested.\nfunc TestMultiContainerSharedMountReadonly(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1220,7 +1220,7 @@ func TestMultiContainerSharedMountReadonly(t *testing.T) {\n// Test that shared pod mounts continue to work after container is restarted.\nfunc TestMultiContainerSharedMountRestart(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1329,7 +1329,7 @@ func TestMultiContainerSharedMountRestart(t *testing.T) {\n// Test that unsupported pod mounts options are ignored when matching master and\n// replica mounts.\nfunc TestMultiContainerSharedMountUnsupportedOptions(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all...) {\n+ for name, conf := range configs(t, all...) {\nt.Run(name, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1663,7 +1663,7 @@ func TestMultiContainerRunNonRoot(t *testing.T) {\nfunc TestMultiContainerHomeEnvDir(t *testing.T) {\n// NOTE: Don't use overlay since we need changes to persist to the temp dir\n// outside the sandbox.\n- for testName, conf := range configsWithVFS2(t, noOverlay...) {\n+ for testName, conf := range configs(t, noOverlay...) {\nt.Run(testName, func(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\n" } ]
Go
Apache License 2.0
google/gvisor
Enable container checkpoint/restore tests with VFS2 Updates #1663 PiperOrigin-RevId: 355077816
259,858
01.02.2021 23:01:50
28,800
0c8cc66117f2f966870f78e9db78f264b1948a86
Fix empty Packages file for APT repository. This change also adds an extra sanity check to the make_apt.sh script, in order to ensure that this simple mistake does not occur again.
[ { "change_type": "MODIFY", "old_path": "tools/make_apt.sh", "new_path": "tools/make_apt.sh", "diff": "@@ -119,7 +119,11 @@ for dir in \"${root}\"/pool/*/binary-*; do\narches+=(\"${arch}\")\nrepo_packages=\"${release}\"/main/\"${name}\"\nmkdir -p \"${repo_packages}\"\n- (cd \"${root}\" && apt-ftparchive --arch \"${arch}\" packages pool > \"${repo_packages}\"/Packages)\n+ (cd \"${root}\" && apt-ftparchive packages \"${dir##${root}/}\" > \"${repo_packages}\"/Packages)\n+ if ! [[ -s \"${repo_packages}\"/Packages ]]; then\n+ echo \"Packages file is size zero.\" >&2\n+ exit 1\n+ fi\n(cd \"${repo_packages}\" && cat Packages | gzip > Packages.gz)\n(cd \"${repo_packages}\" && cat Packages | xz > Packages.xz)\ndone\n" } ]
Go
Apache License 2.0
google/gvisor
Fix empty Packages file for APT repository. This change also adds an extra sanity check to the make_apt.sh script, in order to ensure that this simple mistake does not occur again. PiperOrigin-RevId: 355101754
259,858
02.02.2021 09:34:29
28,800
3817c7349de2dde950fd65dcab1f4859c095eeaf
Remove go_tool_library references. This is required only for the built-in bazel nogo functionality. Since we roll these targets manually via the wrappers, we don't need to use go_tool_library. The inconsistent use of these targets leads to conflicting instantiations of go_default_library and go_tool_library, which both contain the same output files.
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -8,7 +8,7 @@ load(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"git_repository\")\nhttp_file(\nname = \"google_root_pem\",\nurls = [\n- \"https://pki.goog/roots.pem\"\n+ \"https://pki.goog/roots.pem\",\n],\n)\n@@ -36,9 +36,11 @@ http_archive(\nname = \"io_bazel_rules_go\",\npatch_args = [\"-p1\"],\npatches = [\n+ # Ensure we don't destroy the facts visibility.\n+ \"//tools:rules_go_visibility.patch\",\n# Newer versions of the rules_go rules will automatically strip test\n# binaries of symbols, which we don't want.\n- \"//tools:rules_go.patch\",\n+ \"//tools:rules_go_symbols.patch\",\n],\nsha256 = \"8e9434015ff8f3d6962cb8f016230ea7acc1ac402b760a8d66ff54dc11673ca6\",\nurls = [\n@@ -51,9 +53,13 @@ http_archive(\nname = \"bazel_gazelle\",\npatch_args = [\"-p1\"],\npatches = [\n+ # Fix permissions for facts for go_library, not just tool library.\n+ # This is actually a no-op with the hacky patch above, but should\n+ # slightly future proof this mechanism.\n+ \"//tools:bazel_gazelle_generate.patch\",\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+ \"//tools:bazel_gazelle_noise.patch\",\n],\nsha256 = \"b85f48fa105c4403326e9525ad2b2cc437babaa6e15a3fc0b1dbab0ab064bc7c\",\nurls = [\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/bazel_gazelle_generate.patch", "diff": "+diff --git a/language/go/generate.go b/language/go/generate.go\n+index 2892948..feb4ad6 100644\n+--- a/language/go/generate.go\n++++ b/language/go/generate.go\n+@@ -691,6 +691,10 @@ func (g *generator) setImportAttrs(r *rule.Rule, importPath string) {\n+ }\n+\n+ func (g *generator) commonVisibility(importPath string) []string {\n++ if importPath == \"golang.org/x/tools/go/analysis/internal/facts\" {\n++ // Imported by nogo main. We add a visibility exception.\n++ return []string{\"//visibility:public\"}\n++ }\n+ // If the Bazel package name (rel) contains \"internal\", add visibility for\n+ // subpackages of the parent.\n+ // If the import path contains \"internal\" but rel does not, this is\n" }, { "change_type": "RENAME", "old_path": "tools/bazel_gazelle.patch", "new_path": "tools/bazel_gazelle_noise.patch", "diff": "" }, { "change_type": "MODIFY", "old_path": "tools/checkescape/BUILD", "new_path": "tools/checkescape/BUILD", "diff": "@@ -8,8 +8,8 @@ go_library(\nnogo = False,\nvisibility = [\"//tools/nogo:__subpackages__\"],\ndeps = [\n- \"@org_golang_x_tools//go/analysis:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/buildssa:go_tool_library\",\n- \"@org_golang_x_tools//go/ssa:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/buildssa:go_default_library\",\n+ \"@org_golang_x_tools//go/ssa:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/checkunsafe/BUILD", "new_path": "tools/checkunsafe/BUILD", "diff": "@@ -8,6 +8,6 @@ go_library(\nnogo = False,\nvisibility = [\"//tools/nogo:__subpackages__\"],\ndeps = [\n- \"@org_golang_x_tools//go/analysis:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/nogo/BUILD", "new_path": "tools/nogo/BUILD", "diff": "@@ -38,34 +38,34 @@ go_library(\n\"//tools/checkunsafe\",\n\"@co_honnef_go_tools//staticcheck:go_default_library\",\n\"@co_honnef_go_tools//stylecheck:go_default_library\",\n- \"@org_golang_x_tools//go/analysis:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/internal/facts:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/asmdecl:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/assign:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/atomic:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/bools:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/buildtag:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/cgocall:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/composite:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/copylock:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/errorsas:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/httpresponse:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/loopclosure:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/lostcancel:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/nilfunc:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/nilness:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/printf:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/shadow:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/shift:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/stdmethods:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/stringintconv:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/structtag:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/tests:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/unmarshal:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/unreachable:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/unsafeptr:go_tool_library\",\n- \"@org_golang_x_tools//go/analysis/passes/unusedresult:go_tool_library\",\n- \"@org_golang_x_tools//go/gcexportdata:go_tool_library\",\n+ \"@org_golang_x_tools//go/analysis:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/internal/facts:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/asmdecl:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/assign:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/atomic:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/bools:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/buildtag:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/cgocall:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/composite:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/copylock:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/errorsas:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/httpresponse:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/loopclosure:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/lostcancel:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/nilfunc:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/nilness:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/printf:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/shadow:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/shift:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/stdmethods:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/stringintconv:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/structtag:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/tests:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unmarshal:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unreachable:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unsafeptr:go_default_library\",\n+ \"@org_golang_x_tools//go/analysis/passes/unusedresult:go_default_library\",\n+ \"@org_golang_x_tools//go/gcexportdata:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/nogo/defs.bzl", "new_path": "tools/nogo/defs.bzl", "diff": "@@ -188,6 +188,14 @@ def _nogo_aspect_impl(target, ctx):\n# All work is done in the shadow properties for go rules. For a proto\n# library, we simply skip the analysis portion but still need to return a\n# valid NogoInfo to reference the generated binary.\n+ #\n+ # Note that we almost exclusively use go_library, not go_tool_library.\n+ # This is because nogo is manually annotated, so the go_tool_library kind\n+ # is not needed to avoid dependency loops. Unfortunately, bazel coverdata\n+ # is exported *only* as a go_tool_library. This does not cause a problem,\n+ # since there is guaranteed to be no conflict. However for consistency,\n+ # we should not introduce new go_tool_library dependencies unless strictly\n+ # necessary.\nif ctx.rule.kind in (\"go_library\", \"go_tool_library\", \"go_binary\", \"go_test\"):\nsrcs = ctx.rule.files.srcs\ndeps = ctx.rule.attr.deps\n" }, { "change_type": "RENAME", "old_path": "tools/rules_go.patch", "new_path": "tools/rules_go_symbols.patch", "diff": "" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/rules_go_visibility.patch", "diff": "+diff --git a/third_party/org_golang_x_tools-gazelle.patch b/third_party/org_golang_x_tools-gazelle.patch\n+index 7bdacff5..2fe9ce93 100644\n+--- a/third_party/org_golang_x_tools-gazelle.patch\n++++ b/third_party/org_golang_x_tools-gazelle.patch\n+@@ -2054,7 +2054,7 @@ diff -urN b/go/analysis/internal/facts/BUILD.bazel c/go/analysis/internal/facts/\n+ + \"imports.go\",\n+ + ],\n+ + importpath = \"golang.org/x/tools/go/analysis/internal/facts\",\n+-+ visibility = [\"//go/analysis:__subpackages__\"],\n+++ visibility = [\"//visibility:public\"],\n+ + deps = [\n+ + \"//go/analysis\",\n+ + \"//go/types/objectpath\",\n+@@ -2078,7 +2078,7 @@ diff -urN b/go/analysis/internal/facts/BUILD.bazel c/go/analysis/internal/facts/\n+ +alias(\n+ + name = \"go_default_library\",\n+ + actual = \":facts\",\n+-+ visibility = [\"//go/analysis:__subpackages__\"],\n+++ visibility = [\"//visibility:public\"],\n+ +)\n+ +\n+ +go_test(\n" } ]
Go
Apache License 2.0
google/gvisor
Remove go_tool_library references. This is required only for the built-in bazel nogo functionality. Since we roll these targets manually via the wrappers, we don't need to use go_tool_library. The inconsistent use of these targets leads to conflicting instantiations of go_default_library and go_tool_library, which both contain the same output files. PiperOrigin-RevId: 355184975
259,858
02.02.2021 11:26:37
28,800
017348af99b3aa129596a1345851b1b67cd9633e
Drop gazelle target from the Makefile. This is replaced with a straight call to bazel. Unfortunately, the built gazelle target requires a bazel installation to run anyways.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -151,10 +151,6 @@ nogo: ## Surfaces all nogo findings.\n@$(call run,//tools/github $(foreach dir,$(BUILD_ROOTS),-path=$(CURDIR)/$(dir)) -dry-run nogo)\n.PHONY: nogo\n-gazelle: ## Runs gazelle to update WORKSPACE.\n- @$(call run,//:gazelle,update-repos -from_file=go.mod -prune)\n-.PHONY: gazelle\n-\n##\n## Canonical build and test targets.\n##\n" } ]
Go
Apache License 2.0
google/gvisor
Drop gazelle target from the Makefile. This is replaced with a straight call to bazel. Unfortunately, the built gazelle target requires a bazel installation to run anyways. PiperOrigin-RevId: 355211990
259,992
02.02.2021 11:35:07
28,800
d6d169320cd40d0910955debc9b0c91877b53900
Add ETIMEDOUT to partial result list Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/error.go", "new_path": "pkg/sentry/syscalls/linux/error.go", "diff": "@@ -134,8 +134,8 @@ func handleIOErrorImpl(t *kernel.Task, partialResult bool, err, intr error, op s\n// Similar to EPIPE. Return what we wrote this time, and let\n// ENOSPC be returned on the next call.\nreturn true, nil\n- case syserror.ECONNRESET:\n- // For TCP sendfile connections, we may have a reset. But we\n+ case syserror.ECONNRESET, syserror.ETIMEDOUT:\n+ // For TCP sendfile connections, we may have a reset or timeout. But we\n// should just return n as the result.\nreturn true, nil\ncase syserror.ErrWouldBlock:\n" } ]
Go
Apache License 2.0
google/gvisor
Add ETIMEDOUT to partial result list Reported-by: [email protected] PiperOrigin-RevId: 355213994
259,891
02.02.2021 12:45:25
28,800
5f7bf3152652d36903f9659688321ae7c42995d0
Stub out basic `runsc events --stat` CPU functionality Because we lack gVisor-internal cgroups, we take the CPU usage of the entire pod and divide it proportionally according to sentry-internal usage stats. This fixes `kubectl top pods`, which gets a pod's CPU usage by summing the usage of its containers. Addresses
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/control/proc.go", "new_path": "pkg/sentry/control/proc.go", "diff": "@@ -404,3 +404,16 @@ func ttyName(tty *kernel.TTY) string {\n}\nreturn fmt.Sprintf(\"pts/%d\", tty.Index)\n}\n+\n+// ContainerUsage retrieves per-container CPU usage.\n+func ContainerUsage(kr *kernel.Kernel) map[string]uint64 {\n+ cusage := make(map[string]uint64)\n+ for _, tg := range kr.TaskSet().Root.ThreadGroups() {\n+ // We want each tg's usage including reaped children.\n+ cid := tg.Leader().ContainerID()\n+ stats := tg.CPUStats()\n+ stats.Accumulate(tg.JoinedChildCPUStats())\n+ cusage[cid] += uint64(stats.UserTime.Nanoseconds()) + uint64(stats.SysTime.Nanoseconds())\n+ }\n+ return cusage\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/events.go", "new_path": "runsc/boot/events.go", "diff": "package boot\nimport (\n- \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/control\"\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n)\n+// EventOut is the return type of the Event command.\n+type EventOut struct {\n+ Event Event `json:\"event\"`\n+\n+ // ContainerUsage maps each container ID to its total CPU usage.\n+ ContainerUsage map[string]uint64 `json:\"containerUsage\"`\n+}\n+\n// Event struct for encoding the event data to JSON. Corresponds to runc's\n// main.event struct.\ntype Event struct {\nType string `json:\"type\"`\nID string `json:\"id\"`\n- Data interface{} `json:\"data,omitempty\"`\n+ Data Stats `json:\"data\"`\n}\n// Stats is the runc specific stats structure for stability when encoding and\n// decoding stats.\ntype Stats struct {\n+ CPU CPU `json:\"cpu\"`\nMemory Memory `json:\"memory\"`\nPids Pids `json:\"pids\"`\n}\n@@ -58,24 +67,42 @@ type Memory struct {\nRaw map[string]uint64 `json:\"raw,omitempty\"`\n}\n+// CPU contains stats on the CPU.\n+type CPU struct {\n+ Usage CPUUsage `json:\"usage\"`\n+}\n+\n+// CPUUsage contains stats on CPU usage.\n+type CPUUsage struct {\n+ Kernel uint64 `json:\"kernel,omitempty\"`\n+ User uint64 `json:\"user,omitempty\"`\n+ Total uint64 `json:\"total,omitempty\"`\n+ PerCPU []uint64 `json:\"percpu,omitempty\"`\n+}\n+\n// Event gets the events from the container.\n-func (cm *containerManager) Event(_ *struct{}, out *Event) error {\n- stats := &Stats{}\n- stats.populateMemory(cm.l.k)\n- stats.populatePIDs(cm.l.k)\n- *out = Event{Type: \"stats\", Data: stats}\n- return nil\n+func (cm *containerManager) Event(_ *struct{}, out *EventOut) error {\n+ *out = EventOut{\n+ Event: Event{\n+ Type: \"stats\",\n+ },\n}\n-func (s *Stats) populateMemory(k *kernel.Kernel) {\n- mem := k.MemoryFile()\n+ // Memory usage.\n+ // TODO(gvisor.dev/issue/172): Per-container accounting.\n+ mem := cm.l.k.MemoryFile()\nmem.UpdateUsage()\n_, totalUsage := usage.MemoryAccounting.Copy()\n- s.Memory.Usage = MemoryEntry{\n+ out.Event.Data.Memory.Usage = MemoryEntry{\nUsage: totalUsage,\n}\n-}\n-func (s *Stats) populatePIDs(k *kernel.Kernel) {\n- s.Pids.Current = uint64(len(k.TaskSet().Root.ThreadGroups()))\n+ // PIDs.\n+ // TODO(gvisor.dev/issue/172): Per-container accounting.\n+ out.Event.Data.Pids.Current = uint64(len(cm.l.k.TaskSet().Root.ThreadGroups()))\n+\n+ // CPU usage by container.\n+ out.ContainerUsage = control.ContainerUsage(cm.l.k)\n+\n+ return nil\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -102,7 +102,7 @@ type containerInfo struct {\ngoferFDs []*fd.FD\n}\n-// Loader keeps state needed to start the kernel and run the container..\n+// Loader keeps state needed to start the kernel and run the container.\ntype Loader struct {\n// k is the kernel.\nk *kernel.Kernel\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -281,8 +281,13 @@ func New(spec *specs.Spec) (*Cgroup, error) {\nif spec.Linux == nil || spec.Linux.CgroupsPath == \"\" {\nreturn nil, nil\n}\n+ return NewFromPath(spec.Linux.CgroupsPath)\n+}\n+\n+// NewFromPath creates a new Cgroup instance.\n+func NewFromPath(cgroupsPath string) (*Cgroup, error) {\nvar parents map[string]string\n- if !filepath.IsAbs(spec.Linux.CgroupsPath) {\n+ if !filepath.IsAbs(cgroupsPath) {\nvar err error\nparents, err = LoadPaths(\"self\")\nif err != nil {\n@@ -291,7 +296,7 @@ func New(spec *specs.Spec) (*Cgroup, error) {\n}\nown := make(map[string]bool)\nreturn &Cgroup{\n- Name: spec.Linux.CgroupsPath,\n+ Name: cgroupsPath,\nParents: parents,\nOwn: own,\n}, nil\n@@ -389,6 +394,9 @@ func (c *Cgroup) Join() (func(), error) {\nundo = func() {\nfor _, path := range undoPaths {\nlog.Debugf(\"Restoring cgroup %q\", path)\n+ // Writing the value 0 to a cgroup.procs file causes\n+ // the writing process to be moved to the corresponding\n+ // cgroup. - cgroups(7).\nif err := setValue(path, \"cgroup.procs\", \"0\"); err != nil {\nlog.Warningf(\"Error restoring cgroup %q: %v\", path, err)\n}\n@@ -399,6 +407,9 @@ func (c *Cgroup) Join() (func(), error) {\nfor key, cfg := range controllers {\npath := c.makePath(key)\nlog.Debugf(\"Joining cgroup %q\", path)\n+ // Writing the value 0 to a cgroup.procs file causes the\n+ // writing process to be moved to the corresponding cgroup.\n+ // - cgroups(7).\nif err := setValue(path, \"cgroup.procs\", \"0\"); err != nil {\nif cfg.optional && os.IsNotExist(err) {\ncontinue\n@@ -426,6 +437,16 @@ func (c *Cgroup) CPUQuota() (float64, error) {\nreturn float64(quota) / float64(period), nil\n}\n+// CPUUsage returns the total CPU usage of the cgroup.\n+func (c *Cgroup) CPUUsage() (uint64, error) {\n+ path := c.makePath(\"cpuacct\")\n+ usage, err := getValue(path, \"cpuacct.usage\")\n+ if err != nil {\n+ return 0, err\n+ }\n+ return strconv.ParseUint(strings.TrimSpace(usage), 10, 64)\n+}\n+\n// NumCPU returns the number of CPUs configured in 'cpuset/cpuset.cpus'.\nfunc (c *Cgroup) NumCPU() (int, error) {\npath := c.makePath(\"cpuset\")\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/events.go", "new_path": "runsc/cmd/events.go", "diff": "@@ -93,9 +93,9 @@ func (evs *Events) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\n// err must be preserved because it is used below when breaking\n// out of the loop.\n- b, err := json.Marshal(ev)\n+ b, err := json.Marshal(ev.Event)\nif err != nil {\n- log.Warningf(\"Error while marshalling event %v: %v\", ev, err)\n+ log.Warningf(\"Error while marshalling event %v: %v\", ev.Event, err)\n} else {\nos.Stdout.Write(b)\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -486,12 +486,20 @@ func (c *Container) Execute(args *control.ExecArgs) (int32, error) {\n}\n// Event returns events for the container.\n-func (c *Container) Event() (*boot.Event, error) {\n+func (c *Container) Event() (*boot.EventOut, error) {\nlog.Debugf(\"Getting events for container, cid: %s\", c.ID)\nif err := c.requireStatus(\"get events for\", Created, Running, Paused); err != nil {\nreturn nil, err\n}\n- return c.Sandbox.Event(c.ID)\n+ event, err := c.Sandbox.Event(c.ID)\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ // Some stats can utilize host cgroups for accuracy.\n+ c.populateStats(event)\n+\n+ return event, nil\n}\n// SandboxPid returns the Pid of the sandbox the container is running in, or -1 if the\n@@ -1110,3 +1118,54 @@ func setOOMScoreAdj(pid int, scoreAdj int) error {\n}\nreturn nil\n}\n+\n+// populateStats populates event with stats estimates based on cgroups and the\n+// sentry's accounting.\n+// TODO(gvisor.dev/issue/172): This is an estimation; we should do more\n+// detailed accounting.\n+func (c *Container) populateStats(event *boot.EventOut) {\n+ // The events command, when run for all running containers, should\n+ // account for the full cgroup CPU usage. We split cgroup usage\n+ // proportionally according to the sentry-internal usage measurements,\n+ // only counting Running containers.\n+ log.Warningf(\"event.ContainerUsage: %v\", event.ContainerUsage)\n+ var containerUsage uint64\n+ var allContainersUsage uint64\n+ for ID, usage := range event.ContainerUsage {\n+ allContainersUsage += usage\n+ if ID == c.ID {\n+ containerUsage = usage\n+ }\n+ }\n+\n+ cgroup, err := c.Sandbox.FindCgroup()\n+ if err != nil {\n+ // No cgroup, so rely purely on the sentry's accounting.\n+ log.Warningf(\"events: no cgroups\")\n+ event.Event.Data.CPU.Usage.Total = containerUsage\n+ return\n+ }\n+\n+ // Get the host cgroup CPU usage.\n+ cgroupsUsage, err := cgroup.CPUUsage()\n+ if err != nil {\n+ // No cgroup usage, so rely purely on the sentry's accounting.\n+ log.Warningf(\"events: failed when getting cgroup CPU usage for container: %v\", err)\n+ event.Event.Data.CPU.Usage.Total = containerUsage\n+ return\n+ }\n+\n+ // If the sentry reports no memory usage, fall back on cgroups and\n+ // split usage equally across containers.\n+ if allContainersUsage == 0 {\n+ log.Warningf(\"events: no sentry CPU usage reported\")\n+ allContainersUsage = cgroupsUsage\n+ containerUsage = cgroupsUsage / uint64(len(event.ContainerUsage))\n+ }\n+\n+ log.Warningf(\"%f, %f, %f\", containerUsage, cgroupsUsage, allContainersUsage)\n+ // Scaling can easily overflow a uint64 (e.g. a containerUsage and\n+ // cgroupsUsage of 16 seconds each will overflow), so use floats.\n+ event.Event.Data.CPU.Usage.Total = uint64(float64(containerUsage) * (float64(cgroupsUsage) / float64(allContainersUsage)))\n+ return\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/multi_container_test.go", "new_path": "runsc/container/multi_container_test.go", "diff": "package container\nimport (\n- \"encoding/json\"\n\"fmt\"\n\"io/ioutil\"\n\"math\"\n@@ -322,8 +321,8 @@ func TestMultiContainerWait(t *testing.T) {\n}\n}\n-// TestExecWait ensures what we can wait containers and individual processes in the\n-// sandbox that have already exited.\n+// TestExecWait ensures what we can wait on containers and individual processes\n+// in the sandbox that have already exited.\nfunc TestExecWait(t *testing.T) {\nrootDir, cleanup, err := testutil.SetupRootDir()\nif err != nil {\n@@ -1743,8 +1742,9 @@ func TestMultiContainerEvent(t *testing.T) {\n// Setup the containers.\nsleep := []string{\"/bin/sleep\", \"100\"}\n+ busy := []string{\"/bin/bash\", \"-c\", \"i=0 ; while true ; do (( i += 1 )) ; done\"}\nquick := []string{\"/bin/true\"}\n- podSpec, ids := createSpecs(sleep, sleep, quick)\n+ podSpec, ids := createSpecs(sleep, busy, quick)\ncontainers, cleanup, err := startContainers(conf, podSpec, ids)\nif err != nil {\nt.Fatalf(\"error starting containers: %v\", err)\n@@ -1755,37 +1755,58 @@ func TestMultiContainerEvent(t *testing.T) {\nt.Logf(\"Running containerd %s\", cont.ID)\n}\n- // Wait for last container to stabilize the process count that is checked\n- // further below.\n+ // Wait for last container to stabilize the process count that is\n+ // checked further below.\nif ws, err := containers[2].Wait(); err != nil || ws != 0 {\nt.Fatalf(\"Container.Wait, status: %v, err: %v\", ws, err)\n}\n+ expectedPL := []*control.Process{\n+ newProcessBuilder().Cmd(\"sleep\").Process(),\n+ }\n+ if err := waitForProcessList(containers[0], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for sleep to start: %v\", err)\n+ }\n+ expectedPL = []*control.Process{\n+ newProcessBuilder().Cmd(\"bash\").Process(),\n+ }\n+ if err := waitForProcessList(containers[1], expectedPL); err != nil {\n+ t.Errorf(\"failed to wait for bash to start: %v\", err)\n+ }\n// Check events for running containers.\n+ var prevUsage uint64\nfor _, cont := range containers[:2] {\n- evt, err := cont.Event()\n+ ret, err := cont.Event()\nif err != nil {\nt.Errorf(\"Container.Events(): %v\", err)\n}\n+ evt := ret.Event\nif want := \"stats\"; evt.Type != want {\nt.Errorf(\"Wrong event type, want: %s, got: %s\", want, evt.Type)\n}\nif cont.ID != evt.ID {\nt.Errorf(\"Wrong container ID, want: %s, got: %s\", cont.ID, evt.ID)\n}\n- // Event.Data is an interface, so it comes from the wire was\n- // map[string]string. Marshal and unmarshall again to the correc type.\n- data, err := json.Marshal(evt.Data)\n- if err != nil {\n- t.Fatalf(\"invalid event data: %v\", err)\n+ // One process per remaining container.\n+ if got, want := evt.Data.Pids.Current, uint64(2); got != want {\n+ t.Errorf(\"Wrong number of PIDs, want: %d, got: %d\", want, got)\n}\n- var stats boot.Stats\n- if err := json.Unmarshal(data, &stats); err != nil {\n- t.Fatalf(\"invalid event data: %v\", err)\n+\n+ // Both remaining containers should have nonzero usage, and\n+ // 'busy' should have higher usage than 'sleep'.\n+ usage := evt.Data.CPU.Usage.Total\n+ if usage == 0 {\n+ t.Errorf(\"Running container should report nonzero CPU usage, but got %d\", usage)\n}\n- // One process per remaining container.\n- if want := uint64(2); stats.Pids.Current != want {\n- t.Errorf(\"Wrong number of PIDs, want: %d, got :%d\", want, stats.Pids.Current)\n+ if usage <= prevUsage {\n+ t.Errorf(\"Expected container %s to use more than %d ns of CPU, but used %d\", cont.ID, prevUsage, usage)\n+ }\n+ t.Logf(\"Container %s usage: %d\", cont.ID, usage)\n+ prevUsage = usage\n+\n+ // The exited container should have a usage of zero.\n+ if exited := ret.ContainerUsage[containers[2].ID]; exited != 0 {\n+ t.Errorf(\"Exited container should report 0 CPU usage, but got %d\", exited)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/state_file.go", "new_path": "runsc/container/state_file.go", "diff": "@@ -49,7 +49,7 @@ type LoadOpts struct {\n// Returns ErrNotExist if no container is found. Returns error in case more than\n// one containers matching the ID prefix is found.\nfunc Load(rootDir string, id FullID, opts LoadOpts) (*Container, error) {\n- //log.Debugf(\"Load container, rootDir: %q, partial cid: %s\", rootDir, partialID)\n+ log.Debugf(\"Load container, rootDir: %q, id: %+v, opts: %+v\", rootDir, id, opts)\nif !opts.Exact {\nvar err error\nid, err = findContainerID(rootDir, id.ContainerID)\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/sandbox.go", "new_path": "runsc/sandbox/sandbox.go", "diff": "@@ -308,6 +308,22 @@ func (s *Sandbox) Processes(cid string) ([]*control.Process, error) {\nreturn pl, nil\n}\n+// FindCgroup returns the sandbox's Cgroup, or an error if it does not have one.\n+func (s *Sandbox) FindCgroup() (*cgroup.Cgroup, error) {\n+ paths, err := cgroup.LoadPaths(strconv.Itoa(s.Pid))\n+ if err != nil {\n+ return nil, err\n+ }\n+ // runsc places sandboxes in the same cgroup for each controller, so we\n+ // pick an arbitrary controller here to get the cgroup path.\n+ const controller = \"cpuacct\"\n+ controllerPath, ok := paths[controller]\n+ if !ok {\n+ return nil, fmt.Errorf(\"no %q controller found\", controller)\n+ }\n+ return cgroup.NewFromPath(controllerPath)\n+}\n+\n// Execute runs the specified command in the container. It returns the PID of\n// the newly created process.\nfunc (s *Sandbox) Execute(args *control.ExecArgs) (int32, error) {\n@@ -327,7 +343,7 @@ func (s *Sandbox) Execute(args *control.ExecArgs) (int32, error) {\n}\n// Event retrieves stats about the sandbox such as memory and CPU utilization.\n-func (s *Sandbox) Event(cid string) (*boot.Event, error) {\n+func (s *Sandbox) Event(cid string) (*boot.EventOut, error) {\nlog.Debugf(\"Getting events for container %q in sandbox %q\", cid, s.ID)\nconn, err := s.sandboxConnect()\nif err != nil {\n@@ -335,13 +351,13 @@ func (s *Sandbox) Event(cid string) (*boot.Event, error) {\n}\ndefer conn.Close()\n- var e boot.Event\n+ var e boot.EventOut\n// TODO(b/129292330): Pass in the container id (cid) here. The sandbox\n// should return events only for that container.\nif err := conn.Call(boot.ContainerEvent, nil, &e); err != nil {\nreturn nil, fmt.Errorf(\"retrieving event data from sandbox: %v\", err)\n}\n- e.ID = cid\n+ e.Event.ID = cid\nreturn &e, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Stub out basic `runsc events --stat` CPU functionality Because we lack gVisor-internal cgroups, we take the CPU usage of the entire pod and divide it proportionally according to sentry-internal usage stats. This fixes `kubectl top pods`, which gets a pod's CPU usage by summing the usage of its containers. Addresses #172. PiperOrigin-RevId: 355229833
259,896
02.02.2021 13:19:51
28,800
49f783fb659327966ce23ff4b4a7f977cb270723
Rename HandleNDupAcks in TCP. Rename HandleNDupAcks() to HandleLossDetected() as it will enter this when is detected after: reorder window expires and TLP (in case of RACK) dupAckCount >= 3
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/cubic.go", "new_path": "pkg/tcpip/transport/tcp/cubic.go", "diff": "@@ -178,8 +178,8 @@ func (c *cubicState) getCwnd(packetsAcked, sndCwnd int, srtt time.Duration) int\nreturn int(cwnd)\n}\n-// HandleNDupAcks implements congestionControl.HandleNDupAcks.\n-func (c *cubicState) HandleNDupAcks() {\n+// HandleLossDetected implements congestionControl.HandleLossDetected.\n+func (c *cubicState) HandleLossDetected() {\n// See: https://tools.ietf.org/html/rfc8312#section-4.5\nc.numCongestionEvents++\nc.t = time.Now()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack.go", "new_path": "pkg/tcpip/transport/tcp/rack.go", "diff": "@@ -301,7 +301,7 @@ func (s *sender) detectTLPRecovery(ack seqnum.Value, rcvdSeg *segment) {\n// Step 2. Either the original packet or the retransmission (in the\n// form of a probe) was lost. Invoke a congestion control response\n// equivalent to fast recovery.\n- s.cc.HandleNDupAcks()\n+ s.cc.HandleLossDetected()\ns.enterRecovery()\ns.leaveRecovery()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/reno.go", "new_path": "pkg/tcpip/transport/tcp/reno.go", "diff": "@@ -79,10 +79,10 @@ func (r *renoState) Update(packetsAcked int) {\nr.updateCongestionAvoidance(packetsAcked)\n}\n-// HandleNDupAcks implements congestionControl.HandleNDupAcks.\n-func (r *renoState) HandleNDupAcks() {\n- // A retransmit was triggered due to nDupAckThreshold\n- // being hit. Reduce our slow start threshold.\n+// HandleLossDetected implements congestionControl.HandleLossDetected.\n+func (r *renoState) HandleLossDetected() {\n+ // A retransmit was triggered due to nDupAckThreshold or when RACK\n+ // detected loss. Reduce our slow start threshold.\nr.reduceSlowStartThreshold()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -51,9 +51,10 @@ const (\n// congestionControl is an interface that must be implemented by any supported\n// congestion control algorithm.\ntype congestionControl interface {\n- // HandleNDupAcks is invoked when sender.dupAckCount >= nDupAckThreshold\n- // just before entering fast retransmit.\n- HandleNDupAcks()\n+ // HandleLossDetected is invoked when the loss is detected by RACK or\n+ // sender.dupAckCount >= nDupAckThreshold just before entering fast\n+ // retransmit.\n+ HandleLossDetected()\n// HandleRTOExpired is invoked when the retransmit timer expires.\nHandleRTOExpired()\n@@ -1152,7 +1153,7 @@ func (s *sender) detectLoss(seg *segment) (fastRetransmit bool) {\ns.dupAckCount = 0\nreturn false\n}\n- s.cc.HandleNDupAcks()\n+ s.cc.HandleLossDetected()\ns.enterRecovery()\ns.dupAckCount = 0\nreturn true\n" } ]
Go
Apache License 2.0
google/gvisor
Rename HandleNDupAcks in TCP. Rename HandleNDupAcks() to HandleLossDetected() as it will enter this when is detected after: - reorder window expires and TLP (in case of RACK) - dupAckCount >= 3 PiperOrigin-RevId: 355237858
259,975
02.02.2021 13:38:24
28,800
fcc2468db573fec37c91236f805f7fa0e46e4492
Add CPUSet for runsc mitigate.
[ { "change_type": "MODIFY", "old_path": "runsc/mitigate/cpu.go", "new_path": "runsc/mitigate/cpu.go", "diff": "@@ -16,6 +16,7 @@ package mitigate\nimport (\n\"fmt\"\n+ \"io/ioutil\"\n\"regexp\"\n\"strconv\"\n\"strings\"\n@@ -35,12 +36,100 @@ const (\nvendorIDKey = \"vendor_id\"\ncpuFamilyKey = \"cpu family\"\nmodelKey = \"model\"\n+ physicalIDKey = \"physical id\"\ncoreIDKey = \"core id\"\nbugsKey = \"bugs\"\n)\n-// getCPUSet returns cpu structs from reading /proc/cpuinfo.\n-func getCPUSet(data string) ([]*cpu, error) {\n+const (\n+ cpuOnlineTemplate = \"/sys/devices/system/cpu/cpu%d/online\"\n+)\n+\n+// cpuSet contains a map of all CPUs on the system, mapped\n+// by Physical ID and CoreIDs. threads with the same\n+// Core and Physical ID are Hyperthread pairs.\n+type cpuSet map[cpuID]*threadGroup\n+\n+// newCPUSet creates a CPUSet from data read from /proc/cpuinfo.\n+func newCPUSet(data []byte, vulnerable func(*thread) bool) (cpuSet, error) {\n+ processors, err := getThreads(string(data))\n+ if err != nil {\n+ return nil, err\n+ }\n+\n+ set := make(cpuSet)\n+ for _, p := range processors {\n+ // Each ID is of the form physicalID:coreID. Hyperthread pairs\n+ // have identical physical and core IDs. We need to match\n+ // Hyperthread pairs so that we can shutdown all but one per\n+ // pair.\n+ core, ok := set[p.id]\n+ if !ok {\n+ core = &threadGroup{}\n+ set[p.id] = core\n+ }\n+ core.isVulnerable = core.isVulnerable || vulnerable(p)\n+ core.threads = append(core.threads, p)\n+ }\n+ return set, nil\n+}\n+\n+// String implements the String method for CPUSet.\n+func (c cpuSet) String() string {\n+ ret := \"\"\n+ for _, tg := range c {\n+ ret += fmt.Sprintf(\"%s\\n\", tg)\n+ }\n+ return ret\n+}\n+\n+// getRemainingList returns the list of threads that will remain active\n+// after mitigation.\n+func (c cpuSet) getRemainingList() []*thread {\n+ threads := make([]*thread, 0, len(c))\n+ for _, core := range c {\n+ // If we're vulnerable, take only one thread from the pair.\n+ if core.isVulnerable {\n+ threads = append(threads, core.threads[0])\n+ continue\n+ }\n+ // Otherwise don't shutdown anything.\n+ threads = append(threads, core.threads...)\n+ }\n+ return threads\n+}\n+\n+// getShutdownList returns the list of threads that will be shutdown on\n+// mitigation.\n+func (c cpuSet) getShutdownList() []*thread {\n+ threads := make([]*thread, 0)\n+ for _, core := range c {\n+ // Only if we're vulnerable do shutdown anything. In this case,\n+ // shutdown all but the first entry.\n+ if core.isVulnerable && len(core.threads) > 1 {\n+ threads = append(threads, core.threads[1:]...)\n+ }\n+ }\n+ return threads\n+}\n+\n+// threadGroup represents Hyperthread pairs on the same physical/core ID.\n+type threadGroup struct {\n+ threads []*thread\n+ isVulnerable bool\n+}\n+\n+// String implements the String method for threadGroup.\n+func (c *threadGroup) String() string {\n+ ret := fmt.Sprintf(\"ThreadGroup:\\nIsVulnerable: %t\\n\", c.isVulnerable)\n+ for _, processor := range c.threads {\n+ ret += fmt.Sprintf(\"%s\\n\", processor)\n+ }\n+ return ret\n+}\n+\n+// getThreads returns threads structs from reading /proc/cpuinfo.\n+func getThreads(data string) ([]*thread, error) {\n// Each processor entry should start with the\n// processor key. Find the beginings of each.\nr := buildRegex(processorKey, `\\d+`)\n@@ -56,13 +145,13 @@ func getCPUSet(data string) ([]*cpu, error) {\n// indexes (e.g. data[index[i], index[i+1]]).\n// There should be len(indicies) - 1 CPUs\n// since the last index is the end of the string.\n- var cpus = make([]*cpu, 0, len(indices)-1)\n+ var cpus = make([]*thread, 0, len(indices)-1)\n// Find each string that represents a CPU. These begin \"processor\".\nfor i := 1; i < len(indices); i++ {\nstart := indices[i-1][0]\nend := indices[i][0]\n// Parse the CPU entry, which should be between start/end.\n- c, err := getCPU(data[start:end])\n+ c, err := newThread(data[start:end])\nif err != nil {\nreturn nil, err\n}\n@@ -71,18 +160,25 @@ func getCPUSet(data string) ([]*cpu, error) {\nreturn cpus, nil\n}\n+// cpuID for each thread is defined by the physical and\n+// core IDs. If equal, two threads are Hyperthread pairs.\n+type cpuID struct {\n+ physicalID int64\n+ coreID int64\n+}\n+\n// type cpu represents pertinent info about a cpu.\n-type cpu struct {\n+type thread struct {\nprocessorNumber int64 // the processor number of this CPU.\nvendorID string // the vendorID of CPU (e.g. AuthenticAMD).\ncpuFamily int64 // CPU family number (e.g. 6 for CascadeLake/Skylake).\nmodel int64 // CPU model number (e.g. 85 for CascadeLake/Skylake).\n- coreID int64 // This CPU's core id to match Hyperthread Pairs\n+ id cpuID // id for this thread\nbugs map[string]struct{} // map of vulnerabilities parsed from the 'bugs' field.\n}\n-// getCPU parses a CPU from a single cpu entry from /proc/cpuinfo.\n-func getCPU(data string) (*cpu, error) {\n+// newThread parses a CPU from a single cpu entry from /proc/cpuinfo.\n+func newThread(data string) (*thread, error) {\nprocessor, err := parseProcessor(data)\nif err != nil {\nreturn nil, err\n@@ -103,6 +199,11 @@ func getCPU(data string) (*cpu, error) {\nreturn nil, err\n}\n+ physicalID, err := parsePhysicalID(data)\n+ if err != nil {\n+ return nil, err\n+ }\n+\ncoreID, err := parseCoreID(data)\nif err != nil {\nreturn nil, err\n@@ -113,16 +214,41 @@ func getCPU(data string) (*cpu, error) {\nreturn nil, err\n}\n- return &cpu{\n+ return &thread{\nprocessorNumber: processor,\nvendorID: vendorID,\ncpuFamily: cpuFamily,\nmodel: model,\n+ id: cpuID{\n+ physicalID: physicalID,\ncoreID: coreID,\n+ },\nbugs: bugs,\n}, nil\n}\n+// String implements the String method for thread.\n+func (t *thread) String() string {\n+ template := `CPU: %d\n+CPU ID: %+v\n+Vendor: %s\n+Family/Model: %d/%d\n+Bugs: %s\n+`\n+ bugs := make([]string, 0)\n+ for bug := range t.bugs {\n+ bugs = append(bugs, bug)\n+ }\n+\n+ return fmt.Sprintf(template, t.processorNumber, t.id, t.vendorID, t.cpuFamily, t.model, strings.Join(bugs, \",\"))\n+}\n+\n+// shutdown turns off the CPU by writing 0 to /sys/devices/cpu/cpu{N}/online.\n+func (t *thread) shutdown() error {\n+ cpuPath := fmt.Sprintf(cpuOnlineTemplate, t.processorNumber)\n+ return ioutil.WriteFile(cpuPath, []byte{'0'}, 0644)\n+}\n+\n// List of pertinent side channel vulnerablilites.\n// For mds, see: https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/mds.html.\nvar vulnerabilities = []string{\n@@ -134,35 +260,46 @@ var vulnerabilities = []string{\n}\n// isVulnerable checks if a CPU is vulnerable to pertinent bugs.\n-func (c *cpu) isVulnerable() bool {\n+func (t *thread) isVulnerable() bool {\nfor _, bug := range vulnerabilities {\n- if _, ok := c.bugs[bug]; ok {\n+ if _, ok := t.bugs[bug]; ok {\nreturn true\n}\n}\nreturn false\n}\n+// isActive checks if a CPU is active from /sys/devices/system/cpu/cpu{N}/online\n+// If the file does not exist (ioutil returns in error), we assume the CPU is on.\n+func (t *thread) isActive() bool {\n+ cpuPath := fmt.Sprintf(cpuOnlineTemplate, t.processorNumber)\n+ data, err := ioutil.ReadFile(cpuPath)\n+ if err != nil {\n+ return true\n+ }\n+ return len(data) > 0 && data[0] != '0'\n+}\n+\n// similarTo checks family/model/bugs fields for equality of two\n// processors.\n-func (c *cpu) similarTo(other *cpu) bool {\n- if c.vendorID != other.vendorID {\n+func (t *thread) similarTo(other *thread) bool {\n+ if t.vendorID != other.vendorID {\nreturn false\n}\n- if other.cpuFamily != c.cpuFamily {\n+ if other.cpuFamily != t.cpuFamily {\nreturn false\n}\n- if other.model != c.model {\n+ if other.model != t.model {\nreturn false\n}\n- if len(other.bugs) != len(c.bugs) {\n+ if len(other.bugs) != len(t.bugs) {\nreturn false\n}\n- for bug := range c.bugs {\n+ for bug := range t.bugs {\nif _, ok := other.bugs[bug]; !ok {\nreturn false\n}\n@@ -190,6 +327,11 @@ func parseModel(data string) (int64, error) {\nreturn parseIntegerResult(data, modelKey)\n}\n+// parsePhysicalID parses the physical id field.\n+func parsePhysicalID(data string) (int64, error) {\n+ return parseIntegerResult(data, physicalIDKey)\n+}\n+\n// parseCoreID parses the core id field.\nfunc parseCoreID(data string) (int64, error) {\nreturn parseIntegerResult(data, coreIDKey)\n" }, { "change_type": "MODIFY", "old_path": "runsc/mitigate/cpu_test.go", "new_path": "runsc/mitigate/cpu_test.go", "diff": "package mitigate\nimport (\n+ \"fmt\"\n\"io/ioutil\"\n\"strings\"\n\"testing\"\n)\n-// CPU info for a Intel CascadeLake processor. Both Skylake and CascadeLake have\n-// the same family/model numbers, but with different bugs (e.g. skylake has\n-// cpu_meltdown).\n-var cascadeLake = &cpu{\n+// cpuTestCase represents data from CPUs that will be mitigated.\n+type cpuTestCase struct {\n+ name string\n+ vendorID string\n+ family int\n+ model int\n+ modelName string\n+ bugs string\n+ physicalCores int\n+ cores int\n+ threadsPerCore int\n+}\n+\n+var cascadeLake4 = cpuTestCase{\n+ name: \"CascadeLake\",\nvendorID: \"GenuineIntel\",\n- cpuFamily: 6,\n+ family: 6,\nmodel: 85,\n- bugs: map[string]struct{}{\n- \"spectre_v1\": struct{}{},\n- \"spectre_v2\": struct{}{},\n- \"spec_store_bypass\": struct{}{},\n- mds: struct{}{},\n- swapgs: struct{}{},\n- taa: struct{}{},\n+ modelName: \"Intel(R) Xeon(R) CPU\",\n+ bugs: \"spectre_v1 spectre_v2 spec_store_bypass mds swapgs taa\",\n+ physicalCores: 1,\n+ cores: 2,\n+ threadsPerCore: 2,\n+}\n+\n+var haswell2 = cpuTestCase{\n+ name: \"Haswell\",\n+ vendorID: \"GenuineIntel\",\n+ family: 6,\n+ model: 63,\n+ modelName: \"Intel(R) Xeon(R) CPU\",\n+ bugs: \"cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\",\n+ physicalCores: 1,\n+ cores: 1,\n+ threadsPerCore: 2,\n+}\n+\n+var haswell2core = cpuTestCase{\n+ name: \"Haswell2Physical\",\n+ vendorID: \"GenuineIntel\",\n+ family: 6,\n+ model: 63,\n+ modelName: \"Intel(R) Xeon(R) CPU\",\n+ bugs: \"cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs\",\n+ physicalCores: 2,\n+ cores: 1,\n+ threadsPerCore: 1,\n+}\n+\n+var amd8 = cpuTestCase{\n+ name: \"AMD\",\n+ vendorID: \"AuthenticAMD\",\n+ family: 23,\n+ model: 49,\n+ modelName: \"AMD EPYC 7B12\",\n+ bugs: \"sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass\",\n+ physicalCores: 4,\n+ cores: 1,\n+ threadsPerCore: 2,\n+}\n+\n+// makeCPUString makes a string formated like /proc/cpuinfo for each cpuTestCase\n+func (tc cpuTestCase) makeCPUString() string {\n+ template := `processor : %d\n+vendor_id : %s\n+cpu family : %d\n+model : %d\n+model name : %s\n+physical id : %d\n+core id : %d\n+cpu cores : %d\n+bugs : %s\n+`\n+ ret := ``\n+ for i := 0; i < tc.physicalCores; i++ {\n+ for j := 0; j < tc.cores; j++ {\n+ for k := 0; k < tc.threadsPerCore; k++ {\n+ processorNum := (i*tc.cores+j)*tc.threadsPerCore + k\n+ ret += fmt.Sprintf(template,\n+ processorNum, /*processor*/\n+ tc.vendorID, /*vendor_id*/\n+ tc.family, /*cpu family*/\n+ tc.model, /*model*/\n+ tc.modelName, /*model name*/\n+ i, /*physical id*/\n+ j, /*core id*/\n+ tc.cores*tc.physicalCores, /*cpu cores*/\n+ tc.bugs /*bugs*/)\n+ }\n+ }\n+ }\n+ return ret\n+}\n+\n+// TestMockCPUSet tests mock cpu test cases against the cpuSet functions.\n+func TestMockCPUSet(t *testing.T) {\n+ for _, tc := range []struct {\n+ testCase cpuTestCase\n+ isVulnerable bool\n+ }{\n+ {\n+ testCase: amd8,\n+ isVulnerable: false,\n},\n+ {\n+ testCase: haswell2,\n+ isVulnerable: true,\n+ },\n+ {\n+ testCase: haswell2core,\n+ isVulnerable: true,\n+ },\n+\n+ {\n+ testCase: cascadeLake4,\n+ isVulnerable: true,\n+ },\n+ } {\n+ t.Run(tc.testCase.name, func(t *testing.T) {\n+ data := tc.testCase.makeCPUString()\n+ vulnerable := func(t *thread) bool {\n+ return t.isVulnerable()\n+ }\n+ set, err := newCPUSet([]byte(data), vulnerable)\n+ if err != nil {\n+ t.Fatalf(\"Failed to \")\n+ }\n+ remaining := set.getRemainingList()\n+ // In the non-vulnerable case, no cores should be shutdown so all should remain.\n+ want := tc.testCase.physicalCores * tc.testCase.cores * tc.testCase.threadsPerCore\n+ if tc.isVulnerable {\n+ want = tc.testCase.physicalCores * tc.testCase.cores\n+ }\n+\n+ if want != len(remaining) {\n+ t.Fatalf(\"Failed to shutdown the correct number of cores: want: %d got: %d\", want, len(remaining))\n+ }\n+\n+ if !tc.isVulnerable {\n+ return\n+ }\n+\n+ // If the set is vulnerable, we expect only 1 thread per hyperthread pair.\n+ for _, r := range remaining {\n+ if _, ok := set[r.id]; !ok {\n+ t.Fatalf(\"Entry %+v not in map, there must be two entries in the same thread group.\", r)\n+ }\n+ delete(set, r.id)\n+ }\n+ })\n+ }\n}\n// TestGetCPU tests basic parsing of single CPU strings from reading\n@@ -44,15 +181,19 @@ func TestGetCPU(t *testing.T) {\nvendor_id : GenuineIntel\ncpu family : 6\nmodel : 85\n+physical id: 0\ncore id : 0\nbugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa itlb_multihit\n`\n- want := cpu{\n+ want := thread{\nprocessorNumber: 0,\nvendorID: \"GenuineIntel\",\ncpuFamily: 6,\nmodel: 85,\n+ id: cpuID{\n+ physicalID: 0,\ncoreID: 0,\n+ },\nbugs: map[string]struct{}{\n\"cpu_meltdown\": struct{}{},\n\"spectre_v1\": struct{}{},\n@@ -66,7 +207,7 @@ bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\n},\n}\n- got, err := getCPU(data)\n+ got, err := newThread(data)\nif err != nil {\nt.Fatalf(\"getCpu failed with error: %v\", err)\n}\n@@ -81,7 +222,7 @@ bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa\n}\nfunc TestInvalid(t *testing.T) {\n- result, err := getCPUSet(`something not a processor`)\n+ result, err := getThreads(`something not a processor`)\nif err == nil {\nt.Fatalf(\"getCPU set didn't return an error: %+v\", result)\n}\n@@ -148,7 +289,7 @@ cache_alignment : 64\naddress sizes : 46 bits physical, 48 bits virtual\npower management:\n`\n- cpuSet, err := getCPUSet(data)\n+ cpuSet, err := getThreads(data)\nif err != nil {\nt.Fatalf(\"getCPUSet failed: %v\", err)\n}\n@@ -158,7 +299,7 @@ power management:\nt.Fatalf(\"Num CPU mismatch: want: %d, got: %d\", wantCPULen, len(cpuSet))\n}\n- wantCPU := cpu{\n+ wantCPU := thread{\nvendorID: \"GenuineIntel\",\ncpuFamily: 6,\nmodel: 63,\n@@ -187,7 +328,11 @@ func TestReadFile(t *testing.T) {\nt.Fatalf(\"Failed to read cpuinfo: %v\", err)\n}\n- set, err := getCPUSet(string(data))\n+ vulnerable := func(t *thread) bool {\n+ return t.isVulnerable()\n+ }\n+\n+ set, err := newCPUSet(data, vulnerable)\nif err != nil {\nt.Fatalf(\"Failed to parse CPU data %v\\n%s\", err, data)\n}\n@@ -196,9 +341,7 @@ func TestReadFile(t *testing.T) {\nt.Fatalf(\"Failed to parse any CPUs: %d\", len(set))\n}\n- for _, c := range set {\n- t.Logf(\"CPU: %+v: %t\", c, c.isVulnerable())\n- }\n+ t.Log(set)\n}\n// TestVulnerable tests if the isVulnerable method is correct\n@@ -331,10 +474,6 @@ power management:`\nname: \"skylake\",\ncpuString: skylake,\nvulnerable: true,\n- }, {\n- name: \"cascadeLake\",\n- cpuString: cascade,\n- vulnerable: false,\n}, {\nname: \"amd\",\ncpuString: amd,\n@@ -342,7 +481,7 @@ power management:`\n},\n} {\nt.Run(tc.name, func(t *testing.T) {\n- set, err := getCPUSet(tc.cpuString)\n+ set, err := getThreads(tc.cpuString)\nif err != nil {\nt.Fatalf(\"Failed to getCPUSet:%v\\n %s\", err, tc.cpuString)\n}\n@@ -353,9 +492,6 @@ power management:`\nfor _, c := range set {\ngot := func() bool {\n- if cascadeLake.similarTo(c) {\n- return false\n- }\nreturn c.isVulnerable()\n}()\n" } ]
Go
Apache License 2.0
google/gvisor
Add CPUSet for runsc mitigate. PiperOrigin-RevId: 355242055
259,885
02.02.2021 13:59:42
28,800
ff8b308a30f46993f31f398c6e8d5b3bad03d865
Remove call to Notify from pipe.VFSPipeFD.CopyOutFrom. This was missed in cl/351911375; pipe.VFSPipeFD.SpliceFromNonPipe already calls Notify.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/vfs.go", "new_path": "pkg/sentry/kernel/pipe/vfs.go", "diff": "@@ -368,17 +368,15 @@ func (fd *VFSPipeFD) CopyInTo(ctx context.Context, ars usermem.AddrRangeSeq, dst\n})\n}\n-// CopyOutFrom implements usermem.IO.CopyOutFrom.\n+// CopyOutFrom implements usermem.IO.CopyOutFrom. Note that it is the caller's\n+// responsibility to call fd.pipe.Notify(waiter.EventIn) after the write is\n+// completed.\n//\n// Preconditions: fd.pipe.mu must be locked.\nfunc (fd *VFSPipeFD) CopyOutFrom(ctx context.Context, ars usermem.AddrRangeSeq, src safemem.Reader, opts usermem.IOOpts) (int64, error) {\n- n, err := fd.pipe.writeLocked(ars.NumBytes(), func(dsts safemem.BlockSeq) (uint64, error) {\n+ return fd.pipe.writeLocked(ars.NumBytes(), func(dsts safemem.BlockSeq) (uint64, error) {\nreturn src.ReadToBlocks(dsts)\n})\n- if n > 0 {\n- fd.pipe.Notify(waiter.EventIn)\n- }\n- return n, err\n}\n// SwapUint32 implements usermem.IO.SwapUint32.\n" } ]
Go
Apache License 2.0
google/gvisor
Remove call to Notify from pipe.VFSPipeFD.CopyOutFrom. This was missed in cl/351911375; pipe.VFSPipeFD.SpliceFromNonPipe already calls Notify. PiperOrigin-RevId: 355246655
260,019
14.01.2021 16:50:52
-28,800
25130d6183d399fc3bfa93385aeba6819437ea6c
arm64: clean code In order to improve the performance and stability, I reorg 2 modules slightly. arch: no red zone on Arm64. ring0: use stp instead of movd, and set RSV_REG_APP=R19.
[ { "change_type": "MODIFY", "old_path": "pkg/ring0/defs_arm64.go", "new_path": "pkg/ring0/defs_arm64.go", "diff": "@@ -38,7 +38,7 @@ type KernelArchState struct {\n// CPUArchState contains CPU-specific arch state.\ntype CPUArchState struct {\n// stack is the stack used for interrupts on this CPU.\n- stack [512]byte\n+ stack [128]byte\n// errorCode is the error code from the last exception.\nerrorCode uintptr\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/signal_arm64.go", "new_path": "pkg/sentry/arch/signal_arm64.go", "diff": "@@ -36,7 +36,6 @@ type SignalContext64 struct {\nPstate uint64\n_pad [8]byte // __attribute__((__aligned__(16)))\nFpsimd64 FpsimdContext // size = 528\n- Reserved [3568]uint8\n}\n// +marshal\n@@ -86,10 +85,6 @@ func (c *context64) NewSignalStack() NativeSignalStack {\nfunc (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt *SignalStack, sigset linux.SignalSet) error {\nsp := st.Bottom\n- if !(alt.IsEnabled() && sp == alt.Top()) {\n- sp -= 128\n- }\n-\n// Construct the UContext64 now since we need its size.\nuc := &UContext64{\nFlags: 0,\n@@ -102,6 +97,10 @@ func (c *context64) SignalSetup(st *Stack, act *SignalAct, info *SignalInfo, alt\n},\nSigset: sigset,\n}\n+ if linux.Signal(info.Signo) == linux.SIGSEGV || linux.Signal(info.Signo) == linux.SIGBUS {\n+ uc.MContext.FaultAddr = info.Addr()\n+ }\n+\nucSize := uc.SizeBytes()\n// frameSize = ucSize + sizeof(siginfo).\n" } ]
Go
Apache License 2.0
google/gvisor
arm64: clean code In order to improve the performance and stability, I reorg 2 modules slightly. arch: no red zone on Arm64. ring0: use stp instead of movd, and set RSV_REG_APP=R19. Signed-off-by: Robin Luk <[email protected]>
260,019
14.01.2021 19:06:46
-28,800
6eb80b2e2df4a7e0a0b9dcfc99906a84fd8fc3f0
arm64 kvm:implement basic lazy save and restore for FPSIMD registers Implement basic lazy save and restore for FPSIMD registers, which only restore FPSIMD state on el0_fpsimd_acc and save FPSIMD state in switch().
[ { "change_type": "MODIFY", "old_path": "pkg/ring0/defs_arm64.go", "new_path": "pkg/ring0/defs_arm64.go", "diff": "@@ -55,6 +55,9 @@ type CPUArchState struct {\n// faultAddr is the value of far_el1.\nfaultAddr uintptr\n+ // el0Fp is the address of application's fpstate.\n+ el0Fp uintptr\n+\n// ttbr0Kvm is the value of ttbr0_el1 for sentry.\nttbr0Kvm uintptr\n" }, { "change_type": "MODIFY", "old_path": "pkg/ring0/kernel_arm64.go", "new_path": "pkg/ring0/kernel_arm64.go", "diff": "@@ -62,6 +62,8 @@ func IsCanonical(addr uint64) bool {\n//go:nosplit\nfunc (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\nstoreAppASID(uintptr(switchOpts.UserASID))\n+ storeEl0Fpstate(switchOpts.FloatingPointState)\n+\nif switchOpts.Flush {\nFlushTlbByASID(uintptr(switchOpts.UserASID))\n}\n@@ -71,13 +73,17 @@ func (c *CPU) SwitchToUser(switchOpts SwitchOpts) (vector Vector) {\nregs.Pstate &= ^uint64(PsrFlagsClear)\nregs.Pstate |= UserFlagsSet\n- EnableVFP()\n- LoadFloatingPoint(switchOpts.FloatingPointState)\n+ fpDisableTrap := CPACREL1()\n+ if fpDisableTrap != 0 {\n+ FPSIMDEnableTrap()\n+ }\nkernelExitToEl0()\n+ fpDisableTrap = CPACREL1()\n+ if fpDisableTrap != 0 {\nSaveFloatingPoint(switchOpts.FloatingPointState)\n- DisableVFP()\n+ }\nvector = c.vecCode\n" }, { "change_type": "MODIFY", "old_path": "pkg/ring0/lib_arm64.go", "new_path": "pkg/ring0/lib_arm64.go", "diff": "package ring0\n+// storeEl0Fpstate writes the address of application's fpstate.\n+func storeEl0Fpstate(value *byte)\n+\n// storeAppASID writes the application's asid value.\nfunc storeAppASID(asid uintptr)\n@@ -59,11 +62,10 @@ func LoadFloatingPoint(*byte)\n// SaveFloatingPoint saves floating point state.\nfunc SaveFloatingPoint(*byte)\n-// EnableVFP enables fpsimd.\n-func EnableVFP()\n+func FPSIMDDisableTrap()\n// DisableVFP disables fpsimd.\n-func DisableVFP()\n+func FPSIMDEnableTrap()\n// Init sets function pointers based on architectural features.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/ring0/offsets_arm64.go", "new_path": "pkg/ring0/offsets_arm64.go", "diff": "@@ -36,6 +36,7 @@ func Emit(w io.Writer) {\nfmt.Fprintf(w, \"#define CPU_ERROR_CODE 0x%02x\\n\", reflect.ValueOf(&c.errorCode).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_ERROR_TYPE 0x%02x\\n\", reflect.ValueOf(&c.errorType).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_FAULT_ADDR 0x%02x\\n\", reflect.ValueOf(&c.faultAddr).Pointer()-reflect.ValueOf(c).Pointer())\n+ fmt.Fprintf(w, \"#define CPU_FPSTATE_EL0 0x%02x\\n\", reflect.ValueOf(&c.el0Fp).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_TTBR0_KVM 0x%02x\\n\", reflect.ValueOf(&c.ttbr0Kvm).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_TTBR0_APP 0x%02x\\n\", reflect.ValueOf(&c.ttbr0App).Pointer()-reflect.ValueOf(c).Pointer())\nfmt.Fprintf(w, \"#define CPU_VECTOR_CODE 0x%02x\\n\", reflect.ValueOf(&c.vecCode).Pointer()-reflect.ValueOf(c).Pointer())\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64.go", "diff": "@@ -111,8 +111,8 @@ func (c *vCPU) KernelSyscall() {\nregs.Pc -= 4 // Rewind.\n}\n- vfpEnable := ring0.CPACREL1()\n- if vfpEnable != 0 {\n+ fpDisableTrap := ring0.CPACREL1()\n+ if fpDisableTrap != 0 {\nfpsimd := fpsimdPtr((*byte)(c.floatingPointState))\nfpcr := ring0.GetFPCR()\nfpsr := ring0.GetFPSR()\n@@ -135,8 +135,8 @@ func (c *vCPU) KernelException(vector ring0.Vector) {\nregs.Pc = 0\n}\n- vfpEnable := ring0.CPACREL1()\n- if vfpEnable != 0 {\n+ fpDisableTrap := ring0.CPACREL1()\n+ if fpDisableTrap != 0 {\nfpsimd := fpsimdPtr((*byte)(c.floatingPointState))\nfpcr := ring0.GetFPCR()\nfpsr := ring0.GetFPSR()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_arm64_unsafe.go", "diff": "@@ -70,14 +70,6 @@ func (c *vCPU) initArchState() error {\npanic(fmt.Sprintf(\"error setting KVM_ARM_VCPU_INIT failed: %v\", errno))\n}\n- // cpacr_el1\n- reg.id = _KVM_ARM64_REGS_CPACR_EL1\n- // It is off by default, and it is turned on only when in use.\n- data = 0 // Disable fpsimd.\n- if err := c.setOneRegister(&reg); err != nil {\n- return err\n- }\n-\n// tcr_el1\ndata = _TCR_TXSZ_VA48 | _TCR_CACHE_FLAGS | _TCR_SHARED | _TCR_TG_FLAGS | _TCR_ASID16 | _TCR_IPS_40BITS\nreg.id = _KVM_ARM64_REGS_TCR_EL1\n" } ]
Go
Apache License 2.0
google/gvisor
arm64 kvm:implement basic lazy save and restore for FPSIMD registers Implement basic lazy save and restore for FPSIMD registers, which only restore FPSIMD state on el0_fpsimd_acc and save FPSIMD state in switch(). Signed-off-by: Robin Luk <[email protected]>
259,896
03.02.2021 11:06:55
28,800
e3bce9689fcdbd1f6a3cfd9ead23abcdb0afd368
Add a function to enable RACK in tests. Adds a function to enable RACK in tests. RACK update functions are guarded behind the flag tcpRecovery.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -1320,7 +1320,9 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// unacknowledged and also never retransmitted sequence below\n// RACK.fack, then the corresponding packet has been\n// reordered and RACK.reord is set to TRUE.\n+ if s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.walkSACK(rcvdSeg)\n+ }\ns.SetPipe()\n}\n@@ -1339,7 +1341,9 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n}\n// See if TLP based recovery was successful.\n+ if s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.detectTLPRecovery(ack, rcvdSeg)\n+ }\n// Stash away the current window size.\ns.sndWnd = rcvdSeg.window\n@@ -1421,7 +1425,7 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n}\n// Update the RACK fields if SACK is enabled.\n- if s.ep.sackPermitted && !seg.acked {\n+ if s.ep.sackPermitted && !seg.acked && s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.rc.update(seg, rcvdSeg)\ns.rc.detectReorder(seg)\n}\n@@ -1455,9 +1459,11 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// Update RACK when we are exiting fast or RTO\n// recovery as described in the RFC\n// draft-ietf-tcpm-rack-08 Section-7.2 Step 4.\n+ if s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.rc.exitRecovery()\n}\n}\n+ }\n// It is possible for s.outstanding to drop below zero if we get\n// a retransmit timeout, reset outstanding to zero but later\n@@ -1483,7 +1489,9 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n// * Upon receiving an ACK:\n// * Step 4: Update RACK reordering window\n+ if s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.rc.updateRACKReorderWindow(rcvdSeg)\n+ }\n// Now that we've popped all acknowledged data from the retransmit\n// queue, retransmit if needed.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "diff": "@@ -34,6 +34,14 @@ const (\nmtu = header.TCPMinimumSize + header.IPv4MinimumSize + maxTCPOptionSize + maxPayload\n)\n+func setStackRACKPermitted(t *testing.T, c *context.Context) {\n+ t.Helper()\n+ opt := tcpip.TCPRecovery(tcpip.TCPRACKLossDetection)\n+ if err := c.Stack().SetTransportProtocolOption(header.TCPProtocolNumber, &opt); err != nil {\n+ t.Fatalf(\"c.s.SetTransportProtocolOption(%d, &%v(%v)): %s\", header.TCPProtocolNumber, opt, opt, err)\n+ }\n+}\n+\n// TestRACKUpdate tests the RACK related fields are updated when an ACK is\n// received on a SACK enabled connection.\nfunc TestRACKUpdate(t *testing.T) {\n@@ -60,6 +68,7 @@ func TestRACKUpdate(t *testing.T) {\nclose(probeDone)\n})\nsetStackSACKPermitted(t, c, true)\n+ setStackRACKPermitted(t, c)\ncreateConnectedWithSACKAndTS(c)\ndata := make([]byte, maxPayload)\n@@ -116,6 +125,7 @@ func TestRACKDetectReorder(t *testing.T) {\nclose(probeDone)\n})\nsetStackSACKPermitted(t, c, true)\n+ setStackRACKPermitted(t, c)\ncreateConnectedWithSACKAndTS(c)\ndata := make([]byte, ackNumToVerify*maxPayload)\nfor i := range data {\n@@ -148,6 +158,7 @@ func TestRACKDetectReorder(t *testing.T) {\nfunc sendAndReceive(t *testing.T, c *context.Context, numPackets int) []byte {\nsetStackSACKPermitted(t, c, true)\n+ setStackRACKPermitted(t, c)\ncreateConnectedWithSACKAndTS(c)\ndata := make([]byte, numPackets*maxPayload)\n" } ]
Go
Apache License 2.0
google/gvisor
Add a function to enable RACK in tests. - Adds a function to enable RACK in tests. - RACK update functions are guarded behind the flag tcpRecovery. PiperOrigin-RevId: 355435973
259,907
04.02.2021 08:25:44
28,800
fa2d3698c44c7a691dd438ce8a7f92789bd909d2
[infra] Do not recompile integration test executables each time. Instead build the executable into the image.
[ { "change_type": "MODIFY", "old_path": "images/basic/integrationtest/Dockerfile.x86_64", "new_path": "images/basic/integrationtest/Dockerfile.x86_64", "diff": "@@ -5,3 +5,9 @@ COPY . .\nRUN chmod +x *.sh\nRUN apt-get update && apt-get install -y gcc iputils-ping iproute2\n+\n+# Compilation Steps.\n+RUN gcc -O2 -o test_copy_up test_copy_up.c\n+RUN gcc -O2 -o test_rewinddir test_rewinddir.c\n+RUN gcc -O2 -o link_test link_test.c\n+RUN gcc -O2 -o test_sticky test_sticky.c\n" }, { "change_type": "MODIFY", "old_path": "test/e2e/integration_test.go", "new_path": "test/e2e/integration_test.go", "diff": "@@ -434,7 +434,7 @@ func TestTmpMount(t *testing.T) {\n// runsc to hide the incoherence of FDs opened before and after overlayfs\n// copy-up on the host.\nfunc TestHostOverlayfsCopyUp(t *testing.T) {\n- runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o test_copy_up test_copy_up.c && ./test_copy_up\")\n+ runIntegrationTest(t, nil, \"./test_copy_up\")\n}\n// TestHostOverlayfsRewindDir tests that rewinddir() \"causes the directory\n@@ -449,14 +449,14 @@ func TestHostOverlayfsCopyUp(t *testing.T) {\n// automated tests yield newly-added files from readdir() even if the fsgofer\n// does not explicitly rewinddir(), but overlayfs does not.\nfunc TestHostOverlayfsRewindDir(t *testing.T) {\n- runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o test_rewinddir test_rewinddir.c && ./test_rewinddir\")\n+ runIntegrationTest(t, nil, \"./test_rewinddir\")\n}\n// Basic test for linkat(2). Syscall tests requires CAP_DAC_READ_SEARCH and it\n// cannot use tricks like userns as root. For this reason, run a basic link test\n// to ensure some coverage.\nfunc TestLink(t *testing.T) {\n- runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o link_test link_test.c && ./link_test\")\n+ runIntegrationTest(t, nil, \"./link_test\")\n}\n// This test ensures we can run ping without errors.\n@@ -498,7 +498,7 @@ func TestStickyDir(t *testing.T) {\nt.Skip(\"sticky bit test fails on VFS1.\")\n}\n- runIntegrationTest(t, nil, \"sh\", \"-c\", \"gcc -O2 -o test_sticky test_sticky.c && ./test_sticky\")\n+ runIntegrationTest(t, nil, \"./test_sticky\")\n}\nfunc runIntegrationTest(t *testing.T, capAdd []string, args ...string) {\n" } ]
Go
Apache License 2.0
google/gvisor
[infra] Do not recompile integration test executables each time. Instead build the executable into the image. PiperOrigin-RevId: 355631672
259,896
04.02.2021 09:36:09
28,800
eaba5bc7ef382c6070c02186ca86f734bf5d8a57
Fix flaky packetimpact test
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_rack_test.go", "new_path": "test/packetimpact/tests/tcp_rack_test.go", "diff": "@@ -168,9 +168,10 @@ func TestRACKTLPLost(t *testing.T) {\ncloseSACKConnection(t, dut, conn, acceptFd, listenFd)\n}\n-// TestRACKTLPWithSACK tests TLP by acknowledging out of order packets.\n+// TestRACKWithSACK tests that RACK marks the packets as lost after receiving\n+// the ACK for retransmitted packets.\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-8.1\n-func TestRACKTLPWithSACK(t *testing.T) {\n+func TestRACKWithSACK(t *testing.T) {\ndut, conn, acceptFd, listenFd := createSACKConnection(t)\nseqNum1 := *conn.RemoteSeqNum(t)\n@@ -180,8 +181,9 @@ func TestRACKTLPWithSACK(t *testing.T) {\n// We are not sending ACK for these packets.\nconst numPkts = 3\n- lastSent := sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+ sendAndReceive(t, dut, conn, numPkts, acceptFd, false /* sendACK */)\n+ time.Sleep(simulatedRTT)\n// SACK for #2 packet.\nsackBlock := make([]byte, 40)\nstart := seqNum1.Add(seqnum.Size(payloadSize))\n@@ -194,32 +196,25 @@ func TestRACKTLPWithSACK(t *testing.T) {\n}}, sackBlock[sbOff:])\nconn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n- // RACK marks #1 packet as lost and retransmits it.\n- if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, time.Second); err != nil {\n+ rtt, _ := getRTTAndRTO(t, dut, acceptFd)\n+ timeout := 2 * rtt\n+ // RACK marks #1 packet as lost after RTT+reorderWindow(RTT/4) and\n+ // retransmits it.\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, timeout); err != nil {\nt.Fatalf(\"expected payload was not received: %s\", err)\n}\n+ time.Sleep(simulatedRTT)\n// ACK for #1 packet.\nconn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(end))})\n- // Probe Timeout (PTO) should be two times RTT. TLP will trigger for #3\n- // packet. RACK adds an additional timeout of 200ms if the number of\n- // outstanding packets is equal to 1.\n- rtt, rto := getRTTAndRTO(t, dut, acceptFd)\n- pto := rtt*2 + (200 * time.Millisecond)\n- if rto < pto {\n- pto = rto\n- }\n- // We expect the 3rd packet (the last unacknowledged packet) to be\n- // retransmitted.\n- tlpProbe := testbench.Uint32(uint32(seqNum1) + uint32((numPkts-1)*payloadSize))\n- if _, err := conn.Expect(t, testbench.TCP{SeqNum: tlpProbe}, time.Second); err != nil {\n+ // RACK considers transmission times of the packets to mark them lost.\n+ // As the 3rd packet was sent before the retransmitted 1st packet, RACK\n+ // marks it as lost and retransmits it..\n+ expectedSeqNum := testbench.Uint32(uint32(seqNum1) + uint32((numPkts-1)*payloadSize))\n+ if _, err := conn.Expect(t, testbench.TCP{SeqNum: expectedSeqNum}, timeout); err != nil {\nt.Fatalf(\"expected payload was not received: %s\", err)\n}\n- diff := time.Now().Sub(lastSent)\n- if diff < pto {\n- t.Fatalf(\"expected payload was received before the probe timeout, got: %v, want: %v\", diff, pto)\n- }\ncloseSACKConnection(t, dut, conn, acceptFd, listenFd)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix flaky packetimpact test PiperOrigin-RevId: 355645297
259,853
04.02.2021 10:39:04
28,800
63c9dd365666c35a0c10444e56367c2d13e15562
images: Rework syzkaller documentation.
[ { "change_type": "MODIFY", "old_path": "images/syzkaller/Dockerfile", "new_path": "images/syzkaller/Dockerfile", "diff": "FROM gcr.io/syzkaller/env\n+# This image is mostly for investigating syzkaller crashes, so let's install\n+# developer tools.\nRUN apt update && apt install -y git vim strace gdb procps\nWORKDIR /syzkaller/gopath/src/github.com/google/syzkaller\n" }, { "change_type": "MODIFY", "old_path": "images/syzkaller/README.md", "new_path": "images/syzkaller/README.md", "diff": "@@ -5,21 +5,54 @@ syzkaller is an unsupervised coverage-guided kernel fuzzer.\n# How to run syzkaller.\n-* Build the syzkaller docker image `make load-syzkaller`\n-* Build runsc and place it in /tmp/syzkaller. `make RUNTIME_DIR=/tmp/syzkaller\n- refresh`\n-* Copy the syzkaller config in /tmp/syzkaller `cp\n- images/syzkaller/default-gvisor-config.cfg /tmp/syzkaller/syzkaller.cfg`\n-* Run syzkaller `docker run --privileged -it --rm -v\n- /tmp/syzkaller:/tmp/syzkaller gvisor.dev/images/syzkaller:latest`\n+First, we need to load a syzkaller docker image:\n+\n+```bash\n+make load-syzkaller\n+```\n+\n+or we can rebuild it to use an up-to-date version of the master branch:\n+\n+```bash\n+make rebuild-syzkaller\n+```\n+\n+Then we need to create a directory with all artifacts that we will need to run a\n+syzkaller. Then we will bind-mount this directory to a docker container.\n+\n+We need to build runsc and place it on the artifact directory:\n+\n+```bash\n+make RUNTIME_DIR=/tmp/syzkaller refresh\n+```\n+\n+The next step is to create a syzkaller config. We can copy the default one and\n+customize it:\n+\n+```bash\n+cp images/syzkaller/default-gvisor-config.cfg /tmp/syzkaller/syzkaller.cfg\n+```\n+\n+Now we can start syzkaller in a docker container:\n+\n+```bash\n+docker run --privileged -it --rm \\\n+ -v /tmp/syzkaller:/tmp/syzkaller \\\n+ gvisor.dev/images/syzkaller:latest\n+```\n+\n+All logs will be in /tmp/syzkaller/workdir.\n# How to run a syz repro.\n-* Repeate all steps except the last one from the previous section.\n+We need to repeat all preparation steps from the previous section and save a\n+syzkaller repro in /tmp/syzkaller/repro.\n-* Save a syzkaller repro in /tmp/syzkaller/repro\n+Now we can run syz-repro to reproduce a crash:\n-* Run syz-repro `docker run --privileged -it --rm -v\n+```bash\n+docker run --privileged -it --rm -v\n/tmp/syzkaller:/tmp/syzkaller --entrypoint=\"\"\ngvisor.dev/images/syzkaller:latest ./bin/syz-repro -config\n- /tmp/syzkaller/syzkaller.cfg /tmp/syzkaller/repro`\n+ /tmp/syzkaller/syzkaller.cfg /tmp/syzkaller/repro\n+```\n" } ]
Go
Apache License 2.0
google/gvisor
images: Rework syzkaller documentation. PiperOrigin-RevId: 355660221
259,881
04.02.2021 14:54:42
28,800
41510d2746756818269b0bf8f3961f026a0c247c
Move getcpu() to core filter list Some versions of the Go runtime call getcpu(), so add it for compatibility. The hostcpu package already uses getcpu() on arm64.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/filters.go", "new_path": "pkg/sentry/platform/ptrace/filters.go", "diff": "@@ -17,14 +17,12 @@ package ptrace\nimport (\n\"syscall\"\n- \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/seccomp\"\n)\n// SyscallFilters returns syscalls made exclusively by the ptrace platform.\nfunc (*PTrace) SyscallFilters() seccomp.SyscallRules {\nreturn seccomp.SyscallRules{\n- unix.SYS_GETCPU: {},\nsyscall.SYS_PTRACE: {},\nsyscall.SYS_TGKILL: {},\nsyscall.SYS_WAIT4: {},\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -100,6 +100,15 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.MatchAny{},\n},\n},\n+ // getcpu is used by some versions of the Go runtime and by the hostcpu\n+ // package on arm64.\n+ unix.SYS_GETCPU: []seccomp.Rule{\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(0),\n+ seccomp.EqualTo(0),\n+ },\n+ },\nsyscall.SYS_GETPID: {},\nunix.SYS_GETRANDOM: {},\nsyscall.SYS_GETSOCKOPT: []seccomp.Rule{\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config.go", "new_path": "runsc/fsgofer/filter/config.go", "diff": "@@ -107,6 +107,15 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.MatchAny{},\n},\n},\n+ // getcpu is used by some versions of the Go runtime and by the hostcpu\n+ // package on arm64.\n+ unix.SYS_GETCPU: []seccomp.Rule{\n+ {\n+ seccomp.MatchAny{},\n+ seccomp.EqualTo(0),\n+ seccomp.EqualTo(0),\n+ },\n+ },\nsyscall.SYS_GETDENTS64: {},\nsyscall.SYS_GETPID: {},\nunix.SYS_GETRANDOM: {},\n" } ]
Go
Apache License 2.0
google/gvisor
Move getcpu() to core filter list Some versions of the Go runtime call getcpu(), so add it for compatibility. The hostcpu package already uses getcpu() on arm64. PiperOrigin-RevId: 355717757
260,004
04.02.2021 17:58:58
28,800
71def1c5869af69e4127f2b07ebd7d5c62642597
Lock ConnTrack before initializing buckets
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/conntrack.go", "new_path": "pkg/tcpip/stack/conntrack.go", "diff": "@@ -231,6 +231,12 @@ func newConn(orig, reply tupleID, manip manipType, hook Hook) *conn {\nreturn &conn\n}\n+func (ct *ConnTrack) init() {\n+ ct.mu.Lock()\n+ defer ct.mu.Unlock()\n+ ct.buckets = make([]bucket, numBuckets)\n+}\n+\n// connFor gets the conn for pkt if it exists, or returns nil\n// if it does not. It returns an error when pkt does not contain a valid TCP\n// header.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables.go", "new_path": "pkg/tcpip/stack/iptables.go", "diff": "@@ -235,7 +235,7 @@ func (it *IPTables) ReplaceTable(id TableID, table Table, ipv6 bool) tcpip.Error\n// If iptables is being enabled, initialize the conntrack table and\n// reaper.\nif !it.modified {\n- it.connections.buckets = make([]bucket, numBuckets)\n+ it.connections.init()\nit.startReaper(reaperDelay)\n}\nit.modified = true\n" } ]
Go
Apache License 2.0
google/gvisor
Lock ConnTrack before initializing buckets PiperOrigin-RevId: 355751801
260,004
05.02.2021 16:44:49
28,800
24416032ab848cff7696b3f37e4c18220aeee2c0
Refactor locally delivered packets Make it clear that failing to parse a looped back is not a packet sending error but a malformed received packet error. FindNetworkEndpoint returns nil when no network endpoint is found instead of an error.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/BUILD", "new_path": "pkg/tcpip/network/BUILD", "diff": "@@ -16,7 +16,6 @@ go_test(\n\"//pkg/tcpip/checker\",\n\"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n- \"//pkg/tcpip/header/parse\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/loopback\",\n\"//pkg/tcpip/network/ipv4\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp.go", "new_path": "pkg/tcpip/network/arp/arp.go", "diff": "@@ -129,6 +129,11 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n+ if _, _, ok := e.protocol.Parse(pkt); !ok {\n+ stats.malformedPacketsReceived.Increment()\n+ return\n+ }\n+\nh := header.ARP(pkt.NetworkHeader().View())\nif !h.IsValid() {\nstats.malformedPacketsReceived.Increment()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip_test.go", "new_path": "pkg/tcpip/network/ip_test.go", "diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n- \"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\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@@ -626,9 +625,6 @@ func TestReceive(t *testing.T) {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: view.ToVectorisedView(),\n})\n- if ok := parse.IPv4(pkt); !ok {\n- t.Fatalf(\"failed to parse packet: %x\", pkt.Data.ToView())\n- }\nep.HandlePacket(pkt)\n},\n},\n@@ -664,9 +660,6 @@ func TestReceive(t *testing.T) {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: view.ToVectorisedView(),\n})\n- if _, _, _, _, ok := parse.IPv6(pkt); !ok {\n- t.Fatalf(\"failed to parse packet: %x\", pkt.Data.ToView())\n- }\nep.HandlePacket(pkt)\n},\n},\n@@ -943,9 +936,6 @@ func TestIPv4FragmentationReceive(t *testing.T) {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: frag1.ToVectorisedView(),\n})\n- if _, _, ok := proto.Parse(pkt); !ok {\n- t.Fatalf(\"failed to parse packet: %x\", pkt.Data.ToView())\n- }\naddressableEndpoint, ok := ep.(stack.AddressableEndpoint)\nif !ok {\n@@ -967,9 +957,6 @@ func TestIPv4FragmentationReceive(t *testing.T) {\npkt = stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: frag2.ToVectorisedView(),\n})\n- if _, _, ok := proto.Parse(pkt); !ok {\n- t.Fatalf(\"failed to parse packet: %x\", pkt.Data.ToView())\n- }\nep.HandlePacket(pkt)\nif nic.testObject.dataCalls != 1 {\nt.Fatalf(\"Bad number of data calls: got %x, want 1\", nic.testObject.dataCalls)\n@@ -1234,7 +1221,6 @@ func truncatedPacket(view buffer.View, trunc, netHdrLen int) *stack.PacketBuffer\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: v.ToVectorisedView(),\n})\n- _, _ = pkt.NetworkHeader().Consume(netHdrLen)\nreturn pkt\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -347,15 +347,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\n// short circuits broadcasts before they are sent out to other hosts.\nif pkt.NatDone {\nnetHeader := header.IPv4(pkt.NetworkHeader().View())\n- ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress())\n- if err == nil {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n- // Since we rewrote the packet but it is being routed back to us, we can\n- // safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = true\n- ep.(*endpoint).handlePacket(pkt)\n- }\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n+ // Since we rewrote the packet but it is being routed back to us, we\n+ // can safely assume the checksum is valid.\n+ ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nreturn nil\n}\n}\n@@ -365,14 +360,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\nfunc (e *endpoint) writePacket(r *stack.Route, gso *stack.GSO, pkt *stack.PacketBuffer, headerIncluded bool) tcpip.Error {\nif r.Loop&stack.PacketLoop != 0 {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n// If the packet was generated by the stack (not a raw/packet endpoint\n// where a packet may be written with the header included), then we can\n// safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = !headerIncluded\n- e.handlePacket(pkt)\n- }\n+ e.handleLocalPacket(pkt, !headerIncluded /* canSkipRXChecksum */)\n}\nif r.Loop&stack.PacketOut == 0 {\nreturn nil\n@@ -471,14 +462,10 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n}\nif _, ok := natPkts[pkt]; ok {\nnetHeader := header.IPv4(pkt.NetworkHeader().View())\n- if ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); err == nil {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n// can safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = true\n- ep.(*endpoint).handlePacket(pkt)\n- }\n+ ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nn++\ncontinue\n}\n@@ -573,14 +560,10 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) tcpip.Error {\ndstAddr := h.DestinationAddress()\n// Check if the destination is owned by the stack.\n- networkEndpoint, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr)\n- if err == nil {\n- networkEndpoint.(*endpoint).handlePacket(pkt)\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr); ep != nil {\n+ ep.(*endpoint).handlePacket(pkt)\nreturn nil\n}\n- if _, ok := err.(*tcpip.ErrBadAddress); !ok {\n- return err\n- }\nr, err := e.protocol.stack.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\nif err != nil {\n@@ -619,8 +602,26 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n- // Loopback traffic skips the prerouting chain.\n+ if !e.protocol.parse(pkt) {\n+ stats.MalformedPacketsReceived.Increment()\n+ return\n+ }\n+\nif !e.nic.IsLoopback() {\n+ if e.protocol.stack.HandleLocal() {\n+ addressEndpoint := e.AcquireAssignedAddress(header.IPv4(pkt.NetworkHeader().View()).SourceAddress(), e.nic.Promiscuous(), stack.CanBePrimaryEndpoint)\n+ if addressEndpoint != nil {\n+ addressEndpoint.DecRef()\n+\n+ // The source address is one of our own, so we never should have gotten\n+ // a packet like this unless HandleLocal is false or our NIC is the\n+ // loopback interface.\n+ stats.InvalidSourceAddressesReceived.Increment()\n+ return\n+ }\n+ }\n+\n+ // Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\nif ok := e.protocol.stack.IPTables().Check(stack.Prerouting, pkt, nil, nil, e.MainAddress().Address, inNicName, \"\" /* outNicName */); !ok {\n// iptables is telling us to drop the packet.\n@@ -632,6 +633,21 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\ne.handlePacket(pkt)\n}\n+func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum bool) {\n+ stats := e.stats.ip\n+\n+ stats.PacketsReceived.Increment()\n+\n+ pkt = pkt.CloneToInbound()\n+ if e.protocol.parse(pkt) {\n+ pkt.RXTransportChecksumValidated = canSkipRXChecksum\n+ e.handlePacket(pkt)\n+ return\n+ }\n+\n+ stats.MalformedPacketsReceived.Increment()\n+}\n+\n// handlePacket is like HandlePacket except it does not perform the prerouting\n// iptables hook.\nfunc (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\n@@ -1043,6 +1059,29 @@ func (*protocol) Close() {}\n// Wait implements stack.TransportProtocol.Wait.\nfunc (*protocol) Wait() {}\n+// parse is like Parse but also attempts to parse the transport layer.\n+//\n+// Returns true if the network header was successfully parsed.\n+func (p *protocol) parse(pkt *stack.PacketBuffer) bool {\n+ transProtoNum, hasTransportHdr, ok := p.Parse(pkt)\n+ if !ok {\n+ return false\n+ }\n+\n+ if hasTransportHdr {\n+ switch err := p.stack.ParsePacketBufferTransport(transProtoNum, pkt); err {\n+ case stack.ParsedOK:\n+ case stack.UnknownTransportProtocol, stack.TransportLayerParseError:\n+ // The transport layer will handle unknown protocols and transport layer\n+ // parsing errors.\n+ default:\n+ panic(fmt.Sprintf(\"unexpected error parsing transport header = %d\", err))\n+ }\n+ }\n+\n+ return true\n+}\n+\n// Parse implements stack.NetworkProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool) {\nif ok := parse.IPv4(pkt); !ok {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -149,6 +149,23 @@ func (t *testInterface) HandleNeighborConfirmation(tcpip.NetworkProtocolNumber,\nreturn nil\n}\n+func handleICMPInIPv6(ep stack.NetworkEndpoint, src, dst tcpip.Address, icmp header.ICMPv6) {\n+ ip := buffer.NewView(header.IPv6MinimumSize)\n+ header.IPv6(ip).Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(len(icmp)),\n+ TransportProtocol: header.ICMPv6ProtocolNumber,\n+ HopLimit: header.NDPHopLimit,\n+ SrcAddr: src,\n+ DstAddr: dst,\n+ })\n+ vv := ip.ToVectorisedView()\n+ vv.AppendView(buffer.View(icmp))\n+ ep.HandlePacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ ReserveHeaderBytes: header.IPv6MinimumSize,\n+ Data: vv,\n+ }))\n+}\n+\nfunc TestICMPCounts(t *testing.T) {\ntests := []struct {\nname string\n@@ -282,33 +299,17 @@ func TestICMPCounts(t *testing.T) {\n},\n}\n- handleIPv6Payload := func(icmp header.ICMPv6) {\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.IPv6MinimumSize,\n- Data: buffer.View(icmp).ToVectorisedView(),\n- })\n- ip := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))\n- ip.Encode(&header.IPv6Fields{\n- PayloadLength: uint16(len(icmp)),\n- TransportProtocol: header.ICMPv6ProtocolNumber,\n- HopLimit: header.NDPHopLimit,\n- SrcAddr: lladdr1,\n- DstAddr: lladdr0,\n- })\n- ep.HandlePacket(pkt)\n- }\n-\nfor _, typ := range types {\nicmp := header.ICMPv6(buffer.NewView(typ.size + len(typ.extraData)))\ncopy(icmp[typ.size:], typ.extraData)\nicmp.SetType(typ.typ)\nicmp.SetChecksum(header.ICMPv6Checksum(icmp[:typ.size], lladdr0, lladdr1, buffer.View(typ.extraData).ToVectorisedView()))\n- handleIPv6Payload(icmp)\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, icmp)\n}\n// Construct an empty ICMP packet so that\n// Stats().ICMP.ICMPv6ReceivedPacketStats.Invalid is incremented.\n- handleIPv6Payload(header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\nicmpv6Stats := s.Stats().ICMP.V6.PacketsReceived\nvisitStats(reflect.ValueOf(&icmpv6Stats).Elem(), func(name string, s *tcpip.StatCounter) {\n@@ -440,33 +441,17 @@ func TestICMPCountsWithNeighborCache(t *testing.T) {\n},\n}\n- handleIPv6Payload := func(icmp header.ICMPv6) {\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.IPv6MinimumSize,\n- Data: buffer.View(icmp).ToVectorisedView(),\n- })\n- ip := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))\n- ip.Encode(&header.IPv6Fields{\n- PayloadLength: uint16(len(icmp)),\n- TransportProtocol: header.ICMPv6ProtocolNumber,\n- HopLimit: header.NDPHopLimit,\n- SrcAddr: lladdr1,\n- DstAddr: lladdr0,\n- })\n- ep.HandlePacket(pkt)\n- }\n-\nfor _, typ := range types {\nicmp := header.ICMPv6(buffer.NewView(typ.size + len(typ.extraData)))\ncopy(icmp[typ.size:], typ.extraData)\nicmp.SetType(typ.typ)\nicmp.SetChecksum(header.ICMPv6Checksum(icmp[:typ.size], lladdr0, lladdr1, buffer.View(typ.extraData).ToVectorisedView()))\n- handleIPv6Payload(icmp)\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, icmp)\n}\n// Construct an empty ICMP packet so that\n// Stats().ICMP.ICMPv6ReceivedPacketStats.Invalid is incremented.\n- handleIPv6Payload(header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\nicmpv6Stats := s.Stats().ICMP.V6.PacketsReceived\nvisitStats(reflect.ValueOf(&icmpv6Stats).Elem(), func(name string, s *tcpip.StatCounter) {\n@@ -1818,19 +1803,7 @@ func TestCallsToNeighborCache(t *testing.T) {\nicmp := test.createPacket()\nicmp.SetChecksum(header.ICMPv6Checksum(icmp, test.source, test.destination, buffer.VectorisedView{}))\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.IPv6MinimumSize,\n- Data: buffer.View(icmp).ToVectorisedView(),\n- })\n- ip := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize))\n- ip.Encode(&header.IPv6Fields{\n- PayloadLength: uint16(len(icmp)),\n- TransportProtocol: header.ICMPv6ProtocolNumber,\n- HopLimit: header.NDPHopLimit,\n- SrcAddr: test.source,\n- DstAddr: test.destination,\n- })\n- ep.HandlePacket(pkt)\n+ handleICMPInIPv6(ep, test.source, test.destination, icmp)\n// Confirm the endpoint calls the correct NUDHandler method.\nif testInterface.probeCount != test.wantProbeCount {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -648,14 +648,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\n// short circuits broadcasts before they are sent out to other hosts.\nif pkt.NatDone {\nnetHeader := header.IPv6(pkt.NetworkHeader().View())\n- if ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); err == nil {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n- // Since we rewrote the packet but it is being routed back to us, we can\n- // safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = true\n- ep.(*endpoint).handlePacket(pkt)\n- }\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n+ // Since we rewrote the packet but it is being routed back to us, we\n+ // can safely assume the checksum is valid.\n+ ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nreturn nil\n}\n}\n@@ -665,14 +661,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\nfunc (e *endpoint) writePacket(r *stack.Route, gso *stack.GSO, pkt *stack.PacketBuffer, protocol tcpip.TransportProtocolNumber, headerIncluded bool) tcpip.Error {\nif r.Loop&stack.PacketLoop != 0 {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n// If the packet was generated by the stack (not a raw/packet endpoint\n// where a packet may be written with the header included), then we can\n// safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = !headerIncluded\n- e.handlePacket(pkt)\n- }\n+ e.handleLocalPacket(pkt, !headerIncluded /* canSkipRXChecksum */)\n}\nif r.Loop&stack.PacketOut == 0 {\nreturn nil\n@@ -771,14 +763,10 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n}\nif _, ok := natPkts[pkt]; ok {\nnetHeader := header.IPv6(pkt.NetworkHeader().View())\n- if ep, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); err == nil {\n- pkt := pkt.CloneToInbound()\n- if e.protocol.stack.ParsePacketBuffer(ProtocolNumber, pkt) == stack.ParsedOK {\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n// can safely assume the checksum is valid.\n- pkt.RXTransportChecksumValidated = true\n- ep.(*endpoint).handlePacket(pkt)\n- }\n+ ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nn++\ncontinue\n}\n@@ -852,14 +840,11 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) tcpip.Error {\ndstAddr := h.DestinationAddress()\n// Check if the destination is owned by the stack.\n- networkEndpoint, err := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr)\n- if err == nil {\n- networkEndpoint.(*endpoint).handlePacket(pkt)\n+\n+ if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr); ep != nil {\n+ ep.(*endpoint).handlePacket(pkt)\nreturn nil\n}\n- if _, ok := err.(*tcpip.ErrBadAddress); !ok {\n- return err\n- }\nr, err := e.protocol.stack.FindRoute(0, \"\", dstAddr, ProtocolNumber, false /* multicastLoop */)\nif err != nil {\n@@ -896,8 +881,26 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n- // Loopback traffic skips the prerouting chain.\n+ if !e.protocol.parse(pkt) {\n+ stats.MalformedPacketsReceived.Increment()\n+ return\n+ }\n+\nif !e.nic.IsLoopback() {\n+ if e.protocol.stack.HandleLocal() {\n+ addressEndpoint := e.AcquireAssignedAddress(header.IPv6(pkt.NetworkHeader().View()).SourceAddress(), e.nic.Promiscuous(), stack.CanBePrimaryEndpoint)\n+ if addressEndpoint != nil {\n+ addressEndpoint.DecRef()\n+\n+ // The source address is one of our own, so we never should have gotten\n+ // a packet like this unless HandleLocal is false or our NIC is the\n+ // loopback interface.\n+ stats.InvalidSourceAddressesReceived.Increment()\n+ return\n+ }\n+ }\n+\n+ // Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\nif ok := e.protocol.stack.IPTables().Check(stack.Prerouting, pkt, nil, nil, e.MainAddress().Address, inNicName, \"\" /* outNicName */); !ok {\n// iptables is telling us to drop the packet.\n@@ -909,6 +912,21 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\ne.handlePacket(pkt)\n}\n+func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum bool) {\n+ stats := e.stats.ip\n+\n+ stats.PacketsReceived.Increment()\n+\n+ pkt = pkt.CloneToInbound()\n+ if e.protocol.parse(pkt) {\n+ pkt.RXTransportChecksumValidated = canSkipRXChecksum\n+ e.handlePacket(pkt)\n+ return\n+ }\n+\n+ stats.MalformedPacketsReceived.Increment()\n+}\n+\n// handlePacket is like HandlePacket except it does not perform the prerouting\n// iptables hook.\nfunc (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\n@@ -1798,6 +1816,29 @@ func (*protocol) Close() {}\n// Wait implements stack.TransportProtocol.Wait.\nfunc (*protocol) Wait() {}\n+// parse is like Parse but also attempts to parse the transport layer.\n+//\n+// Returns true if the network header was successfully parsed.\n+func (p *protocol) parse(pkt *stack.PacketBuffer) bool {\n+ transProtoNum, hasTransportHdr, ok := p.Parse(pkt)\n+ if !ok {\n+ return false\n+ }\n+\n+ if hasTransportHdr {\n+ switch err := p.stack.ParsePacketBufferTransport(transProtoNum, pkt); err {\n+ case stack.ParsedOK:\n+ case stack.UnknownTransportProtocol, stack.TransportLayerParseError:\n+ // The transport layer will handle unknown protocols and transport layer\n+ // parsing errors.\n+ default:\n+ panic(fmt.Sprintf(\"unexpected error parsing transport header = %d\", err))\n+ }\n+ }\n+\n+ return true\n+}\n+\n// Parse implements stack.NetworkProtocol.Parse.\nfunc (*protocol) Parse(pkt *stack.PacketBuffer) (proto tcpip.TransportProtocolNumber, hasTransportHdr bool, ok bool) {\nproto, _, fragOffset, fragMore, ok := parse.IPv6(pkt)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -977,12 +977,8 @@ func TestNDPValidation(t *testing.T) {\n}\nextHdrsLen := extHdrs.Length()\n- pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.IPv6MinimumSize + extHdrsLen,\n- Data: payload.ToVectorisedView(),\n- })\n- ip := header.IPv6(pkt.NetworkHeader().Push(header.IPv6MinimumSize + extHdrsLen))\n- ip.Encode(&header.IPv6Fields{\n+ ip := buffer.NewView(header.IPv6MinimumSize + extHdrsLen)\n+ header.IPv6(ip).Encode(&header.IPv6Fields{\nPayloadLength: uint16(len(payload) + extHdrsLen),\nTransportProtocol: header.ICMPv6ProtocolNumber,\nHopLimit: hopLimit,\n@@ -990,7 +986,11 @@ func TestNDPValidation(t *testing.T) {\nDstAddr: lladdr0,\nExtensionHeaders: extHdrs,\n})\n- ep.HandlePacket(pkt)\n+ vv := ip.ToVectorisedView()\n+ vv.AppendView(payload)\n+ ep.HandlePacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: vv,\n+ }))\n}\nvar tllData [header.NDPLinkLayerAddressSize]byte\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/forwarding_test.go", "new_path": "pkg/tcpip/stack/forwarding_test.go", "diff": "@@ -75,6 +75,10 @@ func (*fwdTestNetworkEndpoint) DefaultTTL() uint8 {\n}\nfunc (f *fwdTestNetworkEndpoint) HandlePacket(pkt *PacketBuffer) {\n+ if _, _, ok := f.proto.Parse(pkt); !ok {\n+ return\n+ }\n+\nnetHdr := pkt.NetworkHeader().View()\n_, dst := f.proto.ParseAddresses(netHdr)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -777,36 +777,6 @@ func (n *NIC) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\nanyEPs.forEach(deliverPacketEPs)\n}\n- // Parse headers.\n- netProto := n.stack.NetworkProtocolInstance(protocol)\n- transProtoNum, hasTransportHdr, ok := netProto.Parse(pkt)\n- if !ok {\n- // The packet is too small to contain a network header.\n- n.stack.stats.MalformedRcvdPackets.Increment()\n- return\n- }\n- if hasTransportHdr {\n- pkt.TransportProtocolNumber = transProtoNum\n- // Parse the transport header if present.\n- if state, ok := n.stack.transportProtocols[transProtoNum]; ok {\n- state.proto.Parse(pkt)\n- }\n- }\n-\n- if n.stack.handleLocal && !n.IsLoopback() {\n- src, _ := netProto.ParseAddresses(pkt.NetworkHeader().View())\n- if r := n.getAddress(protocol, src); r != nil {\n- r.DecRef()\n-\n- // The source address is one of our own, so we never should have gotten a\n- // packet like this unless handleLocal is false. Loopback also calls this\n- // function even though the packets didn't come from the physical interface\n- // so don't drop those.\n- n.stack.stats.IP.InvalidSourceAddressesReceived.Increment()\n- return\n- }\n- }\n-\nnetworkEndpoint.HandlePacket(pkt)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -1319,6 +1319,11 @@ func (s *Stack) findLocalRouteRLocked(localAddressNICID tcpip.NICID, localAddr,\nreturn nil\n}\n+// HandleLocal returns true if non-loopback interfaces are allowed to loop packets.\n+func (s *Stack) HandleLocal() bool {\n+ return s.handleLocal\n+}\n+\n// FindRoute creates a route to the given destination address, leaving through\n// the given NIC and local address (if provided).\n//\n@@ -2063,7 +2068,9 @@ func generateRandInt64() int64 {\n}\n// FindNetworkEndpoint returns the network endpoint for the given address.\n-func (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, address tcpip.Address) (NetworkEndpoint, tcpip.Error) {\n+//\n+// Returns nil if the address is not associated with any network endpoint.\n+func (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, address tcpip.Address) NetworkEndpoint {\ns.mu.RLock()\ndefer s.mu.RUnlock()\n@@ -2073,9 +2080,9 @@ func (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, addres\ncontinue\n}\naddressEndpoint.DecRef()\n- return nic.getNetworkEndpoint(netProto), nil\n+ return nic.getNetworkEndpoint(netProto)\n}\n- return nil, &tcpip.ErrBadAddress{}\n+ return nil\n}\n// FindNICNameFromID returns the name of the NIC for the given NICID.\n@@ -2103,13 +2110,6 @@ const (\n// ParsedOK indicates that a packet was successfully parsed.\nParsedOK ParseResult = iota\n- // UnknownNetworkProtocol indicates that the network protocol is unknown.\n- UnknownNetworkProtocol\n-\n- // NetworkLayerParseError indicates that the network packet was not\n- // successfully parsed.\n- NetworkLayerParseError\n-\n// UnknownTransportProtocol indicates that the transport protocol is unknown.\nUnknownTransportProtocol\n@@ -2118,31 +2118,19 @@ const (\nTransportLayerParseError\n)\n-// ParsePacketBuffer parses the provided packet buffer.\n-func (s *Stack) ParsePacketBuffer(protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) ParseResult {\n- netProto, ok := s.networkProtocols[protocol]\n- if !ok {\n- return UnknownNetworkProtocol\n- }\n-\n- transProtoNum, hasTransportHdr, ok := netProto.Parse(pkt)\n- if !ok {\n- return NetworkLayerParseError\n- }\n- if !hasTransportHdr {\n- return ParsedOK\n- }\n-\n+// ParsePacketBufferTransport parses the provided packet buffer's transport\n+// header.\n+func (s *Stack) ParsePacketBufferTransport(protocol tcpip.TransportProtocolNumber, pkt *PacketBuffer) ParseResult {\n// TODO(gvisor.dev/issue/170): ICMP packets don't have their TransportHeader\n// fields set yet, parse it here. See icmp/protocol.go:protocol.Parse for a\n// full explanation.\n- if transProtoNum == header.ICMPv4ProtocolNumber || transProtoNum == header.ICMPv6ProtocolNumber {\n+ if protocol == header.ICMPv4ProtocolNumber || protocol == header.ICMPv6ProtocolNumber {\nreturn ParsedOK\n}\n- pkt.TransportProtocolNumber = transProtoNum\n+ pkt.TransportProtocolNumber = protocol\n// Parse the transport header if present.\n- state, ok := s.transportProtocols[transProtoNum]\n+ state, ok := s.transportProtocols[protocol]\nif !ok {\nreturn UnknownTransportProtocol\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -119,6 +119,10 @@ func (*fakeNetworkEndpoint) DefaultTTL() uint8 {\n}\nfunc (f *fakeNetworkEndpoint) HandlePacket(pkt *stack.PacketBuffer) {\n+ if _, _, ok := f.proto.Parse(pkt); !ok {\n+ return\n+ }\n+\n// Increment the received packet count in the protocol descriptor.\nnetHdr := pkt.NetworkHeader().View()\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor locally delivered packets Make it clear that failing to parse a looped back is not a packet sending error but a malformed received packet error. FindNetworkEndpoint returns nil when no network endpoint is found instead of an error. PiperOrigin-RevId: 355954946
260,003
05.02.2021 17:25:35
28,800
120c8e34687129c919ae45263c14b239a0a5d343
Replace TaskFromContext(ctx).Kernel() with KernelFromContext(ctx) Panic seen at some code path like control.ExecAsync where ctx does not have a Task. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "new_path": "pkg/sentry/socket/hostinet/socket_vfs2.go", "diff": "@@ -80,8 +80,7 @@ func newVFS2Socket(t *kernel.Task, family int, stype linux.SockType, protocol in\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (s *socketVFS2) Release(ctx context.Context) {\n- t := kernel.TaskFromContext(ctx)\n- t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ kernel.KernelFromContext(ctx).DeleteSocketVFS2(&s.vfsfd)\ns.socketOpsCommon.Release(ctx)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go", "diff": "@@ -79,8 +79,7 @@ func NewVFS2(t *kernel.Task, family int, skType linux.SockType, protocol int, qu\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (s *SocketVFS2) Release(ctx context.Context) {\n- t := kernel.TaskFromContext(ctx)\n- t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ kernel.KernelFromContext(ctx).DeleteSocketVFS2(&s.vfsfd)\ns.socketOpsCommon.Release(ctx)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix_vfs2.go", "new_path": "pkg/sentry/socket/unix/unix_vfs2.go", "diff": "@@ -95,8 +95,7 @@ func NewFileDescription(ep transport.Endpoint, stype linux.SockType, flags uint3\n// DecRef implements RefCounter.DecRef.\nfunc (s *SocketVFS2) DecRef(ctx context.Context) {\ns.socketVFS2Refs.DecRef(func() {\n- t := kernel.TaskFromContext(ctx)\n- t.Kernel().DeleteSocketVFS2(&s.vfsfd)\n+ kernel.KernelFromContext(ctx).DeleteSocketVFS2(&s.vfsfd)\ns.ep.Close(ctx)\nif s.abstractNamespace != nil {\ns.abstractNamespace.Remove(s.abstractName, s)\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -777,6 +777,28 @@ func TestExec(t *testing.T) {\n}\n})\n}\n+\n+ // Test for exec failure with an non-existent file.\n+ t.Run(\"nonexist\", func(t *testing.T) {\n+ // b/179114837 found by Syzkaller that causes nil pointer panic when\n+ // trying to dec-ref an unix socket FD.\n+ fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ defer syscall.Close(fds[0])\n+\n+ _, err = cont.executeSync(&control.ExecArgs{\n+ Argv: []string{\"/nonexist\"},\n+ FilePayload: urpc.FilePayload{\n+ Files: []*os.File{os.NewFile(uintptr(fds[1]), \"sock\")},\n+ },\n+ })\n+ want := \"failed to load /nonexist\"\n+ if err == nil || !strings.Contains(err.Error(), want) {\n+ t.Errorf(\"executeSync: want err containing %q; got err = %q\", want, err)\n+ }\n+ })\n})\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Replace TaskFromContext(ctx).Kernel() with KernelFromContext(ctx) Panic seen at some code path like control.ExecAsync where ctx does not have a Task. Reported-by: [email protected] PiperOrigin-RevId: 355960596
260,004
06.02.2021 09:47:26
28,800
9530f624e971183a0e72fe5123f542e0a4e1b329
Unexpose NIC The NIC structure is not to be used outside of the stack package directly.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/linkaddrcache.go", "new_path": "pkg/tcpip/stack/linkaddrcache.go", "diff": "@@ -30,7 +30,7 @@ const linkAddrCacheSize = 512 // max cache entries\n//\n// This struct is safe for concurrent use.\ntype linkAddrCache struct {\n- nic *NIC\n+ nic *nic\nlinkRes LinkAddressResolver\n@@ -280,7 +280,7 @@ func (c *linkAddrCache) checkLinkRequest(now time.Time, k tcpip.Address, attempt\nreturn true\n}\n-func (c *linkAddrCache) init(nic *NIC, ageLimit, resolutionTimeout time.Duration, resolutionAttempts int, linkRes LinkAddressResolver) {\n+func (c *linkAddrCache) init(nic *nic, ageLimit, resolutionTimeout time.Duration, resolutionAttempts int, linkRes LinkAddressResolver) {\n*c = linkAddrCache{\nnic: nic,\nlinkRes: linkRes,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/linkaddrcache_test.go", "new_path": "pkg/tcpip/stack/linkaddrcache_test.go", "diff": "@@ -93,8 +93,8 @@ func getBlocking(c *linkAddrCache, addr tcpip.Address) (tcpip.LinkAddress, tcpip\n}\n}\n-func newEmptyNIC() *NIC {\n- n := &NIC{}\n+func newEmptyNIC() *nic {\n+ n := &nic{}\nn.linkResQueue.init(n)\nreturn n\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -43,7 +43,7 @@ type NeighborStats struct {\n// Their state is always Static. The amount of static entries stored in the\n// cache is unbounded.\ntype neighborCache struct {\n- nic *NIC\n+ nic *nic\nstate *NUDState\nlinkRes LinkAddressResolver\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache_test.go", "new_path": "pkg/tcpip/stack/neighbor_cache_test.go", "diff": "@@ -85,7 +85,7 @@ func newTestNeighborResolver(nudDisp NUDDispatcher, config NUDConfigurations, cl\ndelay: typicalLatency,\n}\nlinkRes.neigh = &neighborCache{\n- nic: &NIC{\n+ nic: &nic{\nstack: &Stack{\nclock: clock,\nnudDisp: nudDisp,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry_test.go", "new_path": "pkg/tcpip/stack/neighbor_entry_test.go", "diff": "@@ -220,7 +220,7 @@ func (r *entryTestLinkResolver) LinkAddressProtocol() tcpip.NetworkProtocolNumbe\nfunc entryTestSetup(c NUDConfigurations) (*neighborEntry, *testNUDDispatcher, *entryTestLinkResolver, *faketime.ManualClock) {\nclock := faketime.NewManualClock()\ndisp := testNUDDispatcher{}\n- nic := NIC{\n+ nic := nic{\nLinkEndpoint: nil, // entryTestLinkResolver doesn't use a LinkEndpoint\nid: entryTestNICID,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -39,7 +39,7 @@ type neighborTable interface {\nsetNUDConfig(NUDConfigurations) tcpip.Error\n}\n-var _ NetworkInterface = (*NIC)(nil)\n+var _ NetworkInterface = (*nic)(nil)\ntype linkResolver struct {\nresolver LinkAddressResolver\n@@ -55,9 +55,9 @@ func (l *linkResolver) confirmReachable(addr tcpip.Address) {\nl.neighborTable.handleUpperLevelConfirmation(addr)\n}\n-// NIC represents a \"network interface card\" to which the networking stack is\n+// nic represents a \"network interface card\" to which the networking stack is\n// attached.\n-type NIC struct {\n+type nic struct {\nLinkEndpoint\nstack *Stack\n@@ -147,7 +147,7 @@ func (p *packetEndpointList) forEach(fn func(PacketEndpoint)) {\n}\n// newNIC returns a new NIC using the default NDP configurations from stack.\n-func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICContext) *NIC {\n+func 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// example, make sure that the link address it provides is a valid\n// unicast ethernet address.\n@@ -156,7 +156,7 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\n// observe an MTU of at least 1280 bytes. Ensure that this requirement\n// of IPv6 is supported on this endpoint's LinkEndpoint.\n- nic := &NIC{\n+ nic := &nic{\nLinkEndpoint: ep,\nstack: stack,\n@@ -212,19 +212,19 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\nreturn nic\n}\n-func (n *NIC) getNetworkEndpoint(proto tcpip.NetworkProtocolNumber) NetworkEndpoint {\n+func (n *nic) getNetworkEndpoint(proto tcpip.NetworkProtocolNumber) NetworkEndpoint {\nreturn n.networkEndpoints[proto]\n}\n// Enabled implements NetworkInterface.\n-func (n *NIC) Enabled() bool {\n+func (n *nic) Enabled() bool {\nreturn atomic.LoadUint32(&n.enabled) == 1\n}\n// setEnabled sets the enabled status for the NIC.\n//\n// Returns true if the enabled status was updated.\n-func (n *NIC) setEnabled(v bool) bool {\n+func (n *nic) setEnabled(v bool) bool {\nif v {\nreturn atomic.SwapUint32(&n.enabled, 1) == 0\n}\n@@ -234,7 +234,7 @@ func (n *NIC) setEnabled(v bool) bool {\n// disable disables n.\n//\n// It undoes the work done by enable.\n-func (n *NIC) disable() {\n+func (n *nic) disable() {\nn.mu.Lock()\nn.disableLocked()\nn.mu.Unlock()\n@@ -245,7 +245,7 @@ func (n *NIC) disable() {\n// It undoes the work done by enable.\n//\n// n MUST be locked.\n-func (n *NIC) disableLocked() {\n+func (n *nic) disableLocked() {\nif !n.Enabled() {\nreturn\n}\n@@ -283,7 +283,7 @@ func (n *NIC) disableLocked() {\n// address (ff02::1), start DAD for permanent addresses, and start soliciting\n// routers if the stack is not operating as a router. If the stack is also\n// configured to auto-generate a link-local address, one will be generated.\n-func (n *NIC) enable() tcpip.Error {\n+func (n *nic) enable() tcpip.Error {\nn.mu.Lock()\ndefer n.mu.Unlock()\n@@ -303,7 +303,7 @@ func (n *NIC) enable() tcpip.Error {\n// remove detaches NIC from the link endpoint and releases network endpoint\n// resources. This guarantees no packets between this NIC and the network\n// stack.\n-func (n *NIC) remove() tcpip.Error {\n+func (n *nic) remove() tcpip.Error {\nn.mu.Lock()\ndefer n.mu.Unlock()\n@@ -319,14 +319,14 @@ func (n *NIC) remove() tcpip.Error {\n}\n// setPromiscuousMode enables or disables promiscuous mode.\n-func (n *NIC) setPromiscuousMode(enable bool) {\n+func (n *nic) setPromiscuousMode(enable bool) {\nn.mu.Lock()\nn.mu.promiscuous = enable\nn.mu.Unlock()\n}\n// Promiscuous implements NetworkInterface.\n-func (n *NIC) Promiscuous() bool {\n+func (n *nic) Promiscuous() bool {\nn.mu.RLock()\nrv := n.mu.promiscuous\nn.mu.RUnlock()\n@@ -334,17 +334,17 @@ func (n *NIC) Promiscuous() bool {\n}\n// IsLoopback implements NetworkInterface.\n-func (n *NIC) IsLoopback() bool {\n+func (n *nic) IsLoopback() bool {\nreturn n.LinkEndpoint.Capabilities()&CapabilityLoopback != 0\n}\n// WritePacket implements NetworkLinkEndpoint.\n-func (n *NIC) WritePacket(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\n+func (n *nic) WritePacket(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\n_, err := n.enqueuePacketBuffer(r, gso, protocol, pkt)\nreturn err\n}\n-func (n *NIC) writePacketBuffer(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\n+func (n *nic) writePacketBuffer(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\nswitch pkt := pkt.(type) {\ncase *PacketBuffer:\nif err := n.writePacket(r, gso, protocol, pkt); err != nil {\n@@ -358,7 +358,7 @@ func (n *NIC) writePacketBuffer(r RouteInfo, gso *GSO, protocol tcpip.NetworkPro\n}\n}\n-func (n *NIC) enqueuePacketBuffer(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\n+func (n *nic) enqueuePacketBuffer(r *Route, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt pendingPacketBuffer) (int, tcpip.Error) {\nrouteInfo, _, err := r.resolvedFields(nil)\nswitch err.(type) {\ncase nil:\n@@ -388,14 +388,14 @@ func (n *NIC) enqueuePacketBuffer(r *Route, gso *GSO, protocol tcpip.NetworkProt\n}\n// WritePacketToRemote implements NetworkInterface.\n-func (n *NIC) WritePacketToRemote(remoteLinkAddr tcpip.LinkAddress, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\n+func (n *nic) WritePacketToRemote(remoteLinkAddr tcpip.LinkAddress, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\nvar r RouteInfo\nr.NetProto = protocol\nr.RemoteLinkAddress = remoteLinkAddr\nreturn n.writePacket(r, gso, protocol, pkt)\n}\n-func (n *NIC) writePacket(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\n+func (n *nic) writePacket(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) tcpip.Error {\n// WritePacket takes ownership of pkt, calculate numBytes first.\nnumBytes := pkt.Size()\n@@ -412,11 +412,11 @@ func (n *NIC) writePacket(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolN\n}\n// WritePackets implements NetworkLinkEndpoint.\n-func (n *NIC) WritePackets(r *Route, gso *GSO, pkts PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\n+func (n *nic) WritePackets(r *Route, gso *GSO, pkts PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\nreturn n.enqueuePacketBuffer(r, gso, protocol, &pkts)\n}\n-func (n *NIC) writePackets(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkts PacketBufferList) (int, tcpip.Error) {\n+func (n *nic) writePackets(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocolNumber, pkts PacketBufferList) (int, tcpip.Error) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\npkt.EgressRoute = r\npkt.GSOOptions = gso\n@@ -435,14 +435,14 @@ func (n *NIC) writePackets(r RouteInfo, gso *GSO, protocol tcpip.NetworkProtocol\n}\n// setSpoofing enables or disables address spoofing.\n-func (n *NIC) setSpoofing(enable bool) {\n+func (n *nic) setSpoofing(enable bool) {\nn.mu.Lock()\nn.mu.spoofing = enable\nn.mu.Unlock()\n}\n// Spoofing implements NetworkInterface.\n-func (n *NIC) Spoofing() bool {\n+func (n *nic) Spoofing() bool {\nn.mu.RLock()\ndefer n.mu.RUnlock()\nreturn n.mu.spoofing\n@@ -450,7 +450,7 @@ func (n *NIC) Spoofing() bool {\n// primaryAddress returns an address that can be used to communicate with\n// remoteAddr.\n-func (n *NIC) primaryEndpoint(protocol tcpip.NetworkProtocolNumber, remoteAddr tcpip.Address) AssignableAddressEndpoint {\n+func (n *nic) primaryEndpoint(protocol tcpip.NetworkProtocolNumber, remoteAddr tcpip.Address) AssignableAddressEndpoint {\nep, ok := n.networkEndpoints[protocol]\nif !ok {\nreturn nil\n@@ -480,11 +480,11 @@ const (\npromiscuous\n)\n-func (n *NIC) getAddress(protocol tcpip.NetworkProtocolNumber, dst tcpip.Address) AssignableAddressEndpoint {\n+func (n *nic) getAddress(protocol tcpip.NetworkProtocolNumber, dst tcpip.Address) AssignableAddressEndpoint {\nreturn n.getAddressOrCreateTemp(protocol, dst, CanBePrimaryEndpoint, promiscuous)\n}\n-func (n *NIC) hasAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+func (n *nic) hasAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\nep := n.getAddressOrCreateTempInner(protocol, addr, false, NeverPrimaryEndpoint)\nif ep != nil {\nep.DecRef()\n@@ -495,7 +495,7 @@ func (n *NIC) hasAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Addres\n}\n// findEndpoint finds the endpoint, if any, with the given address.\n-func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) AssignableAddressEndpoint {\n+func (n *nic) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior) AssignableAddressEndpoint {\nreturn n.getAddressOrCreateTemp(protocol, address, peb, spoofing)\n}\n@@ -508,7 +508,7 @@ func (n *NIC) findEndpoint(protocol tcpip.NetworkProtocolNumber, address tcpip.A\n//\n// If the address is the IPv4 broadcast address for an endpoint's network, that\n// endpoint will be returned.\n-func (n *NIC) getAddressOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior, tempRef getAddressBehaviour) AssignableAddressEndpoint {\n+func (n *nic) getAddressOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, peb PrimaryEndpointBehavior, tempRef getAddressBehaviour) AssignableAddressEndpoint {\nn.mu.RLock()\nvar spoofingOrPromiscuous bool\nswitch tempRef {\n@@ -523,7 +523,7 @@ func (n *NIC) getAddressOrCreateTemp(protocol tcpip.NetworkProtocolNumber, addre\n// getAddressOrCreateTempInner is like getAddressEpOrCreateTemp except a boolean\n// is passed to indicate whether or not we should generate temporary endpoints.\n-func (n *NIC) getAddressOrCreateTempInner(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, createTemp bool, peb PrimaryEndpointBehavior) AssignableAddressEndpoint {\n+func (n *nic) getAddressOrCreateTempInner(protocol tcpip.NetworkProtocolNumber, address tcpip.Address, createTemp bool, peb PrimaryEndpointBehavior) AssignableAddressEndpoint {\nep, ok := n.networkEndpoints[protocol]\nif !ok {\nreturn nil\n@@ -539,7 +539,7 @@ func (n *NIC) getAddressOrCreateTempInner(protocol tcpip.NetworkProtocolNumber,\n// addAddress adds a new address to n, so that it starts accepting packets\n// targeted at the given address (and network protocol).\n-func (n *NIC) addAddress(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) tcpip.Error {\n+func (n *nic) addAddress(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) tcpip.Error {\nep, ok := n.networkEndpoints[protocolAddress.Protocol]\nif !ok {\nreturn &tcpip.ErrUnknownProtocol{}\n@@ -560,7 +560,7 @@ func (n *NIC) addAddress(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpo\n// allPermanentAddresses returns all permanent addresses associated with\n// this NIC.\n-func (n *NIC) allPermanentAddresses() []tcpip.ProtocolAddress {\n+func (n *nic) allPermanentAddresses() []tcpip.ProtocolAddress {\nvar addrs []tcpip.ProtocolAddress\nfor p, ep := range n.networkEndpoints {\naddressableEndpoint, ok := ep.(AddressableEndpoint)\n@@ -576,7 +576,7 @@ func (n *NIC) allPermanentAddresses() []tcpip.ProtocolAddress {\n}\n// primaryAddresses returns the primary addresses associated with this NIC.\n-func (n *NIC) primaryAddresses() []tcpip.ProtocolAddress {\n+func (n *nic) primaryAddresses() []tcpip.ProtocolAddress {\nvar addrs []tcpip.ProtocolAddress\nfor p, ep := range n.networkEndpoints {\naddressableEndpoint, ok := ep.(AddressableEndpoint)\n@@ -596,7 +596,7 @@ func (n *NIC) primaryAddresses() []tcpip.ProtocolAddress {\n// primaryAddress will return the first non-deprecated address if such an\n// address exists. If no non-deprecated address exists, the first deprecated\n// address will be returned.\n-func (n *NIC) primaryAddress(proto tcpip.NetworkProtocolNumber) tcpip.AddressWithPrefix {\n+func (n *nic) primaryAddress(proto tcpip.NetworkProtocolNumber) tcpip.AddressWithPrefix {\nep, ok := n.networkEndpoints[proto]\nif !ok {\nreturn tcpip.AddressWithPrefix{}\n@@ -611,7 +611,7 @@ func (n *NIC) primaryAddress(proto tcpip.NetworkProtocolNumber) tcpip.AddressWit\n}\n// removeAddress removes an address from n.\n-func (n *NIC) removeAddress(addr tcpip.Address) tcpip.Error {\n+func (n *nic) removeAddress(addr tcpip.Address) tcpip.Error {\nfor _, ep := range n.networkEndpoints {\naddressableEndpoint, ok := ep.(AddressableEndpoint)\nif !ok {\n@@ -629,7 +629,7 @@ func (n *NIC) removeAddress(addr tcpip.Address) tcpip.Error {\nreturn &tcpip.ErrBadLocalAddress{}\n}\n-func (n *NIC) getLinkAddress(addr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, onResolve func(LinkResolutionResult)) tcpip.Error {\n+func (n *nic) getLinkAddress(addr, localAddr tcpip.Address, protocol tcpip.NetworkProtocolNumber, onResolve func(LinkResolutionResult)) tcpip.Error {\nlinkRes, ok := n.linkAddrResolvers[protocol]\nif !ok {\nreturn &tcpip.ErrNotSupported{}\n@@ -644,7 +644,7 @@ func (n *NIC) getLinkAddress(addr, localAddr tcpip.Address, protocol tcpip.Netwo\nreturn err\n}\n-func (n *NIC) neighbors(protocol tcpip.NetworkProtocolNumber) ([]NeighborEntry, tcpip.Error) {\n+func (n *nic) neighbors(protocol tcpip.NetworkProtocolNumber) ([]NeighborEntry, tcpip.Error) {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nreturn linkRes.neighborTable.neighbors()\n}\n@@ -652,7 +652,7 @@ func (n *NIC) neighbors(protocol tcpip.NetworkProtocolNumber) ([]NeighborEntry,\nreturn nil, &tcpip.ErrNotSupported{}\n}\n-func (n *NIC) addStaticNeighbor(addr tcpip.Address, protocol tcpip.NetworkProtocolNumber, linkAddress tcpip.LinkAddress) tcpip.Error {\n+func (n *nic) addStaticNeighbor(addr tcpip.Address, protocol tcpip.NetworkProtocolNumber, linkAddress tcpip.LinkAddress) tcpip.Error {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nlinkRes.neighborTable.addStaticEntry(addr, linkAddress)\nreturn nil\n@@ -661,7 +661,7 @@ func (n *NIC) addStaticNeighbor(addr tcpip.Address, protocol tcpip.NetworkProtoc\nreturn &tcpip.ErrNotSupported{}\n}\n-func (n *NIC) removeNeighbor(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\n+func (n *nic) removeNeighbor(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nreturn linkRes.neighborTable.remove(addr)\n}\n@@ -669,7 +669,7 @@ func (n *NIC) removeNeighbor(protocol tcpip.NetworkProtocolNumber, addr tcpip.Ad\nreturn &tcpip.ErrNotSupported{}\n}\n-func (n *NIC) clearNeighbors(protocol tcpip.NetworkProtocolNumber) tcpip.Error {\n+func (n *nic) clearNeighbors(protocol tcpip.NetworkProtocolNumber) tcpip.Error {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nreturn linkRes.neighborTable.removeAll()\n}\n@@ -679,7 +679,7 @@ func (n *NIC) clearNeighbors(protocol tcpip.NetworkProtocolNumber) tcpip.Error {\n// joinGroup adds a new endpoint for the given multicast address, if none\n// exists yet. Otherwise it just increments its count.\n-func (n *NIC) joinGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\n+func (n *nic) joinGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\n// TODO(b/143102137): When implementing MLD, make sure MLD packets are\n// not sent unless a valid link-local address is available for use on n\n// as an MLD packet's source address must be a link-local address as\n@@ -700,7 +700,7 @@ func (n *NIC) joinGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address\n// leaveGroup decrements the count for the given multicast address, and when it\n// reaches zero removes the endpoint for this address.\n-func (n *NIC) leaveGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\n+func (n *nic) leaveGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) tcpip.Error {\nep, ok := n.networkEndpoints[protocol]\nif !ok {\nreturn &tcpip.ErrNotSupported{}\n@@ -715,7 +715,7 @@ func (n *NIC) leaveGroup(protocol tcpip.NetworkProtocolNumber, addr tcpip.Addres\n}\n// isInGroup returns true if n has joined the multicast group addr.\n-func (n *NIC) isInGroup(addr tcpip.Address) bool {\n+func (n *nic) isInGroup(addr tcpip.Address) bool {\nfor _, ep := range n.networkEndpoints {\ngep, ok := ep.(GroupAddressableEndpoint)\nif !ok {\n@@ -736,7 +736,7 @@ func (n *NIC) isInGroup(addr tcpip.Address) bool {\n// Note that the ownership of the slice backing vv is retained by the caller.\n// This rule applies only to the slice itself, not to the items of the slice;\n// the ownership of the items is not retained by the caller.\n-func (n *NIC) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) {\n+func (n *nic) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) {\nn.mu.RLock()\nenabled := n.Enabled()\n// If the NIC is not yet enabled, don't receive any packets.\n@@ -788,7 +788,7 @@ func (n *NIC) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\n}\n// DeliverOutboundPacket implements NetworkDispatcher.DeliverOutboundPacket.\n-func (n *NIC) DeliverOutboundPacket(remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) {\n+func (n *nic) DeliverOutboundPacket(remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *PacketBuffer) {\nn.mu.RLock()\n// We do not deliver to protocol specific packet endpoints as on Linux\n// only ETH_P_ALL endpoints get outbound packets.\n@@ -808,7 +808,7 @@ func (n *NIC) DeliverOutboundPacket(remote, local tcpip.LinkAddress, protocol tc\n// DeliverTransportPacket delivers the packets to the appropriate transport\n// protocol endpoint.\n-func (n *NIC) DeliverTransportPacket(protocol tcpip.TransportProtocolNumber, pkt *PacketBuffer) TransportPacketDisposition {\n+func (n *nic) DeliverTransportPacket(protocol tcpip.TransportProtocolNumber, pkt *PacketBuffer) TransportPacketDisposition {\nstate, ok := n.stack.transportProtocols[protocol]\nif !ok {\nn.stack.stats.UnknownProtocolRcvdPackets.Increment()\n@@ -889,7 +889,7 @@ func (n *NIC) DeliverTransportPacket(protocol tcpip.TransportProtocolNumber, pkt\n}\n// DeliverTransportError implements TransportDispatcher.\n-func (n *NIC) DeliverTransportError(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, transErr TransportError, pkt *PacketBuffer) {\n+func (n *nic) DeliverTransportError(local, remote tcpip.Address, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, transErr TransportError, pkt *PacketBuffer) {\nstate, ok := n.stack.transportProtocols[trans]\nif !ok {\nreturn\n@@ -917,17 +917,17 @@ func (n *NIC) DeliverTransportError(local, remote tcpip.Address, net tcpip.Netwo\n}\n// ID implements NetworkInterface.\n-func (n *NIC) ID() tcpip.NICID {\n+func (n *nic) ID() tcpip.NICID {\nreturn n.id\n}\n// Name implements NetworkInterface.\n-func (n *NIC) Name() string {\n+func (n *nic) Name() string {\nreturn n.name\n}\n// nudConfigs gets the NUD configurations for n.\n-func (n *NIC) nudConfigs(protocol tcpip.NetworkProtocolNumber) (NUDConfigurations, tcpip.Error) {\n+func (n *nic) nudConfigs(protocol tcpip.NetworkProtocolNumber) (NUDConfigurations, tcpip.Error) {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nreturn linkRes.neighborTable.nudConfig()\n}\n@@ -939,7 +939,7 @@ func (n *NIC) nudConfigs(protocol tcpip.NetworkProtocolNumber) (NUDConfiguration\n//\n// Note, if c contains invalid NUD configuration values, it will be fixed to\n// use default values for the erroneous values.\n-func (n *NIC) setNUDConfigs(protocol tcpip.NetworkProtocolNumber, c NUDConfigurations) tcpip.Error {\n+func (n *nic) setNUDConfigs(protocol tcpip.NetworkProtocolNumber, c NUDConfigurations) tcpip.Error {\nif linkRes, ok := n.linkAddrResolvers[protocol]; ok {\nc.resetInvalidFields()\nreturn linkRes.neighborTable.setNUDConfig(c)\n@@ -948,7 +948,7 @@ func (n *NIC) setNUDConfigs(protocol tcpip.NetworkProtocolNumber, c NUDConfigura\nreturn &tcpip.ErrNotSupported{}\n}\n-func (n *NIC) registerPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) tcpip.Error {\n+func (n *nic) registerPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) tcpip.Error {\nn.mu.Lock()\ndefer n.mu.Unlock()\n@@ -961,7 +961,7 @@ func (n *NIC) registerPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep Pa\nreturn nil\n}\n-func (n *NIC) unregisterPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) {\n+func (n *nic) unregisterPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep PacketEndpoint) {\nn.mu.Lock()\ndefer n.mu.Unlock()\n@@ -975,7 +975,7 @@ func (n *NIC) unregisterPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep\n// isValidForOutgoing returns true if the endpoint can be used to send out a\n// packet. It requires the endpoint to not be marked expired (i.e., its address\n// has been removed) unless the NIC is in spoofing mode, or temporary.\n-func (n *NIC) isValidForOutgoing(ep AssignableAddressEndpoint) bool {\n+func (n *nic) isValidForOutgoing(ep AssignableAddressEndpoint) bool {\nn.mu.RLock()\nspoofing := n.mu.spoofing\nn.mu.RUnlock()\n@@ -983,7 +983,7 @@ func (n *NIC) isValidForOutgoing(ep AssignableAddressEndpoint) bool {\n}\n// HandleNeighborProbe implements NetworkInterface.\n-func (n *NIC) HandleNeighborProbe(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, linkAddr tcpip.LinkAddress) tcpip.Error {\n+func (n *nic) HandleNeighborProbe(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, linkAddr tcpip.LinkAddress) tcpip.Error {\nif l, ok := n.linkAddrResolvers[protocol]; ok {\nl.neighborTable.handleProbe(addr, linkAddr)\nreturn nil\n@@ -993,7 +993,7 @@ func (n *NIC) HandleNeighborProbe(protocol tcpip.NetworkProtocolNumber, addr tcp\n}\n// HandleNeighborConfirmation implements NetworkInterface.\n-func (n *NIC) HandleNeighborConfirmation(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags) tcpip.Error {\n+func (n *nic) HandleNeighborConfirmation(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address, linkAddr tcpip.LinkAddress, flags ReachabilityConfirmationFlags) tcpip.Error {\nif l, ok := n.linkAddrResolvers[protocol]; ok {\nl.neighborTable.handleConfirmation(addr, linkAddr, flags)\nreturn nil\n@@ -1003,7 +1003,7 @@ func (n *NIC) HandleNeighborConfirmation(protocol tcpip.NetworkProtocolNumber, a\n}\n// CheckLocalAddress implements NetworkInterface.\n-func (n *NIC) CheckLocalAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+func (n *nic) CheckLocalAddress(protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\nif n.Spoofing() {\nreturn true\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic_test.go", "new_path": "pkg/tcpip/stack/nic_test.go", "diff": "@@ -170,7 +170,7 @@ func (*testIPv6Protocol) Parse(*PacketBuffer) (tcpip.TransportProtocolNumber, bo\nfunc TestDisabledRxStatsWhenNICDisabled(t *testing.T) {\n// When the NIC is disabled, the only field that matters is the stats field.\n// This test is limited to stats counter checks.\n- nic := NIC{\n+ nic := nic{\nstats: makeNICStats(),\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/pending_packets.go", "new_path": "pkg/tcpip/stack/pending_packets.go", "diff": "@@ -55,7 +55,7 @@ type pendingPacket struct {\n//\n// Once link resolution completes successfully, the packets will be written.\ntype packetsPendingLinkResolution struct {\n- nic *NIC\n+ nic *nic\nmu struct {\nsync.Mutex\n@@ -82,7 +82,7 @@ func (f *packetsPendingLinkResolution) incrementOutgoingPacketErrors(proto tcpip\n}\n}\n-func (f *packetsPendingLinkResolution) init(nic *NIC) {\n+func (f *packetsPendingLinkResolution) init(nic *nic) {\nf.mu.Lock()\ndefer f.mu.Unlock()\nf.nic = nic\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -35,7 +35,7 @@ type Route struct {\n// localAddressNIC is the interface the address is associated with.\n// TODO(gvisor.dev/issue/4548): Remove this field once we can query the\n// address's assigned status without the NIC.\n- localAddressNIC *NIC\n+ localAddressNIC *nic\nmu struct {\nsync.RWMutex\n@@ -49,7 +49,7 @@ type Route struct {\n}\n// outgoingNIC is the interface this route uses to write packets.\n- outgoingNIC *NIC\n+ outgoingNIC *nic\n// linkRes is set if link address resolution is enabled for this protocol on\n// the route's NIC.\n@@ -108,7 +108,7 @@ func (r *Route) fieldsLocked() RouteInfo {\n// ownership of the provided local address.\n//\n// Returns an empty route if validation fails.\n-func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndpoint AssignableAddressEndpoint, localAddressNIC, outgoingNIC *NIC, gateway, localAddr, remoteAddr tcpip.Address, handleLocal, multicastLoop bool) *Route {\n+func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndpoint AssignableAddressEndpoint, localAddressNIC, outgoingNIC *nic, gateway, localAddr, remoteAddr tcpip.Address, handleLocal, multicastLoop bool) *Route {\nif len(localAddr) == 0 {\nlocalAddr = addressEndpoint.AddressWithPrefix().Address\n}\n@@ -140,7 +140,7 @@ func constructAndValidateRoute(netProto tcpip.NetworkProtocolNumber, addressEndp\n// makeRoute initializes a new route. It takes ownership of the provided\n// AssignableAddressEndpoint.\n-func makeRoute(netProto tcpip.NetworkProtocolNumber, gateway, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *NIC, localAddressEndpoint AssignableAddressEndpoint, handleLocal, multicastLoop bool) *Route {\n+func makeRoute(netProto tcpip.NetworkProtocolNumber, gateway, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *nic, localAddressEndpoint AssignableAddressEndpoint, handleLocal, multicastLoop bool) *Route {\nif localAddressNIC.stack != outgoingNIC.stack {\npanic(fmt.Sprintf(\"cannot create a route with NICs from different stacks\"))\n}\n@@ -206,7 +206,7 @@ func makeRoute(netProto tcpip.NetworkProtocolNumber, gateway, localAddr, remoteA\nreturn r\n}\n-func makeRouteInner(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *NIC, localAddressEndpoint AssignableAddressEndpoint, loop PacketLooping) *Route {\n+func makeRouteInner(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *nic, localAddressEndpoint AssignableAddressEndpoint, loop PacketLooping) *Route {\nr := &Route{\nrouteInfo: routeInfo{\nNetProto: netProto,\n@@ -230,7 +230,7 @@ func makeRouteInner(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr\n// provided AssignableAddressEndpoint.\n//\n// A local route is a route to a destination that is local to the stack.\n-func makeLocalRoute(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *NIC, localAddressEndpoint AssignableAddressEndpoint) *Route {\n+func makeLocalRoute(netProto tcpip.NetworkProtocolNumber, localAddr, remoteAddr tcpip.Address, outgoingNIC, localAddressNIC *nic, localAddressEndpoint AssignableAddressEndpoint) *Route {\nloop := PacketLoop\n// TODO(gvisor.dev/issue/4689): Loopback interface loops back packets at the\n// link endpoint level. We can remove this check once loopback interfaces\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -395,7 +395,7 @@ type Stack struct {\n}\nmu sync.RWMutex\n- nics map[tcpip.NICID]*NIC\n+ nics map[tcpip.NICID]*nic\n// cleanupEndpointsMu protects cleanupEndpoints.\ncleanupEndpointsMu sync.Mutex\n@@ -656,7 +656,7 @@ func New(opts Options) *Stack {\ns := &Stack{\ntransportProtocols: make(map[tcpip.TransportProtocolNumber]*transportProtocolState),\nnetworkProtocols: make(map[tcpip.NetworkProtocolNumber]NetworkProtocol),\n- nics: make(map[tcpip.NICID]*NIC),\n+ nics: make(map[tcpip.NICID]*nic),\ncleanupEndpoints: make(map[TransportEndpoint]struct{}),\nPortManager: ports.NewPortManager(),\nclock: clock,\n@@ -1233,7 +1233,7 @@ func (s *Stack) GetMainNICAddress(id tcpip.NICID, protocol tcpip.NetworkProtocol\nreturn nic.primaryAddress(protocol), true\n}\n-func (s *Stack) getAddressEP(nic *NIC, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber) AssignableAddressEndpoint {\n+func (s *Stack) getAddressEP(nic *nic, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber) AssignableAddressEndpoint {\nif len(localAddr) == 0 {\nreturn nic.primaryEndpoint(netProto, remoteAddr)\n}\n@@ -1244,13 +1244,13 @@ func (s *Stack) getAddressEP(nic *NIC, localAddr, remoteAddr tcpip.Address, netP\n// from the specified NIC.\n//\n// Precondition: s.mu must be read locked.\n-func (s *Stack) findLocalRouteFromNICRLocked(localAddressNIC *NIC, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber) *Route {\n+func (s *Stack) findLocalRouteFromNICRLocked(localAddressNIC *nic, localAddr, remoteAddr tcpip.Address, netProto tcpip.NetworkProtocolNumber) *Route {\nlocalAddressEndpoint := localAddressNIC.getAddressOrCreateTempInner(netProto, localAddr, false /* createTemp */, NeverPrimaryEndpoint)\nif localAddressEndpoint == nil {\nreturn nil\n}\n- var outgoingNIC *NIC\n+ var outgoingNIC *nic\n// Prefer a local route to the same interface as the local address.\nif localAddressNIC.hasAddress(netProto, remoteAddr) {\noutgoingNIC = localAddressNIC\n@@ -2148,7 +2148,7 @@ func (s *Stack) networkProtocolNumbers() []tcpip.NetworkProtocolNumber {\nreturn protos\n}\n-func isSubnetBroadcastOnNIC(nic *NIC, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\n+func isSubnetBroadcastOnNIC(nic *nic, protocol tcpip.NetworkProtocolNumber, addr tcpip.Address) bool {\naddressEndpoint := nic.getAddressOrCreateTempInner(protocol, addr, false /* createTemp */, NeverPrimaryEndpoint)\nif addressEndpoint == nil {\nreturn false\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer.go", "new_path": "pkg/tcpip/stack/transport_demuxer.go", "diff": "@@ -183,7 +183,7 @@ func (epsByNIC *endpointsByNIC) handlePacket(id TransportEndpointID, pkt *Packet\n}\n// handleError delivers an error to the transport endpoint identified by id.\n-func (epsByNIC *endpointsByNIC) handleError(n *NIC, id TransportEndpointID, transErr TransportError, pkt *PacketBuffer) {\n+func (epsByNIC *endpointsByNIC) handleError(n *nic, id TransportEndpointID, transErr TransportError, pkt *PacketBuffer) {\nepsByNIC.mu.RLock()\ndefer epsByNIC.mu.RUnlock()\n@@ -599,7 +599,7 @@ func (d *transportDemuxer) deliverRawPacket(protocol tcpip.TransportProtocolNumb\n// endpoint.\n//\n// Returns true if the error was delivered.\n-func (d *transportDemuxer) deliverError(n *NIC, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, transErr TransportError, pkt *PacketBuffer, id TransportEndpointID) bool {\n+func (d *transportDemuxer) deliverError(n *nic, net tcpip.NetworkProtocolNumber, trans tcpip.TransportProtocolNumber, transErr TransportError, pkt *PacketBuffer, id TransportEndpointID) bool {\neps, ok := d.protocol[protocolIDs{net, trans}]\nif !ok {\nreturn false\n" } ]
Go
Apache License 2.0
google/gvisor
Unexpose NIC The NIC structure is not to be used outside of the stack package directly. PiperOrigin-RevId: 356036737
260,004
06.02.2021 13:23:44
28,800
c5afaf2854679fbb7470f9a615d3c0fbb2af0999
Remove (*stack.Stack).FindNetworkEndpoint The network endpoints only look for other network endpoints of the same kind. Since the network protocols keeps track of all endpoints, go through the protocol to find an endpoint with an address instead of the stack.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -130,6 +130,20 @@ func (p *protocol) NewEndpoint(nic stack.NetworkInterface, dispatcher stack.Tran\nreturn e\n}\n+func (p *protocol) findEndpointWithAddress(addr tcpip.Address) *endpoint {\n+ p.mu.RLock()\n+ defer p.mu.RUnlock()\n+\n+ for _, e := range p.mu.eps {\n+ if addressEndpoint := e.AcquireAssignedAddress(addr, false /* allowTemp */, stack.NeverPrimaryEndpoint); addressEndpoint != nil {\n+ addressEndpoint.DecRef()\n+ return e\n+ }\n+ }\n+\n+ return nil\n+}\n+\nfunc (p *protocol) forgetEndpoint(nicID tcpip.NICID) {\np.mu.Lock()\ndefer p.mu.Unlock()\n@@ -347,10 +361,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\n// short circuits broadcasts before they are sent out to other hosts.\nif pkt.NatDone {\nnetHeader := header.IPv4(pkt.NetworkHeader().View())\n- if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n+ if ep := e.protocol.findEndpointWithAddress(netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n// can safely assume the checksum is valid.\n- ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\n+ ep.handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nreturn nil\n}\n}\n@@ -449,7 +463,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n// The NAT-ed packets may now be destined for us.\nlocallyDelivered := 0\nfor pkt := range natPkts {\n- ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, header.IPv4(pkt.NetworkHeader().View()).DestinationAddress())\n+ ep := e.protocol.findEndpointWithAddress(header.IPv4(pkt.NetworkHeader().View()).DestinationAddress())\nif ep == nil {\n// The NAT-ed packet is still destined for some remote node.\ncontinue\n@@ -459,7 +473,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\npkts.Remove(pkt)\n// Deliver the packet locally.\n- ep.(*endpoint).handleLocalPacket(pkt, true)\n+ ep.handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nlocallyDelivered++\n}\n@@ -550,8 +564,8 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) tcpip.Error {\ndstAddr := h.DestinationAddress()\n// Check if the destination is owned by the stack.\n- if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr); ep != nil {\n- ep.(*endpoint).handlePacket(pkt)\n+ if ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\n+ ep.handlePacket(pkt)\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -648,10 +648,10 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, params stack.Netw\n// short circuits broadcasts before they are sent out to other hosts.\nif pkt.NatDone {\nnetHeader := header.IPv6(pkt.NetworkHeader().View())\n- if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, netHeader.DestinationAddress()); ep != nil {\n+ if ep := e.protocol.findEndpointWithAddress(netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n// can safely assume the checksum is valid.\n- ep.(*endpoint).handleLocalPacket(pkt, true /* canSkipRXChecksum */)\n+ ep.handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nreturn nil\n}\n}\n@@ -750,7 +750,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\n// The NAT-ed packets may now be destined for us.\nlocallyDelivered := 0\nfor pkt := range natPkts {\n- ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, header.IPv6(pkt.NetworkHeader().View()).DestinationAddress())\n+ ep := e.protocol.findEndpointWithAddress(header.IPv6(pkt.NetworkHeader().View()).DestinationAddress())\nif ep == nil {\n// The NAT-ed packet is still destined for some remote node.\ncontinue\n@@ -760,7 +760,7 @@ func (e *endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts stack.Packe\npkts.Remove(pkt)\n// Deliver the packet locally.\n- ep.(*endpoint).handleLocalPacket(pkt, true)\n+ ep.handleLocalPacket(pkt, true /* canSkipRXChecksum */)\nlocallyDelivered++\n}\n@@ -829,8 +829,8 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) tcpip.Error {\n// Check if the destination is owned by the stack.\n- if ep := e.protocol.stack.FindNetworkEndpoint(ProtocolNumber, dstAddr); ep != nil {\n- ep.(*endpoint).handlePacket(pkt)\n+ if ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\n+ ep.handlePacket(pkt)\nreturn nil\n}\n@@ -1760,6 +1760,20 @@ func (p *protocol) NewEndpoint(nic stack.NetworkInterface, dispatcher stack.Tran\nreturn e\n}\n+func (p *protocol) findEndpointWithAddress(addr tcpip.Address) *endpoint {\n+ p.mu.RLock()\n+ defer p.mu.RUnlock()\n+\n+ for _, e := range p.mu.eps {\n+ if addressEndpoint := e.AcquireAssignedAddress(addr, false /* allowTemp */, stack.NeverPrimaryEndpoint); addressEndpoint != nil {\n+ addressEndpoint.DecRef()\n+ return e\n+ }\n+ }\n+\n+ return nil\n+}\n+\nfunc (p *protocol) forgetEndpoint(nicID tcpip.NICID) {\np.mu.Lock()\ndefer p.mu.Unlock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -2063,24 +2063,6 @@ func generateRandInt64() int64 {\nreturn v\n}\n-// FindNetworkEndpoint returns the network endpoint for the given address.\n-//\n-// Returns nil if the address is not associated with any network endpoint.\n-func (s *Stack) FindNetworkEndpoint(netProto tcpip.NetworkProtocolNumber, address tcpip.Address) NetworkEndpoint {\n- s.mu.RLock()\n- defer s.mu.RUnlock()\n-\n- for _, nic := range s.nics {\n- addressEndpoint := nic.getAddressOrCreateTempInner(netProto, address, false /* createTemp */, NeverPrimaryEndpoint)\n- if addressEndpoint == nil {\n- continue\n- }\n- addressEndpoint.DecRef()\n- return nic.getNetworkEndpoint(netProto)\n- }\n- return nil\n-}\n-\n// FindNICNameFromID returns the name of the NIC for the given NICID.\nfunc (s *Stack) FindNICNameFromID(id tcpip.NICID) string {\ns.mu.RLock()\n" } ]
Go
Apache License 2.0
google/gvisor
Remove (*stack.Stack).FindNetworkEndpoint The network endpoints only look for other network endpoints of the same kind. Since the network protocols keeps track of all endpoints, go through the protocol to find an endpoint with an address instead of the stack. PiperOrigin-RevId: 356051498
259,896
08.02.2021 12:08:11
28,800
fe63db2e96069140a3e02a0dc7b7e28af9b463db
RACK: Detect loss Detect packet loss using reorder window and re-transmit them after the reorder timer expires.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -1301,7 +1301,8 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\n// e.mu is expected to be hold upon entering this section.\nif e.snd != nil {\ne.snd.resendTimer.cleanup()\n- e.snd.rc.probeTimer.cleanup()\n+ e.snd.probeTimer.cleanup()\n+ e.snd.reorderTimer.cleanup()\n}\nif closeTimer != nil {\n@@ -1396,7 +1397,7 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\n},\n},\n{\n- w: &e.snd.rc.probeWaker,\n+ w: &e.snd.probeWaker,\nf: e.snd.probeTimerExpired,\n},\n{\n@@ -1475,6 +1476,10 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\nreturn nil\n},\n},\n+ {\n+ w: &e.snd.reorderWaker,\n+ f: e.snd.rc.reorderTimerExpired,\n+ },\n}\n// Initialize the sleeper based on the wakers in funcs.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack.go", "new_path": "pkg/tcpip/transport/tcp/rack.go", "diff": "@@ -17,7 +17,6 @@ package tcp\nimport (\n\"time\"\n- \"gvisor.dev/gvisor/pkg/sleep\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n)\n@@ -50,7 +49,8 @@ type rackControl struct {\n// dsackSeen indicates if the connection has seen a DSACK.\ndsackSeen bool\n- // endSequence is the ending TCP sequence number of rackControl.seg.\n+ // endSequence is the ending TCP sequence number of the most recent\n+ // acknowledged segment.\nendSequence seqnum.Value\n// exitedRecovery indicates if the connection is exiting loss recovery.\n@@ -90,13 +90,10 @@ type rackControl struct {\n// rttSeq is the SND.NXT when rtt is updated.\nrttSeq seqnum.Value\n- // xmitTime is the latest transmission timestamp of rackControl.seg.\n+ // xmitTime is the latest transmission timestamp of the most recent\n+ // acknowledged segment.\nxmitTime time.Time `state:\".(unixTime)\"`\n- // probeTimer and probeWaker are used to schedule PTO for RACK TLP algorithm.\n- probeTimer timer `state:\"nosave\"`\n- probeWaker sleep.Waker `state:\"nosave\"`\n-\n// tlpRxtOut indicates whether there is an unacknowledged\n// TLP retransmission.\ntlpRxtOut bool\n@@ -114,7 +111,6 @@ func (rc *rackControl) init(snd *sender, iss seqnum.Value) {\nrc.fack = iss\nrc.reoWndIncr = 1\nrc.snd = snd\n- rc.probeTimer.init(&rc.probeWaker)\n}\n// update will update the RACK related fields when an ACK has been received.\n@@ -223,13 +219,13 @@ func (s *sender) schedulePTO() {\ns.resendTimer.disable()\n}\n- s.rc.probeTimer.enable(pto)\n+ s.probeTimer.enable(pto)\n}\n// probeTimerExpired is the same as TLP_send_probe() as defined in\n// https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.5.2.\nfunc (s *sender) probeTimerExpired() tcpip.Error {\n- if !s.rc.probeTimer.checkExpiration() {\n+ if !s.probeTimer.checkExpiration() {\nreturn nil\n}\n@@ -386,3 +382,102 @@ func (rc *rackControl) updateRACKReorderWindow(ackSeg *segment) {\nfunc (rc *rackControl) exitRecovery() {\nrc.exitedRecovery = true\n}\n+\n+// detectLoss marks the segment as lost if the reordering window has elapsed\n+// and the ACK is not received. It will also arm the reorder timer.\n+// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2 Step 5.\n+func (rc *rackControl) detectLoss(rcvTime time.Time) int {\n+ var timeout time.Duration\n+ numLost := 0\n+ for seg := rc.snd.writeList.Front(); seg != nil && seg.xmitCount != 0; seg = seg.Next() {\n+ if rc.snd.ep.scoreboard.IsSACKED(seg.sackBlock()) {\n+ continue\n+ }\n+\n+ if seg.lost && seg.xmitCount == 1 {\n+ numLost++\n+ continue\n+ }\n+\n+ endSeq := seg.sequenceNumber.Add(seqnum.Size(seg.data.Size()))\n+ if seg.xmitTime.Before(rc.xmitTime) || (seg.xmitTime.Equal(rc.xmitTime) && rc.endSequence.LessThan(endSeq)) {\n+ timeRemaining := seg.xmitTime.Sub(rcvTime) + rc.rtt + rc.reoWnd\n+ if timeRemaining <= 0 {\n+ seg.lost = true\n+ numLost++\n+ } else if timeRemaining > timeout {\n+ timeout = timeRemaining\n+ }\n+ }\n+ }\n+\n+ if timeout != 0 && !rc.snd.reorderTimer.enabled() {\n+ rc.snd.reorderTimer.enable(timeout)\n+ }\n+ return numLost\n+}\n+\n+// reorderTimerExpired will retransmit the segments which have not been acked\n+// before the reorder timer expired.\n+func (rc *rackControl) reorderTimerExpired() tcpip.Error {\n+ // Check if the timer actually expired or if it's a spurious wake due\n+ // to a previously orphaned runtime timer.\n+ if !rc.snd.reorderTimer.checkExpiration() {\n+ return nil\n+ }\n+\n+ numLost := rc.detectLoss(time.Now())\n+ if numLost == 0 {\n+ return nil\n+ }\n+\n+ fastRetransmit := false\n+ if !rc.snd.fr.active {\n+ rc.snd.cc.HandleLossDetected()\n+ rc.snd.enterRecovery()\n+ fastRetransmit = true\n+ }\n+\n+ rc.DoRecovery(nil, fastRetransmit)\n+ return nil\n+}\n+\n+// DoRecovery implements lossRecovery.DoRecovery.\n+func (rc *rackControl) DoRecovery(_ *segment, fastRetransmit bool) {\n+ snd := rc.snd\n+ if fastRetransmit {\n+ snd.resendSegment()\n+ }\n+\n+ var dataSent bool\n+ // Iterate the writeList and retransmit the segments which are marked\n+ // as lost by RACK.\n+ for seg := snd.writeList.Front(); seg != nil && seg.xmitCount > 0; seg = seg.Next() {\n+ if seg == snd.writeNext {\n+ break\n+ }\n+\n+ if !seg.lost {\n+ continue\n+ }\n+\n+ // Reset seg.lost as it is already SACKed.\n+ if snd.ep.scoreboard.IsSACKED(seg.sackBlock()) {\n+ seg.lost = false\n+ continue\n+ }\n+\n+ // Check the congestion window after entering recovery.\n+ if snd.outstanding >= snd.sndCwnd {\n+ break\n+ }\n+\n+ snd.outstanding++\n+ dataSent = true\n+ snd.sendSegment(seg)\n+ }\n+\n+ // Rearm the RTO.\n+ snd.resendTimer.enable(snd.rto)\n+ snd.postXmit(dataSent)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack_state.go", "new_path": "pkg/tcpip/transport/tcp/rack_state.go", "diff": "@@ -27,8 +27,3 @@ func (rc *rackControl) saveXmitTime() unixTime {\nfunc (rc *rackControl) loadXmitTime(unix unixTime) {\nrc.xmitTime = time.Unix(unix.second, unix.nano)\n}\n-\n-// afterLoad is invoked by stateify.\n-func (rc *rackControl) afterLoad() {\n- rc.probeTimer.init(&rc.probeWaker)\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/segment.go", "new_path": "pkg/tcpip/transport/tcp/segment.go", "diff": "@@ -83,6 +83,9 @@ type segment struct {\n// dataMemSize is the memory used by data initially.\ndataMemSize int\n+\n+ // lost indicates if the segment is marked as lost by RACK.\n+ lost bool\n}\nfunc newIncomingSegment(id stack.TransportEndpointID, pkt *stack.PacketBuffer) *segment {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -191,6 +191,15 @@ type sender struct {\n// rc has the fields needed for implementing RACK loss detection\n// algorithm.\nrc rackControl\n+\n+ // reorderTimer is the timer used to retransmit the segments after RACK\n+ // detects them as lost.\n+ reorderTimer timer `state:\"nosave\"`\n+ reorderWaker sleep.Waker `state:\"nosave\"`\n+\n+ // probeTimer and probeWaker are used to schedule PTO for RACK TLP algorithm.\n+ probeTimer timer `state:\"nosave\"`\n+ probeWaker sleep.Waker `state:\"nosave\"`\n}\n// rtt is a synchronization wrapper used to appease stateify. See the comment\n@@ -267,7 +276,6 @@ func newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint\n}\ns.cc = s.initCongestionControl(ep.cc)\n-\ns.lr = s.initLossRecovery()\ns.rc.init(s, iss)\n@@ -278,6 +286,8 @@ func newSender(ep *endpoint, iss, irs seqnum.Value, sndWnd seqnum.Size, mss uint\n}\ns.resendTimer.init(&s.resendWaker)\n+ s.reorderTimer.init(&s.reorderWaker)\n+ s.probeTimer.init(&s.probeWaker)\ns.updateMaxPayloadSize(int(ep.route.MTU()), 0)\n@@ -1126,6 +1136,15 @@ func (s *sender) SetPipe() {\nfunc (s *sender) detectLoss(seg *segment) (fastRetransmit bool) {\n// We're not in fast recovery yet.\n+ // If RACK is enabled and there is no reordering we should honor the\n+ // three duplicate ACK rule to enter recovery.\n+ // See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-4\n+ if s.ep.sackPermitted && s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\n+ if s.rc.reorderSeen {\n+ return false\n+ }\n+ }\n+\nif !s.isDupAck(seg) {\ns.dupAckCount = 0\nreturn false\n@@ -1462,6 +1481,7 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\nif s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.rc.exitRecovery()\n}\n+ s.reorderTimer.disable()\n}\n}\n@@ -1481,21 +1501,36 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// Reset firstRetransmittedSegXmitTime to the zero value.\ns.firstRetransmittedSegXmitTime = time.Time{}\ns.resendTimer.disable()\n- s.rc.probeTimer.disable()\n+ s.probeTimer.disable()\n}\n}\n+ if s.ep.sackPermitted && s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\n// Update RACK reorder window.\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n// * Upon receiving an ACK:\n// * Step 4: Update RACK reordering window\n- if s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\ns.rc.updateRACKReorderWindow(rcvdSeg)\n+\n+ // After the reorder window is calculated, detect any loss by checking\n+ // if the time elapsed after the segments are sent is greater than the\n+ // reorder window.\n+ if numLost := s.rc.detectLoss(rcvdSeg.rcvdTime); numLost > 0 && !s.fr.active {\n+ // If any segment is marked as lost by\n+ // RACK, enter recovery and retransmit\n+ // the lost segments.\n+ s.cc.HandleLossDetected()\n+ s.enterRecovery()\n+ }\n+\n+ if s.fr.active {\n+ s.rc.DoRecovery(nil, true)\n+ }\n}\n// Now that we've popped all acknowledged data from the retransmit\n// queue, retransmit if needed.\n- if s.fr.active {\n+ if s.fr.active && s.ep.tcpRecovery&tcpip.TCPRACKLossDetection == 0 {\ns.lr.DoRecovery(rcvdSeg, fastRetransmit)\n// When SACK is enabled data sending is governed by steps in\n// RFC 6675 Section 5 recovery steps A-C.\n@@ -1523,6 +1558,7 @@ func (s *sender) sendSegment(seg *segment) tcpip.Error {\n}\nseg.xmitTime = time.Now()\nseg.xmitCount++\n+ seg.lost = false\nerr := s.sendSegmentFromView(seg.data, seg.flags, seg.sequenceNumber)\n// Every time a packet containing data is sent (including a\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd_state.go", "new_path": "pkg/tcpip/transport/tcp/snd_state.go", "diff": "@@ -47,6 +47,8 @@ func (s *sender) loadRttMeasureTime(unix unixTime) {\n// afterLoad is invoked by stateify.\nfunc (s *sender) afterLoad() {\ns.resendTimer.init(&s.resendWaker)\n+ s.reorderTimer.init(&s.reorderWaker)\n+ s.probeTimer.init(&s.probeWaker)\n}\n// saveFirstRetransmittedSegXmitTime is invoked by stateify.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/testing/context\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n)\nconst (\n@@ -99,6 +100,8 @@ func TestRACKDetectReorder(t *testing.T) {\nc := context.New(t, uint32(mtu))\ndefer c.Cleanup()\n+ t.Skipf(\"Skipping this test as reorder detection does not consider DSACK.\")\n+\nvar n int\nconst ackNumToVerify = 2\nprobeDone := make(chan struct{})\n@@ -591,7 +594,6 @@ func TestRACKCheckReorderWindow(t *testing.T) {\nc.SendAck(seq, bytesRead)\n// Missing [2-6] packets and SACK #7 packet.\n- seq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nstart := c.IRS.Add(1 + seqnum.Size(6*maxPayload))\nend := start.Add(seqnum.Size(maxPayload))\nc.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n@@ -607,3 +609,46 @@ func TestRACKCheckReorderWindow(t *testing.T) {\nt.Fatalf(\"unexpected values for RACK variables: %v\", err)\n}\n}\n+\n+func TestRACKWithDuplicateACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ const numPackets = 4\n+ data := sendAndReceive(t, c, numPackets)\n+\n+ // Send three duplicate ACKs to trigger fast recovery.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ start := c.IRS.Add(1 + seqnum.Size(maxPayload))\n+ end := start.Add(seqnum.Size(maxPayload))\n+ for i := 0; i < 3; i++ {\n+ c.SendAckWithSACK(seq, maxPayload, []header.SACKBlock{{start, end}})\n+ end = end.Add(seqnum.Size(maxPayload))\n+ }\n+\n+ // Receive the retransmitted packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, maxPayload, maxPayload, tsOptionSize)\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 1},\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 1},\n+ {tcpStats.FastRecovery, \"stats.TCP.FastRecovery\", 0},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
RACK: Detect loss Detect packet loss using reorder window and re-transmit them after the reorder timer expires. PiperOrigin-RevId: 356321786
259,907
08.02.2021 18:00:36
28,800
e51f775cbb8db89d1dac6dcf584be5eef1f82d3c
[go-marshal] Remove binary package reference from syscalls package. Fixes a bug in our getsockopt(2) implementation which was incorrectly using binary.Size() instead of Marshallable.SizeBytes().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/BUILD", "new_path": "pkg/sentry/syscalls/linux/BUILD", "diff": "@@ -62,7 +62,6 @@ go_library(\ndeps = [\n\"//pkg/abi\",\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n\"//pkg/bpf\",\n\"//pkg/context\",\n\"//pkg/log\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/marshal/primitive\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n@@ -457,7 +456,7 @@ func GetSockOpt(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn 0, nil, e.ToError()\n}\n- vLen := int32(binary.Size(v))\n+ vLen := int32(v.SizeBytes())\nif _, err := primitive.CopyInt32Out(t, optLenAddr, vLen); err != nil {\nreturn 0, nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "diff": "@@ -39,7 +39,6 @@ go_library(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n\"//pkg/bits\",\n\"//pkg/context\",\n\"//pkg/fspath\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "diff": "@@ -18,7 +18,6 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/marshal\"\n\"gvisor.dev/gvisor/pkg/marshal/primitive\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n@@ -460,7 +459,7 @@ func GetSockOpt(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sy\nreturn 0, nil, e.ToError()\n}\n- vLen := int32(binary.Size(v))\n+ vLen := int32(v.SizeBytes())\nif _, err := primitive.CopyInt32Out(t, optLenAddr, vLen); err != nil {\nreturn 0, nil, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
[go-marshal] Remove binary package reference from syscalls package. Fixes a bug in our getsockopt(2) implementation which was incorrectly using binary.Size() instead of Marshallable.SizeBytes(). PiperOrigin-RevId: 356396551
259,853
08.02.2021 19:15:45
28,800
bf4968e17d7d08299493835a34af1a6d8551c375
exec: don't panic if an elf file is malformed Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/loader/elf.go", "new_path": "pkg/sentry/loader/elf.go", "diff": "@@ -517,12 +517,14 @@ func loadParsedELF(ctx context.Context, m *mm.MemoryManager, f fsbridge.File, in\nstart, ok = start.AddLength(uint64(offset))\nif !ok {\n- panic(fmt.Sprintf(\"Start %#x + offset %#x overflows?\", start, offset))\n+ ctx.Infof(fmt.Sprintf(\"Start %#x + offset %#x overflows?\", start, offset))\n+ return loadedELF{}, syserror.EINVAL\n}\nend, ok = end.AddLength(uint64(offset))\nif !ok {\n- panic(fmt.Sprintf(\"End %#x + offset %#x overflows?\", end, offset))\n+ ctx.Infof(fmt.Sprintf(\"End %#x + offset %#x overflows?\", end, offset))\n+ return loadedELF{}, syserror.EINVAL\n}\ninfo.entry, ok = info.entry.AddLength(uint64(offset))\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exec_binary.cc", "new_path": "test/syscalls/linux/exec_binary.cc", "diff": "@@ -951,6 +951,34 @@ TEST(ElfTest, PIEOutOfOrderSegments) {\nEXPECT_EQ(execve_errno, ENOEXEC);\n}\n+TEST(ElfTest, PIEOverflow) {\n+ ElfBinary<64> elf = StandardElf();\n+\n+ elf.header.e_type = ET_DYN;\n+\n+ // Choose vaddr of the first segment so that the end address overflows if the\n+ // segment is mapped with a non-zero offset.\n+ elf.phdrs[1].p_vaddr = 0xfffffffffffff000UL - elf.phdrs[1].p_memsz;\n+\n+ elf.UpdateOffsets();\n+\n+ TempPath file = ASSERT_NO_ERRNO_AND_VALUE(CreateElfWith(elf));\n+\n+ pid_t child;\n+ int execve_errno;\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n+ ForkAndExec(file.path(), {file.path()}, {}, &child, &execve_errno));\n+ if (IsRunningOnGvisor()) {\n+ ASSERT_EQ(execve_errno, EINVAL);\n+ } else {\n+ ASSERT_EQ(execve_errno, 0);\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(child, &status, 0),\n+ SyscallSucceedsWithValue(child));\n+ EXPECT_TRUE(WIFSIGNALED(status) && WTERMSIG(status) == SIGSEGV) << status;\n+ }\n+}\n+\n// Standard dynamically linked binary with an ELF interpreter.\nTEST(ElfTest, ELFInterpreter) {\nElfBinary<64> interpreter = StandardElf();\n" } ]
Go
Apache License 2.0
google/gvisor
exec: don't panic if an elf file is malformed Reported-by: [email protected] PiperOrigin-RevId: 356406975
259,898
08.02.2021 20:10:54
28,800
95500ece56f2acf34fcdc74e420f91beea888ada
Allow UDP sockets connect()ing to port 0 We previously return EINVAL when connecting to port 0, however this is not the observed behavior on Linux. One of the observable effects after connecting to port 0 on Linux is that getpeername() will fail with ENOTCONN.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -938,11 +938,6 @@ func (e *endpoint) Disconnect() tcpip.Error {\n// Connect connects the endpoint to its peer. Specifying a NIC is optional.\nfunc (e *endpoint) Connect(addr tcpip.FullAddress) tcpip.Error {\n- if addr.Port == 0 {\n- // We don't support connecting to port zero.\n- return &tcpip.ErrInvalidEndpointState{}\n- }\n-\ne.mu.Lock()\ndefer e.mu.Unlock()\n@@ -1188,7 +1183,7 @@ func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n- if e.EndpointState() != StateConnected {\n+ if e.EndpointState() != StateConnected || e.dstPort == 0 {\nreturn tcpip.FullAddress{}, &tcpip.ErrNotConnected{}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "@@ -2061,11 +2061,92 @@ TEST_P(UdpSocketTest, SendToZeroPort) {\nSyscallSucceedsWithValue(sizeof(buf)));\n}\n+TEST_P(UdpSocketTest, ConnectToZeroPortUnbound) {\n+ struct sockaddr_storage addr = InetLoopbackAddr();\n+ SetPort(&addr, 0);\n+ ASSERT_THAT(\n+ connect(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr), addrlen_),\n+ SyscallSucceeds());\n+}\n+\n+TEST_P(UdpSocketTest, ConnectToZeroPortBound) {\n+ struct sockaddr_storage addr = InetLoopbackAddr();\n+ ASSERT_NO_ERRNO(\n+ BindSocket(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr)));\n+\n+ SetPort(&addr, 0);\n+ ASSERT_THAT(\n+ connect(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr), addrlen_),\n+ SyscallSucceeds());\n+ socklen_t len = sizeof(sockaddr_storage);\n+ ASSERT_THAT(\n+ getsockname(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr), &len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(len, addrlen_);\n+}\n+\n+TEST_P(UdpSocketTest, ConnectToZeroPortConnected) {\n+ struct sockaddr_storage addr = InetLoopbackAddr();\n+ ASSERT_NO_ERRNO(\n+ BindSocket(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr)));\n+\n+ // Connect to an address with non-zero port should succeed.\n+ ASSERT_THAT(\n+ connect(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr), addrlen_),\n+ SyscallSucceeds());\n+ sockaddr_storage peername;\n+ socklen_t peerlen = sizeof(peername);\n+ ASSERT_THAT(\n+ getpeername(sock_.get(), reinterpret_cast<struct sockaddr*>(&peername),\n+ &peerlen),\n+ SyscallSucceeds());\n+ ASSERT_EQ(peerlen, addrlen_);\n+ ASSERT_EQ(memcmp(&peername, &addr, addrlen_), 0);\n+\n+ // However connect() to an address with port 0 will make the following\n+ // getpeername() fail.\n+ SetPort(&addr, 0);\n+ ASSERT_THAT(\n+ connect(sock_.get(), reinterpret_cast<struct sockaddr*>(&addr), addrlen_),\n+ SyscallSucceeds());\n+ ASSERT_THAT(\n+ getpeername(sock_.get(), reinterpret_cast<struct sockaddr*>(&peername),\n+ &peerlen),\n+ SyscallFailsWithErrno(ENOTCONN));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, UdpSocketTest,\n::testing::Values(AddressFamily::kIpv4,\nAddressFamily::kIpv6,\nAddressFamily::kDualStack));\n+TEST(UdpInet6SocketTest, ConnectInet4Sockaddr) {\n+ // glibc getaddrinfo expects the invariant expressed by this test to be held.\n+ const sockaddr_in connect_sockaddr = {\n+ .sin_family = AF_INET, .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)}};\n+ auto sock_ =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP));\n+ ASSERT_THAT(\n+ connect(sock_.get(),\n+ reinterpret_cast<const struct sockaddr*>(&connect_sockaddr),\n+ sizeof(sockaddr_in)),\n+ SyscallSucceeds());\n+ socklen_t len;\n+ sockaddr_storage sockname;\n+ ASSERT_THAT(getsockname(sock_.get(),\n+ reinterpret_cast<struct sockaddr*>(&sockname), &len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(sockname.ss_family, AF_INET6);\n+ ASSERT_EQ(len, sizeof(sockaddr_in6));\n+ auto sin6 = reinterpret_cast<struct sockaddr_in6*>(&sockname);\n+ char addr_buf[INET6_ADDRSTRLEN];\n+ const char* addr;\n+ ASSERT_NE(addr = inet_ntop(sockname.ss_family, &sockname, addr_buf,\n+ sizeof(addr_buf)),\n+ nullptr);\n+ ASSERT_TRUE(IN6_IS_ADDR_V4MAPPED(sin6->sin6_addr.s6_addr)) << addr;\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Allow UDP sockets connect()ing to port 0 We previously return EINVAL when connecting to port 0, however this is not the observed behavior on Linux. One of the observable effects after connecting to port 0 on Linux is that getpeername() will fail with ENOTCONN. PiperOrigin-RevId: 356413451
260,004
08.02.2021 21:39:29
28,800
6671a42d605d681e6aa63b610617523ab632e95a
Remove unnecessary locking The thing the lock protects will never be accessed concurrently.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp.go", "new_path": "pkg/tcpip/network/ipv6/ndp.go", "diff": "@@ -466,20 +466,6 @@ type ndpState struct {\ntemporaryAddressDesyncFactor time.Duration\n}\n-type remainingCounter struct {\n- mu struct {\n- sync.Mutex\n-\n- remaining uint8\n- }\n-}\n-\n-func (r *remainingCounter) init(max uint8) {\n- r.mu.Lock()\n- defer r.mu.Unlock()\n- r.mu.remaining = max\n-}\n-\n// defaultRouterState holds data associated with a default router discovered by\n// a Router Advertisement (RA).\ntype defaultRouterState struct {\n@@ -1687,7 +1673,8 @@ func (ndp *ndpState) startSolicitingRouters() {\nreturn\n}\n- if ndp.configs.MaxRtrSolicitations == 0 {\n+ remaining := ndp.configs.MaxRtrSolicitations\n+ if remaining == 0 {\nreturn\n}\n@@ -1698,9 +1685,6 @@ func (ndp *ndpState) startSolicitingRouters() {\ndelay = time.Duration(rand.Int63n(int64(ndp.configs.MaxRtrSolicitationDelay)))\n}\n- var remaining remainingCounter\n- remaining.init(ndp.configs.MaxRtrSolicitations)\n-\n// Protected by ndp.ep.mu.\ndone := false\n@@ -1754,19 +1738,13 @@ func (ndp *ndpState) startSolicitingRouters() {\npanic(fmt.Sprintf(\"failed to add IP header: %s\", err))\n}\n- // Okay to hold this lock while writing packets since we use a different\n- // lock per router solicitaiton timer so there will not be any lock\n- // contention.\n- remaining.mu.Lock()\n- defer remaining.mu.Unlock()\n-\nif err := ndp.ep.nic.WritePacketToRemote(header.EthernetAddressFromMulticastIPv6Address(header.IPv6AllRoutersMulticastAddress), nil /* gso */, ProtocolNumber, pkt); err != nil {\nsent.dropped.Increment()\n// Don't send any more messages if we had an error.\n- remaining.mu.remaining = 0\n+ remaining = 0\n} else {\nsent.routerSolicit.Increment()\n- remaining.mu.remaining--\n+ remaining--\n}\nndp.ep.mu.Lock()\n@@ -1777,7 +1755,7 @@ func (ndp *ndpState) startSolicitingRouters() {\nreturn\n}\n- if remaining.mu.remaining == 0 {\n+ if remaining == 0 {\n// We are done soliciting routers.\nndp.stopSolicitingRouters()\nreturn\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -146,20 +146,6 @@ func newStaticNeighborEntry(cache *neighborCache, addr tcpip.Address, linkAddr t\nreturn n\n}\n-type remainingCounter struct {\n- mu struct {\n- sync.Mutex\n-\n- remaining uint32\n- }\n-}\n-\n-func (r *remainingCounter) init(max uint32) {\n- r.mu.Lock()\n- defer r.mu.Unlock()\n- r.mu.remaining = max\n-}\n-\n// notifyCompletionLocked notifies those waiting for address resolution, with\n// the link address if resolution completed successfully.\n//\n@@ -298,8 +284,7 @@ func (e *neighborEntry) setStateLocked(next NeighborState) {\n// Protected by e.mu.\ndone := false\n- var remaining remainingCounter\n- remaining.init(config.MaxUnicastProbes)\n+ remaining := config.MaxUnicastProbes\naddr := e.mu.neigh.Addr\nlinkAddr := e.mu.neigh.LinkAddr\n@@ -310,13 +295,8 @@ func (e *neighborEntry) setStateLocked(next NeighborState) {\ne.mu.timer = timer{\ndone: &done,\ntimer: e.cache.nic.stack.Clock().AfterFunc(0, func() {\n- // Okay to hold this lock while writing packets since we use a different\n- // lock per probe timer so there will not be any lock contention.\n- remaining.mu.Lock()\n- defer remaining.mu.Unlock()\n-\nvar err tcpip.Error\n- timedoutResolution := remaining.mu.remaining == 0\n+ timedoutResolution := remaining == 0\nif !timedoutResolution {\nerr = e.cache.linkRes.LinkAddressRequest(addr, \"\" /* localAddr */, linkAddr)\n}\n@@ -335,7 +315,7 @@ func (e *neighborEntry) setStateLocked(next NeighborState) {\nreturn\n}\n- remaining.mu.remaining--\n+ remaining--\ne.mu.timer.timer.Reset(config.RetransmitTimer)\n}),\n}\n@@ -373,8 +353,7 @@ func (e *neighborEntry) handlePacketQueuedLocked(localAddr tcpip.Address) {\n// Protected by e.mu.\ndone := false\n- var remaining remainingCounter\n- remaining.init(config.MaxMulticastProbes)\n+ remaining := config.MaxMulticastProbes\naddr := e.mu.neigh.Addr\n// Send a probe in another gorountine to free this thread of execution\n@@ -384,13 +363,8 @@ func (e *neighborEntry) handlePacketQueuedLocked(localAddr tcpip.Address) {\ne.mu.timer = timer{\ndone: &done,\ntimer: e.cache.nic.stack.Clock().AfterFunc(0, func() {\n- // Okay to hold this lock while writing packets since we use a different\n- // lock per probe timer so there will not be any lock contention.\n- remaining.mu.Lock()\n- defer remaining.mu.Unlock()\n-\nvar err tcpip.Error\n- timedoutResolution := remaining.mu.remaining == 0\n+ timedoutResolution := remaining == 0\nif !timedoutResolution {\n// As per RFC 4861 section 7.2.2:\n//\n@@ -416,7 +390,7 @@ func (e *neighborEntry) handlePacketQueuedLocked(localAddr tcpip.Address) {\nreturn\n}\n- remaining.mu.remaining--\n+ remaining--\ne.mu.timer.timer.Reset(config.RetransmitTimer)\n}),\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove unnecessary locking The thing the lock protects will never be accessed concurrently. PiperOrigin-RevId: 356423331
259,853
09.02.2021 01:32:55
28,800
d6dbe6e5ca5445dac278d3b6654af8d13379878a
pipe: writeLocked has to return ErrWouldBlock if the pipe is full
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -656,6 +656,9 @@ func (rw *regularFileReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64,\n// Write to that memory as usual.\nseg, gap = rw.file.data.Insert(gap, gapMR, fr.Start), fsutil.FileRangeGapIterator{}\n+\n+ default:\n+ panic(\"unreachable\")\n}\n}\nexitLoop:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/pipe.go", "new_path": "pkg/sentry/kernel/pipe/pipe.go", "diff": "@@ -247,11 +247,15 @@ func (p *Pipe) writeLocked(count int64, f func(safemem.BlockSeq) (uint64, error)\nreturn 0, syscall.EPIPE\n}\n- // POSIX requires that a write smaller than atomicIOBytes (PIPE_BUF) be\n- // atomic, but requires no atomicity for writes larger than this.\navail := p.max - p.size\n+ if avail == 0 {\n+ return 0, syserror.ErrWouldBlock\n+ }\nshort := false\nif count > avail {\n+ // POSIX requires that a write smaller than atomicIOBytes\n+ // (PIPE_BUF) be atomic, but requires no atomicity for writes\n+ // larger than this.\nif count <= atomicIOBytes {\nreturn 0, syserror.ErrWouldBlock\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sendfile.cc", "new_path": "test/syscalls/linux/sendfile.cc", "diff": "@@ -551,6 +551,29 @@ TEST(SendFileTest, SendPipeEOF) {\nSyscallSucceedsWithValue(0));\n}\n+TEST(SendFileTest, SendToFullPipeReturnsEAGAIN) {\n+ // Create and open an empty input file.\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor in_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+\n+ // Set up the output pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe2(fds, O_NONBLOCK), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ int pipe_size = -1;\n+ ASSERT_THAT(pipe_size = fcntl(wfd.get(), F_GETPIPE_SZ), SyscallSucceeds());\n+ int data_size = pipe_size * 8;\n+ ASSERT_THAT(ftruncate(in_fd.get(), data_size), SyscallSucceeds());\n+\n+ ASSERT_THAT(sendfile(wfd.get(), in_fd.get(), 0, data_size),\n+ SyscallSucceeds());\n+ EXPECT_THAT(sendfile(wfd.get(), in_fd.get(), 0, data_size),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\nTEST(SendFileTest, SendPipeBlocks) {\n// Create temp file.\nconstexpr char kData[] =\n" } ]
Go
Apache License 2.0
google/gvisor
pipe: writeLocked has to return ErrWouldBlock if the pipe is full PiperOrigin-RevId: 356450303
259,853
09.02.2021 10:34:49
28,800
fe4f4789601ddf61260271f7e1d33ba0f2756fcd
kernel: reparentLocked has to update children maps of old and new parents Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_exit.go", "new_path": "pkg/sentry/kernel/task_exit.go", "diff": "@@ -415,6 +415,12 @@ func (tg *ThreadGroup) anyNonExitingTaskLocked() *Task {\nfunc (t *Task) reparentLocked(parent *Task) {\noldParent := t.parent\nt.parent = parent\n+ if oldParent != nil {\n+ delete(oldParent.children, t)\n+ }\n+ if parent != nil {\n+ parent.children[t] = struct{}{}\n+ }\n// If a thread group leader's parent changes, reset the thread group's\n// termination signal to SIGCHLD and re-check exit notification. (Compare\n// kernel/exit.c:reparent_leader().)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -993,3 +993,7 @@ syscall_test(\nsyscall_test(\ntest = \"//test/syscalls/linux:proc_net_udp_test\",\n)\n+\n+syscall_test(\n+ test = \"//test/syscalls/linux:processes_test\",\n+)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -4159,6 +4159,18 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"processes_test\",\n+ testonly = 1,\n+ srcs = [\"processes.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_binary(\nname = \"xattr_test\",\ntestonly = 1,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/processes.cc", "diff": "+// Copyright 2021 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 <stdint.h>\n+#include <sys/syscall.h>\n+#include <unistd.h>\n+\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+int testSetPGIDOfZombie(void* arg) {\n+ int p[2];\n+\n+ TEST_PCHECK(pipe(p) == 0);\n+\n+ pid_t pid = fork();\n+ if (pid == 0) {\n+ pid = fork();\n+ // Create a second child to repeat one of syzkaller reproducers.\n+ if (pid == 0) {\n+ pid = getpid();\n+ TEST_PCHECK(setpgid(pid, 0) == 0);\n+ TEST_PCHECK(write(p[1], &pid, sizeof(pid)) == sizeof(pid));\n+ _exit(0);\n+ }\n+ TEST_PCHECK(pid > 0);\n+ _exit(0);\n+ }\n+ close(p[1]);\n+ TEST_PCHECK(pid > 0);\n+\n+ // Get PID of the second child.\n+ pid_t cpid;\n+ TEST_PCHECK(read(p[0], &cpid, sizeof(cpid)) == sizeof(cpid));\n+\n+ // Wait when both child processes will die.\n+ int c;\n+ TEST_PCHECK(read(p[0], &c, sizeof(c)) == 0);\n+\n+ // Wait the second child process to collect its zombie.\n+ int status;\n+ TEST_PCHECK(RetryEINTR(waitpid)(cpid, &status, 0) == cpid);\n+\n+ // Set the child's group.\n+ TEST_PCHECK(setpgid(pid, pid) == 0);\n+\n+ TEST_PCHECK(RetryEINTR(waitpid)(-pid, &status, 0) == pid);\n+\n+ TEST_PCHECK(status == 0);\n+ _exit(0);\n+}\n+\n+TEST(Processes, SetPGIDOfZombie) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+\n+ // Fork a test process in a new PID namespace, because it needs to manipulate\n+ // with reparanted processes.\n+ struct clone_arg {\n+ // Reserve some space for clone() to locate arguments and retcode in this\n+ // place.\n+ char stack[128] __attribute__((aligned(16)));\n+ char stack_ptr[0];\n+ } ca;\n+ pid_t pid;\n+ ASSERT_THAT(pid = clone(testSetPGIDOfZombie, ca.stack_ptr,\n+ CLONE_NEWPID | SIGCHLD, &ca),\n+ SyscallSucceeds());\n+\n+ int status;\n+ ASSERT_THAT(RetryEINTR(waitpid)(pid, &status, 0),\n+ SyscallSucceedsWithValue(pid));\n+ EXPECT_EQ(status, 0);\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
kernel: reparentLocked has to update children maps of old and new parents Reported-by: [email protected] PiperOrigin-RevId: 356536113
259,992
09.02.2021 14:10:59
28,800
0f84ea5afe21c9ebbccb9fa41482a8f7f8d9d3a1
Fix fd leak from test
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/open_create.cc", "new_path": "test/syscalls/linux/open_create.cc", "diff": "@@ -46,8 +46,10 @@ TEST(CreateTest, ExistingFile) {\nTEST(CreateTest, CreateAtFile) {\nauto dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\nauto dirfd = ASSERT_NO_ERRNO_AND_VALUE(Open(dir.path(), O_DIRECTORY, 0666));\n- EXPECT_THAT(openat(dirfd.get(), \"CreateAtFile\", O_RDWR | O_CREAT, 0666),\n+ int fd;\n+ EXPECT_THAT(fd = openat(dirfd.get(), \"CreateAtFile\", O_RDWR | O_CREAT, 0666),\nSyscallSucceeds());\n+ EXPECT_THAT(close(fd), SyscallSucceeds());\n}\nTEST(CreateTest, HonorsUmask_NoRandomSave) {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix fd leak from test PiperOrigin-RevId: 356587965
259,860
09.02.2021 19:15:53
28,800
f6de413c398231cb392bccda3807897703653ab5
Add cleanup TODO for integer-based proc files.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -238,6 +238,8 @@ func (s *StaticData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// WritableDynamicBytesSource extends DynamicBytesSource to allow writes to the\n// underlying source.\n+//\n+// TODO(b/179825241): Make utility for integer-based writable files.\ntype WritableDynamicBytesSource interface {\nDynamicBytesSource\n" } ]
Go
Apache License 2.0
google/gvisor
Add cleanup TODO for integer-based proc files. PiperOrigin-RevId: 356645022
259,975
10.02.2021 10:46:31
28,800
1ac58cc23e7c069ff59ddea333a89c5c5972a555
Add mitigate command to runsc
[ { "change_type": "MODIFY", "old_path": "runsc/cli/main.go", "new_path": "runsc/cli/main.go", "diff": "@@ -85,6 +85,7 @@ func Main(version string) {\nsubcommands.Register(new(cmd.Start), \"\")\nsubcommands.Register(new(cmd.Symbolize), \"\")\nsubcommands.Register(new(cmd.Wait), \"\")\n+ subcommands.Register(new(cmd.Mitigate), \"\")\n// Register internal commands with the internal group name. This causes\n// them to be sorted below the user-facing commands with empty group.\n" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/BUILD", "new_path": "runsc/cmd/BUILD", "diff": "@@ -22,6 +22,7 @@ go_library(\n\"install.go\",\n\"kill.go\",\n\"list.go\",\n+ \"mitigate.go\",\n\"path.go\",\n\"pause.go\",\n\"ps.go\",\n@@ -59,6 +60,7 @@ go_library(\n\"//runsc/flag\",\n\"//runsc/fsgofer\",\n\"//runsc/fsgofer/filter\",\n+ \"//runsc/mitigate\",\n\"//runsc/specutils\",\n\"@com_github_google_subcommands//:go_default_library\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/cmd/mitigate.go", "diff": "+// Copyright 2021 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 cmd\n+\n+import (\n+ \"context\"\n+ \"io/ioutil\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+ \"gvisor.dev/gvisor/runsc/mitigate\"\n+)\n+\n+// Mitigate implements subcommands.Command for the \"mitigate\" command.\n+type Mitigate struct {\n+ mitigate mitigate.Mitigate\n+}\n+\n+// Name implements subcommands.command.name.\n+func (*Mitigate) Name() string {\n+ return \"mitigate\"\n+}\n+\n+// Synopsis implements subcommands.Command.Synopsis.\n+func (*Mitigate) Synopsis() string {\n+ return \"mitigate mitigates the underlying system against side channel attacks\"\n+}\n+\n+// Usage implements subcommands.Command.Usage.\n+func (m *Mitigate) Usage() string {\n+ return m.mitigate.Usage()\n+}\n+\n+// SetFlags implements subcommands.Command.SetFlags.\n+func (m *Mitigate) SetFlags(f *flag.FlagSet) {\n+ m.mitigate.SetFlags(f)\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (m *Mitigate) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+ if f.NArg() != 0 {\n+ f.Usage()\n+ return subcommands.ExitUsageError\n+ }\n+\n+ const path = \"/proc/cpuinfo\"\n+ data, err := ioutil.ReadFile(path)\n+ if err != nil {\n+ log.Warningf(\"Failed to read %s: %v\", path, err)\n+ return subcommands.ExitFailure\n+ }\n+\n+ if err := m.mitigate.Execute(data); err != nil {\n+ log.Warningf(\"Execute failed: %v\", err)\n+ return subcommands.ExitFailure\n+ }\n+\n+ return subcommands.ExitSuccess\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/mitigate/BUILD", "new_path": "runsc/mitigate/BUILD", "diff": "@@ -7,14 +7,25 @@ go_library(\nsrcs = [\n\"cpu.go\",\n\"mitigate.go\",\n+ \"mitigate_conf.go\",\n+ ],\n+ visibility = [\n+ \"//runsc:__subpackages__\",\n+ ],\n+ deps = [\n+ \"//pkg/log\",\n+ \"//runsc/flag\",\n+ \"@in_gopkg_yaml_v2//:go_default_library\",\n],\n- deps = [\"@in_gopkg_yaml_v2//:go_default_library\"],\n)\ngo_test(\nname = \"mitigate_test\",\nsize = \"small\",\n- srcs = [\"cpu_test.go\"],\n+ srcs = [\n+ \"cpu_test.go\",\n+ \"mitigate_test.go\",\n+ ],\nlibrary = \":mitigate\",\ndeps = [\"@com_github_google_go_cmp//cmp:go_default_library\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/mitigate/mitigate.go", "new_path": "runsc/mitigate/mitigate.go", "diff": "// the mitigate also handles computing available CPU in kubernetes kube_config\n// files.\npackage mitigate\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+// Mitigate handles high level mitigate operations provided to runsc.\n+type Mitigate struct {\n+ dryRun bool // Run the command without changing the underlying system.\n+ other mitigate // Struct holds extra mitigate logic.\n+}\n+\n+// Usage implments Usage for cmd.Mitigate.\n+func (m Mitigate) Usage() string {\n+ usageString := `mitigate [flags]\n+\n+This command mitigates an underlying system against side channel attacks.\n+The command checks /proc/cpuinfo for cpus having key vulnerablilities (meltdown,\n+l1tf, mds, swapgs, taa). If cpus are found to have one of the vulnerabilities,\n+all but one cpu is shutdown on each core via\n+/sys/devices/system/cpu/cpu{N}/online.\n+`\n+ return usageString + m.other.usage()\n+}\n+\n+// SetFlags sets flags for the command Mitigate.\n+func (m Mitigate) SetFlags(f *flag.FlagSet) {\n+ f.BoolVar(&m.dryRun, \"dryrun\", false, \"run the command without changing system\")\n+ m.other.setFlags(f)\n+}\n+\n+// Execute executes the Mitigate command.\n+func (m Mitigate) Execute(data []byte) error {\n+ set, err := newCPUSet(data, m.other.vulnerable)\n+ if err != nil {\n+ return err\n+ }\n+\n+ log.Infof(\"Mitigate found the following CPUs...\")\n+ log.Infof(\"%s\", set)\n+\n+ shutdownList := set.getShutdownList()\n+ log.Infof(\"Shutting down threads on thread pairs.\")\n+ for _, t := range shutdownList {\n+ log.Infof(\"Shutting down thread: %s\", t)\n+ if m.dryRun {\n+ continue\n+ }\n+ if err := t.shutdown(); err != nil {\n+ return fmt.Errorf(\"error shutting down thread: %s err: %v\", t, err)\n+ }\n+ }\n+ log.Infof(\"Shutdown successful.\")\n+ m.other.execute(set, m.dryRun)\n+ return nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/mitigate/mitigate_conf.go", "diff": "+// Copyright 2021 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 mitigate\n+\n+import (\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+type mitigate struct {\n+}\n+\n+// usage returns the usage string portion for the mitigate.\n+func (m mitigate) usage() string { return \"\" }\n+\n+// setFlags sets additional flags for the Mitigate command.\n+func (m mitigate) setFlags(f *flag.FlagSet) {}\n+\n+// execute performs additional parts of Execute for Mitigate.\n+func (m mitigate) execute(set cpuSet, dryrun bool) error {\n+ return nil\n+}\n+\n+func (m mitigate) vulnerable(other *thread) bool {\n+ return other.isVulnerable()\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/mitigate/mitigate_test.go", "diff": "+// Copyright 2021 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 mitigate\n" } ]
Go
Apache License 2.0
google/gvisor
Add mitigate command to runsc PiperOrigin-RevId: 356772367
259,985
10.02.2021 13:04:24
28,800
c2f204658ed4a6b0bd110577f22fbfd4104a6f96
Add proposal for io_uring project.
[ { "change_type": "ADD", "old_path": null, "new_path": "g3doc/proposals/BUILD", "diff": "+load(\"//website:defs.bzl\", \"doc\")\n+\n+package(\n+ default_visibility = [\"//website:__pkg__\"],\n+ licenses = [\"notice\"],\n+)\n+\n+doc(\n+ name = \"gsoc_2021\",\n+ src = \"gsoc-2021-ideas.md\",\n+ category = \"Project\",\n+ include_in_menu = False,\n+ permalink = \"/community/gsoc_2021\",\n+ subcategory = \"Community\",\n+ weight = \"99\",\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "g3doc/proposals/gsoc-2021-ideas.md", "diff": "+# Project Ideas for Google Summer of Code 2021\n+\n+This is a collection of project ideas for\n+[Google Summer of Code 2021][gsoc-2021-site]. These projects are intended to be\n+relatively self-contained and should be good starting projects for new\n+contributors to gVisor. We expect individual contributors to be able to make\n+reasonable progress on these projects over the course of several weeks.\n+Familiarity with Golang and knowledge about systems programming in Linux will be\n+helpful.\n+\n+If you're interested in contributing to gVisor through Google Summer of Code\n+2021, but would like to propose your own idea for a project, please see our\n+[roadmap](../roadmap.md) for areas of development, and get in touch through our\n+[mailing list][gvisor-mailing-list] or [chat][gvisor-chat]!\n+\n+## Implement `io_uring`\n+\n+`io_uring` is the lastest asynchronous I/O API in Linux. This project will\n+involve implementing the system interfaces required to support `io_uring` in\n+gVisor. A successful implementation should have similar relatively performance\n+and scalability characteristics compared to synchronous I/O syscalls, as in\n+Linux.\n+\n+The core of the `io_uring` interface is deceptively simple, involving only three\n+new syscalls:\n+\n+- `io_uring_setup(2)` creates a new `io_uring` instance represented by a file\n+ descriptor, including a set of request submission and completion queues\n+ backed by shared memory ring buffers.\n+\n+- `io_uring_register(2)` optionally binds kernel resources such as files and\n+ memory buffers to handles, which can then be passed to `io_uring`\n+ operations. Pre-registering resources in this way moves the cost of looking\n+ up and validating these resources to registration time rather than paying\n+ the cost during the operation.\n+\n+- `io_uring_enter(2)` is the syscall used to submit queued operations and wait\n+ for completions. This is the most complex part of the mechanism, requiring\n+ the kernel to process queued request from the submission queue, dispatching\n+ the appropriate I/O operation based on the request arguments and blocking\n+ for the requested number of operations to be completed before returning.\n+\n+An `io_uring` request is effectively an opcode specifying the I/O operation to\n+perform, and corresponding arguments. The opcodes and arguments closely relate\n+to the the corresponding synchronous I/O syscall. In addition, there are some\n+`io_uring`-specific arguments that specify things like how to process requests,\n+how to interpret the arguments and communicate the status of the ring buffers.\n+\n+For a detailed description of the `io_uring` interface, see the\n+[design doc][io-uring-doc] by the `io_uring` authors.\n+\n+Due to the complexity of the full `io_uring` mechanism and the numerous\n+supported operations, it should be implemented in two stages:\n+\n+In the first stage, a simplified version of the `io_uring_setup` and\n+`io_uring_enter` syscalls should be implemented, which will only support a\n+minimal set of arguments and just one or two simple opcodes. This simplified\n+implementation can be used to figure out how to integreate `io_uring` with\n+gVisor's virtual filesystem and memory management subsystems, as well as\n+benchmark the implementation to ensure it has the desired performance\n+characteristics. The goal in this stage should be to implement the smallest\n+subset of features required to perform a basic operation through `io_uring`s.\n+\n+In the second stage, support can be added for all the I/O operations supported\n+by Linux, as well as advanced `io_uring` features such as fixed files and\n+buffers (via `io_uring_register`), polled I/O and kernel-side request polling.\n+\n+[gsoc-2021-site]: https://summerofcode.withgoogle.com\n+[gvisor-chat]: https://gitter.im/gvisor/community\n+[gvisor-mailing-list]: https://groups.google.com/g/gvisor-dev\n+[io-uring-doc]: https://kernel.dk/io_uring.pdf\n" } ]
Go
Apache License 2.0
google/gvisor
Add proposal for io_uring project. PiperOrigin-RevId: 356807933
259,975
10.02.2021 15:40:19
28,800
36e4100a2851b42d8f812e92d44eb75ea5e737d4
Update benchmarks README.md
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/README.md", "new_path": "test/benchmarks/README.md", "diff": "@@ -13,49 +13,26 @@ To run benchmarks you will need:\n* Docker installed (17.09.0 or greater).\n-The easiest way to setup runsc for running benchmarks is to use the make file.\n-From the root directory:\n-\n-* Download images: `make load-all-images`\n-* Install runsc suitable for benchmarking, which should probably not have\n- strace or debug logs enabled. For example: `make configure RUNTIME=myrunsc\n- ARGS=--platform=kvm`.\n-* Restart docker: `sudo service docker restart`\n-\n-You should now have a runtime with the following options configured in\n-`/etc/docker/daemon.json`\n-\n-```\n-\"myrunsc\": {\n- \"path\": \"/tmp/myrunsc/runsc\",\n- \"runtimeArgs\": [\n- \"--debug-log\",\n- \"/tmp/bench/logs/runsc.log.%TEST%.%TIMESTAMP%.%COMMAND%\",\n- \"--platform=kvm\"\n- ]\n- },\n-\n-```\n-\n-This runtime has been configured with a debugging off and strace logs off and is\n-using kvm for demonstration.\n-\n## Running benchmarks\n-Given the runtime above runtime `myrunsc`, run benchmarks with the following:\n+To run, use the Makefile:\n-```\n-make sudo TARGETS=//path/to:target ARGS=\"--runtime=myrunsc -test.v \\\n- -test.bench=.\" OPTIONS=\"-c opt\"\n-```\n-\n-For example, to run only the Iperf tests:\n+- Install runsc as a runtime: `make dev`\n+ - The above command will place several configurations of runsc in your\n+ /etc/docker/daemon.json file. Choose one without the debug option set.\n+- Run your benchmark: `make run-benchmark\n+ RUNTIME=[RUNTIME_FROM_DAEMON.JSON/runc]\n+ BENCHMARKS_TARGETS=//path/to/target\"`\n+- Additionally, you can benchmark several platforms in one command:\n```\n-make sudo TARGETS=//test/benchmarks/network:network_test \\\n- ARGS=\"--runtime=myrunsc -test.v -test.bench=Iperf\" OPTIONS=\"-c opt\"\n+make benchmark-platforms BENCHMARKS_PLATFORMS=ptrace,kvm \\\n+BENCHMARKS_TARGET=//path/to/target\"\n```\n+The above command will install runtimes/run benchmarks on ptrace and kvm as well\n+as run the benchmark on native runc.\n+\nBenchmarks are run with root as some benchmarks require root privileges to do\nthings like drop caches.\n@@ -71,7 +48,8 @@ benchmarks.\n`//images/benchmarks/my-cool-dockerfile`.\n* Dockerfiles for benchmarks should:\n* Use explicitly versioned packages.\n- * Not use ENV and CMD statements...it is easy to add these in the API.\n+ * Don't use ENV and CMD statements. It is easy to add these in the API via\n+ `dockerutil.RunOpts`.\n* Note: A common pattern for getting access to a tmpfs mount is to copy files\nthere after container start. See: //test/benchmarks/build/bazel_test.go. You\ncan also make your own with `RunOpts.Mounts`.\n@@ -97,7 +75,7 @@ func BenchmarkMyCoolOne(b *testing.B) {\nout, err := container.Run(ctx, dockerutil.RunOpts{\nImage: \"benchmarks/my-cool-image\",\nEnv: []string{\"MY_VAR=awesome\"},\n- other options...see dockerutil\n+ // other options...see dockerutil\n}, \"sh\", \"-c\", \"echo MY_VAR\")\n// check err...\nb.StopTimer()\n@@ -118,11 +96,16 @@ func TestMain(m *testing.M) {\nSome notes on the above:\n-* Respect `b.N` in that users of the benchmark may want to \"run for an hour\"\n- or something of the sort.\n+* Respect and linearly scale by `b.N` so that users can run a number of times\n+ (--benchtime=10x) or for a time duration (--benchtime=1m). For many\n+ benchmarks, this is just the runtime of the container under test. Sometimes\n+ this is a parameter to the container itself. For Example, the httpd\n+ benchmark (and most client server benchmarks) uses b.N as a parameter to the\n+ Client container that specifies how many requests to make to the server.\n* Use the `b.ReportMetric()` method to report custom metrics.\n-* Set the timer if time is useful for reporting. There isn't a way to turn off\n- default metrics in testing.B (B/op, allocs/op, ns/op).\n+* Never turn off the timer (b.N), but set and reset it if useful for the\n+ benchmark. There isn't a way to turn off default metrics in testing.B (B/op,\n+ allocs/op, ns/op).\n* Take a look at dockerutil at //pkg/test/dockerutil to see all methods\navailable from containers. The API is based on the \"official\"\n[docker API for golang](https://pkg.go.dev/mod/github.com/docker/docker).\n@@ -136,16 +119,11 @@ For profiling, the runtime is required to have the `--profile` flag enabled.\nThis flag loosens seccomp filters so that the runtime can write profile data to\ndisk. This configuration is not recommended for production.\n-* Install runsc with the `--profile` flag: `make configure RUNTIME=myrunsc\n- ARGS=\"--profile --platform=kvm --vfs2\"`. The kvm and vfs2 flags are not\n- required, but are included for demonstration.\n-* Restart docker: `sudo service docker restart`\n+To profile, simply run the `benchmark-platforms` command from above and profiles\n+will be in /tmp/profile.\n-To run and generate CPU profiles fs_test test run:\n-\n-```\n-make sudo TARGETS=//test/benchmarks/fs:fs_test \\\n- ARGS=\"--runtime=myrunsc -test.v -test.bench=. --pprof-cpu\" OPTIONS=\"-c opt\"\n-```\n+Or run with: `make run-benchmark RUNTIME=[RUNTIME_UNDER_TEST]\n+BENCHMARKS_TARGETS=//path/to/target`\n-Profiles would be at: `/tmp/profile/myrunsc/CONTAINERNAME/cpu.pprof`\n+Profiles will be in /tmp/profile. Note: runtimes must have the `--profile` flag\n+set in /etc/docker/daemon.conf and profiling will not work on runc.\n" } ]
Go
Apache License 2.0
google/gvisor
Update benchmarks README.md PiperOrigin-RevId: 356843249
259,907
10.02.2021 16:20:31
28,800
96d3b3188bb19669f09ccad99d243555eb00c3f7
Fix broken IFTTT link in tcpip.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1590,7 +1590,7 @@ type IPStats struct {\n// OptionUnknownReceived is the number of unknown IP options seen.\nOptionUnknownReceived *StatCounter\n- // LINT.ThenChange(network/ip/stats.go:MultiCounterIPStats)\n+ // LINT.ThenChange(network/internal/ip/stats.go:MultiCounterIPStats)\n}\n// ARPStats collects ARP-specific stats.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix broken IFTTT link in tcpip. PiperOrigin-RevId: 356852625
259,853
10.02.2021 16:30:22
28,800
97a36d1696982949722c6d6da1e5031d79e90b48
Don't allow to umount the namespace root mount Linux does the same thing. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -309,6 +309,11 @@ func (vfs *VirtualFilesystem) UmountAt(ctx context.Context, creds *auth.Credenti\nvfs.mountMu.Unlock()\nreturn syserror.EINVAL\n}\n+\n+ if vd.mount == vd.mount.ns.root {\n+ vfs.mountMu.Unlock()\n+ return syserror.EINVAL\n+ }\n}\n// TODO(gvisor.dev/issue/1035): Linux special-cases umount of the caller's\n" } ]
Go
Apache License 2.0
google/gvisor
Don't allow to umount the namespace root mount Linux does the same thing. Reported-by: [email protected] PiperOrigin-RevId: 356854562
259,891
10.02.2021 17:43:25
28,800
81ea0016e62318053f97ec714967047e6191fb2b
Support setgid directories in tmpfs and kernfs
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go", "diff": "@@ -294,22 +294,41 @@ func (a *InodeAttrs) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *aut\nreturn err\n}\n+ clearSID := false\nstat := opts.Stat\n+ if stat.Mask&linux.STATX_UID != 0 {\n+ atomic.StoreUint32(&a.uid, stat.UID)\n+ clearSID = true\n+ }\n+ if stat.Mask&linux.STATX_GID != 0 {\n+ atomic.StoreUint32(&a.gid, stat.GID)\n+ clearSID = true\n+ }\nif stat.Mask&linux.STATX_MODE != 0 {\nfor {\nold := atomic.LoadUint32(&a.mode)\n- new := old | uint32(stat.Mode & ^uint16(linux.S_IFMT))\n- if swapped := atomic.CompareAndSwapUint32(&a.mode, old, new); swapped {\n+ ft := old & linux.S_IFMT\n+ newMode := ft | uint32(stat.Mode & ^uint16(linux.S_IFMT))\n+ if clearSID {\n+ newMode = vfs.ClearSUIDAndSGID(newMode)\n+ }\n+ if swapped := atomic.CompareAndSwapUint32(&a.mode, old, newMode); swapped {\n+ clearSID = false\nbreak\n}\n}\n}\n- if stat.Mask&linux.STATX_UID != 0 {\n- atomic.StoreUint32(&a.uid, stat.UID)\n+ // We may have to clear the SUID/SGID bits, but didn't do so as part of\n+ // STATX_MODE.\n+ if clearSID {\n+ for {\n+ old := atomic.LoadUint32(&a.mode)\n+ newMode := vfs.ClearSUIDAndSGID(old)\n+ if swapped := atomic.CompareAndSwapUint32(&a.mode, old, newMode); swapped {\n+ break\n+ }\n}\n- if stat.Mask&linux.STATX_GID != 0 {\n- atomic.StoreUint32(&a.gid, stat.GID)\n}\nnow := ktime.NowFromContext(ctx).Nanoseconds()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/device_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/device_file.go", "diff": "@@ -30,7 +30,7 @@ type deviceFile struct {\nminor uint32\n}\n-func (fs *filesystem) newDeviceFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, kind vfs.DeviceKind, major, minor uint32) *inode {\n+func (fs *filesystem) newDeviceFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, kind vfs.DeviceKind, major, minor uint32, parentDir *directory) *inode {\nfile := &deviceFile{\nkind: kind,\nmajor: major,\n@@ -44,7 +44,7 @@ func (fs *filesystem) newDeviceFile(kuid auth.KUID, kgid auth.KGID, mode linux.F\ndefault:\npanic(fmt.Sprintf(\"invalid DeviceKind: %v\", kind))\n}\n- file.inode.init(file, fs, kuid, kgid, mode)\n+ file.inode.init(file, fs, kuid, kgid, mode, parentDir)\nfile.inode.nlink = 1 // from parent directory\nreturn &file.inode\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/directory.go", "new_path": "pkg/sentry/fsimpl/tmpfs/directory.go", "diff": "@@ -49,9 +49,9 @@ type directory struct {\nchildList dentryList\n}\n-func (fs *filesystem) newDirectory(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode) *directory {\n+func (fs *filesystem) newDirectory(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, parentDir *directory) *directory {\ndir := &directory{}\n- dir.inode.init(dir, fs, kuid, kgid, linux.S_IFDIR|mode)\n+ dir.inode.init(dir, fs, kuid, kgid, linux.S_IFDIR|mode, parentDir)\ndir.inode.nlink = 2 // from \".\" and parent directory or \"..\" for root\ndir.dentry.inode = &dir.inode\ndir.dentry.vfsd.Init(&dir.dentry)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -277,7 +277,7 @@ func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nreturn syserror.EMLINK\n}\nparentDir.inode.incLinksLocked() // from child's \"..\"\n- childDir := fs.newDirectory(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode)\n+ childDir := fs.newDirectory(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, parentDir)\nparentDir.insertChildLocked(&childDir.dentry, name)\nreturn nil\n})\n@@ -290,15 +290,15 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nvar childInode *inode\nswitch opts.Mode.FileType() {\ncase linux.S_IFREG:\n- childInode = fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode)\n+ childInode = fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, parentDir)\ncase linux.S_IFIFO:\n- childInode = fs.newNamedPipe(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode)\n+ childInode = fs.newNamedPipe(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, parentDir)\ncase linux.S_IFBLK:\n- childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.BlockDevice, opts.DevMajor, opts.DevMinor)\n+ childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.BlockDevice, opts.DevMajor, opts.DevMinor, parentDir)\ncase linux.S_IFCHR:\n- childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.CharDevice, opts.DevMajor, opts.DevMinor)\n+ childInode = fs.newDeviceFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, vfs.CharDevice, opts.DevMajor, opts.DevMinor, parentDir)\ncase linux.S_IFSOCK:\n- childInode = fs.newSocketFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, opts.Endpoint)\n+ childInode = fs.newSocketFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, opts.Endpoint, parentDir)\ndefault:\nreturn syserror.EINVAL\n}\n@@ -387,7 +387,7 @@ afterTrailingSymlink:\ndefer rp.Mount().EndWrite()\n// Create and open the child.\ncreds := rp.Credentials()\n- child := fs.newDentry(fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode))\n+ child := fs.newDentry(fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, opts.Mode, parentDir))\nparentDir.insertChildLocked(child, name)\nchild.IncRef()\ndefer child.DecRef(ctx)\n@@ -727,7 +727,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nfunc (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error {\nreturn fs.doCreateAt(ctx, rp, false /* dir */, func(parentDir *directory, name string) error {\ncreds := rp.Credentials()\n- child := fs.newDentry(fs.newSymlink(creds.EffectiveKUID, creds.EffectiveKGID, 0777, target))\n+ child := fs.newDentry(fs.newSymlink(creds.EffectiveKUID, creds.EffectiveKGID, 0777, target, parentDir))\nparentDir.insertChildLocked(child, name)\nreturn nil\n})\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "new_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "diff": "@@ -30,9 +30,9 @@ type namedPipe struct {\n// Preconditions:\n// * fs.mu must be locked.\n// * rp.Mount().CheckBeginWrite() has been called successfully.\n-func (fs *filesystem) newNamedPipe(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode) *inode {\n+func (fs *filesystem) newNamedPipe(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, parentDir *directory) *inode {\nfile := &namedPipe{pipe: pipe.NewVFSPipe(true /* isNamed */, pipe.DefaultPipeSize)}\n- file.inode.init(file, fs, kuid, kgid, linux.S_IFIFO|mode)\n+ file.inode.init(file, fs, kuid, kgid, linux.S_IFIFO|mode, parentDir)\nfile.inode.nlink = 1 // Only the parent has a link.\nreturn &file.inode\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -91,13 +91,13 @@ type regularFile struct {\nsize uint64\n}\n-func (fs *filesystem) newRegularFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode) *inode {\n+func (fs *filesystem) newRegularFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, parentDir *directory) *inode {\nfile := &regularFile{\nmemFile: fs.mfp.MemoryFile(),\nmemoryUsageKind: usage.Tmpfs,\nseals: linux.F_SEAL_SEAL,\n}\n- file.inode.init(file, fs, kuid, kgid, linux.S_IFREG|mode)\n+ file.inode.init(file, fs, kuid, kgid, linux.S_IFREG|mode, parentDir)\nfile.inode.nlink = 1 // from parent directory\nreturn &file.inode\n}\n@@ -116,7 +116,7 @@ func newUnlinkedRegularFileDescription(ctx context.Context, creds *auth.Credenti\npanic(\"tmpfs.newUnlinkedRegularFileDescription() called with non-tmpfs mount\")\n}\n- inode := fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, 0777)\n+ inode := fs.newRegularFile(creds.EffectiveKUID, creds.EffectiveKGID, 0777, nil /* parentDir */)\nd := fs.newDentry(inode)\ndefer d.DecRef(ctx)\nd.name = name\n@@ -443,6 +443,13 @@ func (fd *regularFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\nrw := getRegularFileReadWriter(f, offset)\nn, err := src.CopyInTo(ctx, rw)\nf.inode.touchCMtimeLocked()\n+ for {\n+ old := atomic.LoadUint32(&f.inode.mode)\n+ new := vfs.ClearSUIDAndSGID(old)\n+ if swapped := atomic.CompareAndSwapUint32(&f.inode.mode, old, new); swapped {\n+ break\n+ }\n+ }\nputRegularFileReadWriter(rw)\nreturn n, n + offset, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/socket_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/socket_file.go", "diff": "@@ -28,9 +28,9 @@ type socketFile struct {\nep transport.BoundEndpoint\n}\n-func (fs *filesystem) newSocketFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, ep transport.BoundEndpoint) *inode {\n+func (fs *filesystem) newSocketFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, ep transport.BoundEndpoint, parentDir *directory) *inode {\nfile := &socketFile{ep: ep}\n- file.inode.init(file, fs, kuid, kgid, mode)\n+ file.inode.init(file, fs, kuid, kgid, mode, parentDir)\nfile.inode.nlink = 1 // from parent directory\nreturn &file.inode\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/symlink.go", "new_path": "pkg/sentry/fsimpl/tmpfs/symlink.go", "diff": "@@ -25,11 +25,11 @@ type symlink struct {\ntarget string // immutable\n}\n-func (fs *filesystem) newSymlink(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, target string) *inode {\n+func (fs *filesystem) newSymlink(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, target string, parentDir *directory) *inode {\nlink := &symlink{\ntarget: target,\n}\n- link.inode.init(link, fs, kuid, kgid, linux.S_IFLNK|mode)\n+ link.inode.init(link, fs, kuid, kgid, linux.S_IFLNK|mode, parentDir)\nlink.inode.nlink = 1 // from parent directory\nreturn &link.inode\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -190,11 +190,11 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nvar root *dentry\nswitch rootFileType {\ncase linux.S_IFREG:\n- root = fs.newDentry(fs.newRegularFile(rootKUID, rootKGID, rootMode))\n+ root = fs.newDentry(fs.newRegularFile(rootKUID, rootKGID, rootMode, nil /* parentDir */))\ncase linux.S_IFLNK:\n- root = fs.newDentry(fs.newSymlink(rootKUID, rootKGID, rootMode, tmpfsOpts.RootSymlinkTarget))\n+ root = fs.newDentry(fs.newSymlink(rootKUID, rootKGID, rootMode, tmpfsOpts.RootSymlinkTarget, nil /* parentDir */))\ncase linux.S_IFDIR:\n- root = &fs.newDirectory(rootKUID, rootKGID, rootMode).dentry\n+ root = &fs.newDirectory(rootKUID, rootKGID, rootMode, nil /* parentDir */).dentry\ndefault:\nfs.vfsfs.DecRef(ctx)\nreturn nil, nil, fmt.Errorf(\"invalid tmpfs root file type: %#o\", rootFileType)\n@@ -385,10 +385,19 @@ type inode struct {\nconst maxLinks = math.MaxUint32\n-func (i *inode) init(impl interface{}, fs *filesystem, kuid auth.KUID, kgid auth.KGID, mode linux.FileMode) {\n+func (i *inode) init(impl interface{}, fs *filesystem, kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, parentDir *directory) {\nif mode.FileType() == 0 {\npanic(\"file type is required in FileMode\")\n}\n+\n+ // Inherit the group and setgid bit as in fs/inode.c:inode_init_owner().\n+ if parentDir != nil && parentDir.inode.mode&linux.S_ISGID == linux.S_ISGID {\n+ kgid = auth.KGID(parentDir.inode.gid)\n+ if mode&linux.S_IFDIR == linux.S_IFDIR {\n+ mode |= linux.S_ISGID\n+ }\n+ }\n+\ni.fs = fs\ni.mode = uint32(mode)\ni.uid = uint32(kuid)\n@@ -519,26 +528,15 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs.\nif err := vfs.CheckSetStat(ctx, creds, opts, mode, auth.KUID(atomic.LoadUint32(&i.uid)), auth.KGID(atomic.LoadUint32(&i.gid))); err != nil {\nreturn err\n}\n+\ni.mu.Lock()\ndefer i.mu.Unlock()\nvar (\nneedsMtimeBump bool\nneedsCtimeBump bool\n)\n+ clearSID := false\nmask := stat.Mask\n- if mask&linux.STATX_MODE != 0 {\n- ft := atomic.LoadUint32(&i.mode) & linux.S_IFMT\n- atomic.StoreUint32(&i.mode, ft|uint32(stat.Mode&^linux.S_IFMT))\n- needsCtimeBump = true\n- }\n- if mask&linux.STATX_UID != 0 {\n- atomic.StoreUint32(&i.uid, stat.UID)\n- needsCtimeBump = true\n- }\n- if mask&linux.STATX_GID != 0 {\n- atomic.StoreUint32(&i.gid, stat.GID)\n- needsCtimeBump = true\n- }\nif mask&linux.STATX_SIZE != 0 {\nswitch impl := i.impl.(type) {\ncase *regularFile:\n@@ -547,6 +545,7 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs.\nreturn err\n}\nif updated {\n+ clearSID = true\nneedsMtimeBump = true\nneedsCtimeBump = true\n}\n@@ -556,6 +555,31 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs.\nreturn syserror.EINVAL\n}\n}\n+ if mask&linux.STATX_UID != 0 {\n+ atomic.StoreUint32(&i.uid, stat.UID)\n+ needsCtimeBump = true\n+ clearSID = true\n+ }\n+ if mask&linux.STATX_GID != 0 {\n+ atomic.StoreUint32(&i.gid, stat.GID)\n+ needsCtimeBump = true\n+ clearSID = true\n+ }\n+ if mask&linux.STATX_MODE != 0 {\n+ for {\n+ old := atomic.LoadUint32(&i.mode)\n+ ft := old & linux.S_IFMT\n+ newMode := ft | uint32(stat.Mode & ^uint16(linux.S_IFMT))\n+ if clearSID {\n+ newMode = vfs.ClearSUIDAndSGID(newMode)\n+ }\n+ if swapped := atomic.CompareAndSwapUint32(&i.mode, old, newMode); swapped {\n+ clearSID = false\n+ break\n+ }\n+ }\n+ needsCtimeBump = true\n+ }\nnow := i.fs.clock.Now().Nanoseconds()\nif mask&linux.STATX_ATIME != 0 {\nif stat.Atime.Nsec == linux.UTIME_NOW {\n@@ -584,6 +608,20 @@ func (i *inode) setStat(ctx context.Context, creds *auth.Credentials, opts *vfs.\n// Ignore the ctime bump, since we just set it ourselves.\nneedsCtimeBump = false\n}\n+\n+ // We may have to clear the SUID/SGID bits, but didn't do so as part of\n+ // STATX_MODE.\n+ if clearSID {\n+ for {\n+ old := atomic.LoadUint32(&i.mode)\n+ newMode := vfs.ClearSUIDAndSGID(old)\n+ if swapped := atomic.CompareAndSwapUint32(&i.mode, old, newMode); swapped {\n+ break\n+ }\n+ }\n+ needsCtimeBump = true\n+ }\n+\nif needsMtimeBump {\natomic.StoreInt64(&i.mtime, now)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/permissions.go", "new_path": "pkg/sentry/vfs/permissions.go", "diff": "@@ -326,3 +326,20 @@ func CheckXattrPermissions(creds *auth.Credentials, ats AccessTypes, mode linux.\n}\nreturn nil\n}\n+\n+// ClearSUIDAndSGID clears the setuid and/or setgid bits after a chown or write.\n+// Depending on the mode, neither bit, only the setuid bit, or both are cleared.\n+func ClearSUIDAndSGID(mode uint32) uint32 {\n+ // Directories don't have their bits changed.\n+ if mode&linux.ModeDirectory == linux.ModeDirectory {\n+ return mode\n+ }\n+\n+ // Changing owners always disables the setuid bit. It disables\n+ // the setgid bit when the file is executable.\n+ mode &= ^uint32(linux.ModeSetUID)\n+ if sgid := uint32(linux.ModeSetGID | linux.ModeGroupExec); mode&sgid == sgid {\n+ mode &= ^uint32(linux.ModeSetGID)\n+ }\n+ return mode\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -89,7 +89,7 @@ syscall_test(\nsize = \"medium\",\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chown_test\",\n- use_tmpfs = True, # chwon tests require gofer to be running as root.\n+ use_tmpfs = True, # chown tests require gofer to be running as root.\n)\nsyscall_test(\n@@ -557,7 +557,11 @@ syscall_test(\n)\nsyscall_test(\n+ add_overlay = True,\ntest = \"//test/syscalls/linux:setgid_test\",\n+ # setgid tests require the gofer's user namespace to have multiple groups,\n+ # but bazel only provides one.\n+ use_tmpfs = True,\n)\nsyscall_test(\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/setgid.cc", "new_path": "test/syscalls/linux/setgid.cc", "diff": "@@ -86,7 +86,7 @@ class SetgidDirTest : public ::testing::Test {\noriginal_gid_ = getegid();\n// TODO(b/175325250): Enable when setgid directories are supported.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SETGID)));\ntemp_dir_ = ASSERT_NO_ERRNO_AND_VALUE(\n@@ -305,9 +305,7 @@ struct FileModeTestcase {\nclass FileModeTest : public ::testing::TestWithParam<FileModeTestcase> {};\nTEST_P(FileModeTest, WriteToFile) {\n- // TODO(b/175325250): Enable when setgid directories are supported.\n- SKIP_IF(IsRunningOnGvisor());\n-\n+ SKIP_IF(IsRunningWithVFS1());\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(\nTempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0777 /* mode */));\nauto path = JoinPath(temp_dir.path(), GetParam().name);\n@@ -330,9 +328,7 @@ TEST_P(FileModeTest, WriteToFile) {\n}\nTEST_P(FileModeTest, TruncateFile) {\n- // TODO(b/175325250): Enable when setgid directories are supported.\n- SKIP_IF(IsRunningOnGvisor());\n-\n+ SKIP_IF(IsRunningWithVFS1());\nauto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(\nTempPath::CreateDirWith(GetAbsoluteTestTmpdir(), 0777 /* mode */));\nauto path = JoinPath(temp_dir.path(), GetParam().name);\n@@ -343,6 +339,11 @@ TEST_P(FileModeTest, TruncateFile) {\nASSERT_THAT(fstat(fd.get(), &stats), SyscallSucceeds());\nEXPECT_EQ(stats.st_mode & kDirmodeMask, GetParam().mode);\n+ // Write something to the file, as truncating an empty file is a no-op.\n+ constexpr char c = 'M';\n+ ASSERT_THAT(write(fd.get(), &c, sizeof(c)),\n+ SyscallSucceedsWithValue(sizeof(c)));\n+\n// For security reasons, truncating the file clears the SUID bit, and clears\n// the SGID bit when the group executable bit is unset (which is not a true\n// SGID binary).\n" } ]
Go
Apache License 2.0
google/gvisor
Support setgid directories in tmpfs and kernfs PiperOrigin-RevId: 356868412
259,992
11.02.2021 10:58:55
28,800
192780946fdf584c5e504b24f47dbd9bd411a3a6
Allow rt_sigaction in gofer seccomp rt_sigaction may be called by Go runtime when trying to panic: https://cs.opensource.google/go/go/+/master:src/runtime/signal_unix.go;drc=ed3e4afa12d655a0c5606bcf3dd4e1cdadcb1476;bpv=1;bpt=1;l=780?q=rt_sigaction&ss=go Updates
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config.go", "new_path": "runsc/fsgofer/filter/config.go", "diff": "@@ -182,6 +182,8 @@ var allowedSyscalls = seccomp.SyscallRules{\n},\nsyscall.SYS_RENAMEAT: {},\nsyscall.SYS_RESTART_SYSCALL: {},\n+ // May be used by the runtime during panic().\n+ syscall.SYS_RT_SIGACTION: {},\nsyscall.SYS_RT_SIGPROCMASK: {},\nsyscall.SYS_RT_SIGRETURN: {},\nsyscall.SYS_SCHED_YIELD: {},\n" } ]
Go
Apache License 2.0
google/gvisor
Allow rt_sigaction in gofer seccomp rt_sigaction may be called by Go runtime when trying to panic: https://cs.opensource.google/go/go/+/master:src/runtime/signal_unix.go;drc=ed3e4afa12d655a0c5606bcf3dd4e1cdadcb1476;bpv=1;bpt=1;l=780?q=rt_sigaction&ss=go Updates #5038 PiperOrigin-RevId: 357013186
259,891
11.02.2021 11:06:56
28,800
ae8d966f5af0bba9978a1aedac64038ef65a4cc9
Assign controlling terminal when tty is opened and support NOCTTY
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/master.go", "new_path": "pkg/sentry/fs/tty/master.go", "diff": "@@ -153,7 +153,7 @@ func (mf *masterFileOperations) Write(ctx context.Context, _ *fs.File, src userm\n}\n// Ioctl implements fs.FileOperations.Ioctl.\n-func (mf *masterFileOperations) Ioctl(ctx context.Context, _ *fs.File, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+func (mf *masterFileOperations) Ioctl(ctx context.Context, file *fs.File, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n// ioctl(2) may only be called from a task goroutine.\n@@ -189,7 +189,7 @@ func (mf *masterFileOperations) Ioctl(ctx context.Context, _ *fs.File, io userme\ncase linux.TIOCSCTTY:\n// Make the given terminal the controlling terminal of the\n// calling process.\n- return 0, mf.t.setControllingTTY(ctx, args, true /* isMaster */)\n+ return 0, mf.t.setControllingTTY(ctx, args, true /* isMaster */, file.Flags().Read)\ncase linux.TIOCNOTTY:\n// Release this process's controlling terminal.\nreturn 0, mf.t.releaseControllingTTY(ctx, args, true /* isMaster */)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/replica.go", "new_path": "pkg/sentry/fs/tty/replica.go", "diff": "@@ -138,7 +138,7 @@ func (sf *replicaFileOperations) Write(ctx context.Context, _ *fs.File, src user\n}\n// Ioctl implements fs.FileOperations.Ioctl.\n-func (sf *replicaFileOperations) Ioctl(ctx context.Context, _ *fs.File, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+func (sf *replicaFileOperations) Ioctl(ctx context.Context, file *fs.File, io usermem.IO, args arch.SyscallArguments) (uintptr, error) {\nt := kernel.TaskFromContext(ctx)\nif t == nil {\n// ioctl(2) may only be called from a task goroutine.\n@@ -167,7 +167,7 @@ func (sf *replicaFileOperations) Ioctl(ctx context.Context, _ *fs.File, io userm\ncase linux.TIOCSCTTY:\n// Make the given terminal the controlling terminal of the\n// calling process.\n- return 0, sf.si.t.setControllingTTY(ctx, args, false /* isMaster */)\n+ return 0, sf.si.t.setControllingTTY(ctx, args, false /* isMaster */, file.Flags().Read)\ncase linux.TIOCNOTTY:\n// Release this process's controlling terminal.\nreturn 0, sf.si.t.releaseControllingTTY(ctx, args, false /* isMaster */)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/terminal.go", "new_path": "pkg/sentry/fs/tty/terminal.go", "diff": "@@ -64,13 +64,14 @@ func newTerminal(ctx context.Context, d *dirInodeOperations, n uint32) *Terminal\n// setControllingTTY makes tm the controlling terminal of the calling thread\n// group.\n-func (tm *Terminal) setControllingTTY(ctx context.Context, args arch.SyscallArguments, isMaster bool) error {\n+func (tm *Terminal) setControllingTTY(ctx context.Context, args arch.SyscallArguments, isMaster bool, readable bool) error {\ntask := kernel.TaskFromContext(ctx)\nif task == nil {\npanic(\"setControllingTTY must be called from a task context\")\n}\n- return task.ThreadGroup().SetControllingTTY(tm.tty(isMaster), args[2].Int())\n+ steal := args[2].Int() == 1\n+ return task.ThreadGroup().SetControllingTTY(tm.tty(isMaster), steal, readable)\n}\n// releaseControllingTTY removes tm as the controlling terminal of the calling\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/master.go", "new_path": "pkg/sentry/fsimpl/devpts/master.go", "diff": "@@ -164,10 +164,11 @@ func (mfd *masterFileDescription) Ioctl(ctx context.Context, io usermem.IO, args\ncase linux.TIOCSCTTY:\n// Make the given terminal the controlling terminal of the\n// calling process.\n- return 0, mfd.t.setControllingTTY(ctx, args, true /* isMaster */)\n+ steal := args[2].Int() == 1\n+ return 0, mfd.t.setControllingTTY(ctx, steal, true /* isMaster */, mfd.vfsfd.IsReadable())\ncase linux.TIOCNOTTY:\n// Release this process's controlling terminal.\n- return 0, mfd.t.releaseControllingTTY(ctx, args, true /* isMaster */)\n+ return 0, mfd.t.releaseControllingTTY(ctx, true /* isMaster */)\ncase linux.TIOCGPGRP:\n// Get the foreground process group.\nreturn mfd.t.foregroundProcessGroup(ctx, args, true /* isMaster */)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/replica.go", "new_path": "pkg/sentry/fsimpl/devpts/replica.go", "diff": "@@ -58,6 +58,12 @@ func (ri *replicaInode) Open(ctx context.Context, rp *vfs.ResolvingPath, d *kern\nif err := fd.vfsfd.Init(fd, opts.Flags, rp.Mount(), d.VFSDentry(), &vfs.FileDescriptionOptions{}); err != nil {\nreturn nil, err\n}\n+ if opts.Flags&linux.O_NOCTTY == 0 {\n+ // Opening a replica sets the process' controlling TTY when\n+ // possible. An error indicates it cannot be set, and is\n+ // ignored silently.\n+ _ = fd.inode.t.setControllingTTY(ctx, false /* steal */, false /* isMaster */, fd.vfsfd.IsReadable())\n+ }\nreturn &fd.vfsfd, nil\n}\n@@ -160,10 +166,11 @@ func (rfd *replicaFileDescription) Ioctl(ctx context.Context, io usermem.IO, arg\ncase linux.TIOCSCTTY:\n// Make the given terminal the controlling terminal of the\n// calling process.\n- return 0, rfd.inode.t.setControllingTTY(ctx, args, false /* isMaster */)\n+ steal := args[2].Int() == 1\n+ return 0, rfd.inode.t.setControllingTTY(ctx, steal, false /* isMaster */, rfd.vfsfd.IsReadable())\ncase linux.TIOCNOTTY:\n// Release this process's controlling terminal.\n- return 0, rfd.inode.t.releaseControllingTTY(ctx, args, false /* isMaster */)\n+ return 0, rfd.inode.t.releaseControllingTTY(ctx, false /* isMaster */)\ncase linux.TIOCGPGRP:\n// Get the foreground process group.\nreturn rfd.inode.t.foregroundProcessGroup(ctx, args, false /* isMaster */)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devpts/terminal.go", "new_path": "pkg/sentry/fsimpl/devpts/terminal.go", "diff": "@@ -54,18 +54,18 @@ func newTerminal(n uint32) *Terminal {\n// setControllingTTY makes tm the controlling terminal of the calling thread\n// group.\n-func (tm *Terminal) setControllingTTY(ctx context.Context, args arch.SyscallArguments, isMaster bool) error {\n+func (tm *Terminal) setControllingTTY(ctx context.Context, steal bool, isMaster, isReadable bool) error {\ntask := kernel.TaskFromContext(ctx)\nif task == nil {\npanic(\"setControllingTTY must be called from a task context\")\n}\n- return task.ThreadGroup().SetControllingTTY(tm.tty(isMaster), args[2].Int())\n+ return task.ThreadGroup().SetControllingTTY(tm.tty(isMaster), steal, isReadable)\n}\n// releaseControllingTTY removes tm as the controlling terminal of the calling\n// thread group.\n-func (tm *Terminal) releaseControllingTTY(ctx context.Context, args arch.SyscallArguments, isMaster bool) error {\n+func (tm *Terminal) releaseControllingTTY(ctx context.Context, isMaster bool) error {\ntask := kernel.TaskFromContext(ctx)\nif task == nil {\npanic(\"releaseControllingTTY must be called from a task context\")\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -464,7 +464,8 @@ func (fs *Filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\n// O_NOFOLLOW have no effect here (they're handled by VFS by setting\n// appropriate bits in rp), but are returned by\n// FileDescriptionImpl.StatusFlags().\n- opts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_TRUNC | linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NONBLOCK\n+ opts.Flags &= linux.O_ACCMODE | linux.O_CREAT | linux.O_EXCL | linux.O_TRUNC |\n+ linux.O_DIRECTORY | linux.O_NOFOLLOW | linux.O_NONBLOCK | linux.O_NOCTTY\nats := vfs.AccessTypesForOpenFlags(&opts)\n// Do not create new file.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/thread_group.go", "new_path": "pkg/sentry/kernel/thread_group.go", "diff": "@@ -344,7 +344,7 @@ func (tg *ThreadGroup) forEachChildThreadGroupLocked(fn func(*ThreadGroup)) {\n}\n// SetControllingTTY sets tty as the controlling terminal of tg.\n-func (tg *ThreadGroup) SetControllingTTY(tty *TTY, arg int32) error {\n+func (tg *ThreadGroup) SetControllingTTY(tty *TTY, steal bool, isReadable bool) error {\ntty.mu.Lock()\ndefer tty.mu.Unlock()\n@@ -361,6 +361,9 @@ func (tg *ThreadGroup) SetControllingTTY(tty *TTY, arg int32) error {\nreturn syserror.EINVAL\n}\n+ creds := auth.CredentialsFromContext(tg.leader)\n+ hasAdmin := creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, creds.UserNamespace.Root())\n+\n// \"If this terminal is already the controlling terminal of a different\n// session group, then the ioctl fails with EPERM, unless the caller\n// has the CAP_SYS_ADMIN capability and arg equals 1, in which case the\n@@ -368,7 +371,7 @@ func (tg *ThreadGroup) SetControllingTTY(tty *TTY, arg int32) error {\n// terminal lose it.\" - tty_ioctl(4)\nif tty.tg != nil && tg.processGroup.session != tty.tg.processGroup.session {\n// Stealing requires CAP_SYS_ADMIN in the root user namespace.\n- if creds := auth.CredentialsFromContext(tg.leader); !creds.HasCapabilityIn(linux.CAP_SYS_ADMIN, creds.UserNamespace.Root()) || arg != 1 {\n+ if !hasAdmin || !steal {\nreturn syserror.EPERM\n}\n// Steal the TTY away. Unlike TIOCNOTTY, don't send signals.\n@@ -388,6 +391,10 @@ func (tg *ThreadGroup) SetControllingTTY(tty *TTY, arg int32) error {\n}\n}\n+ if !isReadable && !hasAdmin {\n+ return syserror.EPERM\n+ }\n+\n// Set the controlling terminal and foreground process group.\ntg.tty = tty\ntg.processGroup.session.foreground = tg.processGroup\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -1441,6 +1441,7 @@ cc_binary(\n\"@com_google_absl//absl/synchronization\",\n\"@com_google_absl//absl/time\",\ngtest,\n+ \"//test/util:cleanup\",\n\"//test/util:posix_error\",\n\"//test/util:pty_util\",\n\"//test/util:test_main\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pty.cc", "new_path": "test/syscalls/linux/pty.cc", "diff": "#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/pty_util.h\"\n@@ -459,6 +460,59 @@ TEST(BasicPtyTest, OpenMasterReplica) {\nFileDescriptor replica = ASSERT_NO_ERRNO_AND_VALUE(OpenReplica(master));\n}\n+TEST(BasicPtyTest, OpenSetsControllingTTY) {\n+ SKIP_IF(IsRunningWithVFS1());\n+ // setsid either puts us in a new session or fails because we're already the\n+ // session leader. Either way, this ensures we're the session leader.\n+ setsid();\n+\n+ // Make sure we're ignoring SIGHUP, which will be sent to this process once we\n+ // disconnect they TTY.\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\n+ sa.sa_flags = 0;\n+ sigemptyset(&sa.sa_mask);\n+ struct sigaction old_sa;\n+ ASSERT_THAT(sigaction(SIGHUP, &sa, &old_sa), SyscallSucceeds());\n+ auto cleanup = Cleanup([old_sa] {\n+ EXPECT_THAT(sigaction(SIGHUP, &old_sa, NULL), SyscallSucceeds());\n+ });\n+\n+ FileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/ptmx\", O_RDWR));\n+ FileDescriptor replica =\n+ ASSERT_NO_ERRNO_AND_VALUE(OpenReplica(master, O_NONBLOCK | O_RDWR));\n+\n+ // Opening replica should make it our controlling TTY, and therefore we are\n+ // able to give it up.\n+ ASSERT_THAT(ioctl(replica.get(), TIOCNOTTY), SyscallSucceeds());\n+}\n+\n+TEST(BasicPtyTest, OpenMasterDoesNotSetsControllingTTY) {\n+ SKIP_IF(IsRunningWithVFS1());\n+ // setsid either puts us in a new session or fails because we're already the\n+ // session leader. Either way, this ensures we're the session leader.\n+ setsid();\n+ FileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/ptmx\", O_RDWR));\n+\n+ // Opening master does not set the controlling TTY, and therefore we are\n+ // unable to give it up.\n+ ASSERT_THAT(ioctl(master.get(), TIOCNOTTY), SyscallFailsWithErrno(ENOTTY));\n+}\n+\n+TEST(BasicPtyTest, OpenNOCTTY) {\n+ SKIP_IF(IsRunningWithVFS1());\n+ // setsid either puts us in a new session or fails because we're already the\n+ // session leader. Either way, this ensures we're the session leader.\n+ setsid();\n+ FileDescriptor master = ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/ptmx\", O_RDWR));\n+ FileDescriptor replica = ASSERT_NO_ERRNO_AND_VALUE(\n+ OpenReplica(master, O_NOCTTY | O_NONBLOCK | O_RDWR));\n+\n+ // Opening replica with O_NOCTTY won't make it our controlling TTY, and\n+ // therefore we are unable to give it up.\n+ ASSERT_THAT(ioctl(replica.get(), TIOCNOTTY), SyscallFailsWithErrno(ENOTTY));\n+}\n+\n// The replica entry in /dev/pts/ disappears when the master is closed, even if\n// the replica is still open.\nTEST(BasicPtyTest, ReplicaEntryGoneAfterMasterClose) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/pty_util.cc", "new_path": "test/util/pty_util.cc", "diff": "@@ -24,11 +24,16 @@ namespace gvisor {\nnamespace testing {\nPosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master) {\n+ return OpenReplica(master, O_NONBLOCK | O_RDWR | O_NOCTTY);\n+}\n+\n+PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master,\n+ int flags) {\nPosixErrorOr<int> n = ReplicaID(master);\nif (!n.ok()) {\nreturn PosixErrorOr<FileDescriptor>(n.error());\n}\n- return Open(absl::StrCat(\"/dev/pts/\", n.ValueOrDie()), O_RDWR | O_NONBLOCK);\n+ return Open(absl::StrCat(\"/dev/pts/\", n.ValueOrDie()), flags);\n}\nPosixErrorOr<int> ReplicaID(const FileDescriptor& master) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/pty_util.h", "new_path": "test/util/pty_util.h", "diff": "namespace gvisor {\nnamespace testing {\n-// Opens the replica end of the passed master as R/W and nonblocking.\n+// Opens the replica end of the passed master as R/W and nonblocking. It does\n+// not set the replica as the controlling TTY.\nPosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master);\n+// Identical to the above OpenReplica, but flags are all specified by the\n+// caller.\n+PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master,\n+ int flags);\n+\n// Get the number of the replica end of the master.\nPosixErrorOr<int> ReplicaID(const FileDescriptor& master);\n" } ]
Go
Apache License 2.0
google/gvisor
Assign controlling terminal when tty is opened and support NOCTTY PiperOrigin-RevId: 357015186
259,875
11.02.2021 12:19:48
28,800
c833eed80a4ceaf9da852ef361dd5f4864eb647d
Implement semtimedop.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64.go", "new_path": "pkg/sentry/syscalls/linux/linux64.go", "diff": "@@ -272,7 +272,7 @@ var AMD64 = &kernel.SyscallTable{\n217: syscalls.Supported(\"getdents64\", Getdents64),\n218: syscalls.Supported(\"set_tid_address\", SetTidAddress),\n219: syscalls.Supported(\"restart_syscall\", RestartSyscall),\n- 220: syscalls.PartiallySupported(\"semtimedop\", Semtimedop, \"A non-zero timeout argument isn't supported.\", []string{\"gvisor.dev/issue/137\"}),\n+ 220: syscalls.Supported(\"semtimedop\", Semtimedop),\n221: syscalls.PartiallySupported(\"fadvise64\", Fadvise64, \"Not all options are supported.\", nil),\n222: syscalls.Supported(\"timer_create\", TimerCreate),\n223: syscalls.Supported(\"timer_settime\", TimerSettime),\n@@ -620,7 +620,7 @@ var ARM64 = &kernel.SyscallTable{\n189: syscalls.ErrorWithEvent(\"msgsnd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/135\"}), // TODO(b/29354921)\n190: syscalls.Supported(\"semget\", Semget),\n191: syscalls.PartiallySupported(\"semctl\", Semctl, \"Options SEM_STAT_ANY not supported.\", nil),\n- 192: syscalls.PartiallySupported(\"semtimedop\", Semtimedop, \"A non-zero timeout argument isn't supported.\", []string{\"gvisor.dev/issue/137\"}),\n+ 192: syscalls.Supported(\"semtimedop\", Semtimedop),\n193: syscalls.PartiallySupported(\"semop\", Semop, \"Option SEM_UNDO not supported.\", nil),\n194: syscalls.PartiallySupported(\"shmget\", Shmget, \"Option SHM_HUGETLB is not supported.\", nil),\n195: syscalls.PartiallySupported(\"shmctl\", Shmctl, \"Options SHM_LOCK, SHM_UNLOCK are 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": "@@ -16,6 +16,7 @@ package linux\nimport (\n\"math\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/marshal/primitive\"\n@@ -50,24 +51,50 @@ func Semget(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n// Semtimedop handles: semop(int semid, struct sembuf *sops, size_t nsops, const struct timespec *timeout)\nfunc Semtimedop(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- // TODO(gvisor.dev/issue/137): A non-zero timeout isn't supported.\n- if args[3].Pointer() != 0 {\n- return 0, nil, syserror.ENOSYS\n- }\n+ // If the timeout argument is NULL, then semtimedop() behaves exactly like semop().\n+ if args[3].Pointer() == 0 {\nreturn Semop(t, args)\n}\n-// Semop handles: semop(int semid, struct sembuf *sops, size_t nsops)\n-func Semop(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nid := args[0].Int()\nsembufAddr := args[1].Pointer()\nnsops := args[2].SizeT()\n+ timespecAddr := args[3].Pointer()\n+ if nsops <= 0 {\n+ return 0, nil, syserror.EINVAL\n+ }\n+ if nsops > opsMax {\n+ return 0, nil, syserror.E2BIG\n+ }\n- r := t.IPCNamespace().SemaphoreRegistry()\n- set := r.FindByID(id)\n- if set == nil {\n+ ops := make([]linux.Sembuf, nsops)\n+ if _, err := linux.CopySembufSliceIn(t, sembufAddr, ops); err != nil {\n+ return 0, nil, err\n+ }\n+\n+ var timeout linux.Timespec\n+ if _, err := timeout.CopyIn(t, timespecAddr); err != nil {\n+ return 0, nil, err\n+ }\n+ if timeout.Sec < 0 || timeout.Nsec < 0 || timeout.Nsec >= 1e9 {\nreturn 0, nil, syserror.EINVAL\n}\n+\n+ if err := semTimedOp(t, id, ops, true, timeout.ToDuration()); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ return 0, nil, syserror.EAGAIN\n+ }\n+ return 0, nil, err\n+ }\n+ return 0, nil, nil\n+}\n+\n+// Semop handles: semop(int semid, struct sembuf *sops, size_t nsops)\n+func Semop(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ id := args[0].Int()\n+ sembufAddr := args[1].Pointer()\n+ nsops := args[2].SizeT()\n+\nif nsops <= 0 {\nreturn 0, nil, syserror.EINVAL\n}\n@@ -79,18 +106,25 @@ func Semop(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nif _, err := linux.CopySembufSliceIn(t, sembufAddr, ops); err != nil {\nreturn 0, nil, err\n}\n+ return 0, nil, semTimedOp(t, id, ops, false, time.Second)\n+}\n+\n+func semTimedOp(t *kernel.Task, id int32, ops []linux.Sembuf, haveTimeout bool, timeout time.Duration) error {\n+ set := t.IPCNamespace().SemaphoreRegistry().FindByID(id)\n+ if set == nil {\n+ return syserror.EINVAL\n+ }\ncreds := auth.CredentialsFromContext(t)\npid := t.Kernel().GlobalInit().PIDNamespace().IDOfThreadGroup(t.ThreadGroup())\nfor {\nch, num, err := set.ExecuteOps(t, ops, creds, int32(pid))\nif ch == nil || err != nil {\n- // We're done (either on success or a failure).\n- return 0, nil, err\n+ return err\n}\n- if err = t.Block(ch); err != nil {\n+ if _, err = t.BlockWithTimeout(ch, haveTimeout, timeout); err != nil {\nset.AbortWait(num, ch)\n- return 0, nil, err\n+ return err\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "@@ -116,6 +116,41 @@ TEST(SemaphoreTest, SemOpSingleNoBlock) {\nASSERT_THAT(semop(sem.get(), nullptr, 0), SyscallFailsWithErrno(EINVAL));\n}\n+// Tests simple timed operations that shouldn't block in a single-thread.\n+TEST(SemaphoreTest, SemTimedOpSingleNoBlock) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ struct sembuf buf = {};\n+ buf.sem_op = 1;\n+ struct timespec timeout = {};\n+ // 50 milliseconds.\n+ timeout.tv_nsec = 5e7;\n+ ASSERT_THAT(semtimedop(sem.get(), &buf, 1, &timeout), SyscallSucceeds());\n+\n+ buf.sem_op = -1;\n+ EXPECT_THAT(semtimedop(sem.get(), &buf, 1, &timeout), SyscallSucceeds());\n+\n+ buf.sem_op = 0;\n+ EXPECT_THAT(semtimedop(sem.get(), &buf, 1, &timeout), SyscallSucceeds());\n+\n+ // Error cases with invalid values.\n+ EXPECT_THAT(semtimedop(sem.get() + 1, &buf, 1, &timeout),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ buf.sem_num = 1;\n+ EXPECT_THAT(semtimedop(sem.get(), &buf, 1, &timeout),\n+ SyscallFailsWithErrno(EFBIG));\n+ buf.sem_num = 0;\n+\n+ EXPECT_THAT(semtimedop(sem.get(), nullptr, 0, &timeout),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ timeout.tv_nsec = 1e9;\n+ EXPECT_THAT(semtimedop(sem.get(), &buf, 0, &timeout),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n// Tests multiple operations that shouldn't block in a single-thread.\nTEST(SemaphoreTest, SemOpMultiNoBlock) {\nAutoSem sem(semget(IPC_PRIVATE, 4, 0600 | IPC_CREAT));\n@@ -184,6 +219,29 @@ TEST(SemaphoreTest, SemOpBlock) {\nblocked.store(0);\n}\n+// Makes a best effort attempt to ensure that operation would be timeout when\n+// being blocked.\n+TEST(SemaphoreTest, SemTimedOpBlock) {\n+ AutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n+ ASSERT_THAT(sem.get(), SyscallSucceeds());\n+\n+ ScopedThread th([&sem] {\n+ absl::SleepFor(absl::Milliseconds(100));\n+\n+ struct sembuf buf = {};\n+ buf.sem_op = 1;\n+ ASSERT_THAT(RetryEINTR(semop)(sem.get(), &buf, 1), SyscallSucceeds());\n+ });\n+\n+ struct sembuf buf = {};\n+ buf.sem_op = -1;\n+ struct timespec timeout = {};\n+ timeout.tv_nsec = 5e7;\n+ // semtimedop reaches the time limit, it fails with errno EAGAIN.\n+ ASSERT_THAT(RetryEINTR(semtimedop)(sem.get(), &buf, 1, &timeout),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n// Tests that IPC_NOWAIT returns with no wait.\nTEST(SemaphoreTest, SemOpNoBlock) {\nAutoSem sem(semget(IPC_PRIVATE, 1, 0600 | IPC_CREAT));\n" } ]
Go
Apache License 2.0
google/gvisor
Implement semtimedop. PiperOrigin-RevId: 357031904
259,891
11.02.2021 15:59:20
28,800
c39284f457383dabd52f468a10072ca6d2211cbb
Let sentry understand tcpip.ErrMalformedHeader Added a LINT IfChange/ThenChange check to catch this in the future.
[ { "change_type": "MODIFY", "old_path": "pkg/syserr/netstack.go", "new_path": "pkg/syserr/netstack.go", "diff": "@@ -21,6 +21,8 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n+// LINT.IfChange\n+\n// Mapping for tcpip.Error types.\nvar (\nErrUnknownProtocol = New((&tcpip.ErrUnknownProtocol{}).String(), linux.EINVAL)\n@@ -48,6 +50,7 @@ var (\nErrBroadcastDisabled = New((&tcpip.ErrBroadcastDisabled{}).String(), linux.EACCES)\nErrNotPermittedNet = New((&tcpip.ErrNotPermitted{}).String(), linux.EPERM)\nErrBadBuffer = New((&tcpip.ErrBadBuffer{}).String(), linux.EFAULT)\n+ ErrMalformedHeader = New((&tcpip.ErrMalformedHeader{}).String(), linux.EINVAL)\n)\n// TranslateNetstackError converts an error from the tcpip package to a sentry\n@@ -130,7 +133,11 @@ func TranslateNetstackError(err tcpip.Error) *Error {\nreturn ErrAddressFamilyNotSupported\ncase *tcpip.ErrBadBuffer:\nreturn ErrBadBuffer\n+ case *tcpip.ErrMalformedHeader:\n+ return ErrMalformedHeader\ndefault:\npanic(fmt.Sprintf(\"unknown error %T\", err))\n}\n}\n+\n+// LINT.ThenChange(../tcpip/errors.go)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/errors.go", "new_path": "pkg/tcpip/errors.go", "diff": "@@ -32,6 +32,8 @@ type Error interface {\nfmt.Stringer\n}\n+// LINT.IfChange\n+\n// ErrAborted indicates the operation was aborted.\n//\n// +stateify savable\n@@ -536,3 +538,5 @@ func (*ErrWouldBlock) IgnoreStats() bool {\nreturn true\n}\nfunc (*ErrWouldBlock) String() string { return \"operation would block\" }\n+\n+// LINT.ThenChange(../syserr/netstack.go)\n" } ]
Go
Apache License 2.0
google/gvisor
Let sentry understand tcpip.ErrMalformedHeader Added a LINT IfChange/ThenChange check to catch this in the future. PiperOrigin-RevId: 357077564
259,885
11.02.2021 19:08:18
28,800
34614c39860a7316132a2bf572366618e7a78be9
Unconditionally check for directory-ness in overlay.filesystem.UnlinkAt().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "new_path": "pkg/sentry/fsimpl/overlay/filesystem.go", "diff": "@@ -1308,8 +1308,8 @@ func (fs *filesystem) RmdirAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn err\n}\n- // Unlike UnlinkAt, we need a dentry representing the child directory being\n- // removed in order to verify that it's empty.\n+ // We need a dentry representing the child directory being removed in order\n+ // to verify that it's empty.\nchild, _, err := fs.getChildLocked(ctx, parent, name, &ds)\nif err != nil {\nreturn err\n@@ -1555,50 +1555,24 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nreturn err\n}\n- parentMode := atomic.LoadUint32(&parent.mode)\n- child := parent.children[name]\n- var childLayer lookupLayer\n- if child == nil {\n- if parentMode&linux.S_ISVTX != 0 {\n- // If the parent's sticky bit is set, we need a child dentry to get\n- // its owner.\n- child, _, err = fs.getChildLocked(ctx, parent, name, &ds)\n+ // We need a dentry representing the child being removed in order to verify\n+ // that it's not a directory.\n+ child, childLayer, err := fs.getChildLocked(ctx, parent, name, &ds)\nif err != nil {\nreturn err\n}\n- } else {\n- // Determine if the file being unlinked actually exists. Holding\n- // parent.dirMu prevents a dentry from being instantiated for the file,\n- // which in turn prevents it from being copied-up, so this result is\n- // stable.\n- childLayer, err = fs.lookupLayerLocked(ctx, parent, name)\n- if err != nil {\n- return err\n- }\n- if !childLayer.existsInOverlay() {\n- return syserror.ENOENT\n- }\n- }\n- }\n- if child != nil {\nif child.isDir() {\nreturn syserror.EISDIR\n}\nif err := parent.mayDelete(rp.Credentials(), child); err != nil {\nreturn err\n}\n- if err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil {\n- return err\n- }\n// Hold child.copyMu to prevent it from being copied-up during\n// deletion.\nchild.copyMu.RLock()\ndefer child.copyMu.RUnlock()\n- if child.upperVD.Ok() {\n- childLayer = lookupLayerUpper\n- } else {\n- childLayer = lookupLayerLower\n- }\n+ if err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil {\n+ return err\n}\npop := vfs.PathOperation{\n" } ]
Go
Apache License 2.0
google/gvisor
Unconditionally check for directory-ness in overlay.filesystem.UnlinkAt(). PiperOrigin-RevId: 357106080
259,907
11.02.2021 22:03:45
28,800
845d0a65f449ade1952568b5fc120e7cb8cd709f
[rack] TLP: ACK Processing and PTO scheduling. This change implements TLP details enumerated in Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -222,6 +222,7 @@ var Metrics = tcpip.Stats{\nRetransmits: mustCreateMetric(\"/netstack/tcp/retransmits\", \"Number of TCP segments retransmitted.\"),\nFastRecovery: mustCreateMetric(\"/netstack/tcp/fast_recovery\", \"Number of times fast recovery was used to recover from packet loss.\"),\nSACKRecovery: mustCreateMetric(\"/netstack/tcp/sack_recovery\", \"Number of times SACK recovery was used to recover from packet loss.\"),\n+ TLPRecovery: mustCreateMetric(\"/netstack/tcp/tlp_recovery\", \"Number of times tail loss probe triggers recovery from tail loss.\"),\nSlowStartRetransmits: mustCreateMetric(\"/netstack/tcp/slow_start_retransmits\", \"Number of segments retransmitted in slow start mode.\"),\nFastRetransmit: mustCreateMetric(\"/netstack/tcp/fast_retransmit\", \"Number of TCP segments which were fast retransmitted.\"),\nTimeouts: mustCreateMetric(\"/netstack/tcp/timeouts\", \"Number of times RTO expired.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1731,6 +1731,10 @@ type TCPStats struct {\n// recover from packet loss.\nSACKRecovery *StatCounter\n+ // TLPRecovery is the number of times recovery was accomplished by the tail\n+ // loss probe.\n+ TLPRecovery *StatCounter\n+\n// SlowStartRetransmits is the number of segments retransmitted in slow\n// start.\nSlowStartRetransmits *StatCounter\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack.go", "new_path": "pkg/tcpip/transport/tcp/rack.go", "diff": "@@ -263,7 +263,10 @@ func (s *sender) probeTimerExpired() tcpip.Error {\n}\n}\n- s.postXmit(dataSent)\n+ // Whether or not the probe was sent, the sender must arm the resend timer,\n+ // not the probe timer. This ensures that the sender does not send repeated,\n+ // back-to-back tail loss probes.\n+ s.postXmit(dataSent, false /* shouldScheduleProbe */)\nreturn nil\n}\n@@ -477,7 +480,5 @@ func (rc *rackControl) DoRecovery(_ *segment, fastRetransmit bool) {\nsnd.sendSegment(seg)\n}\n- // Rearm the RTO.\n- snd.resendTimer.enable(snd.rto)\n- snd.postXmit(dataSent)\n+ snd.postXmit(dataSent, true /* shouldScheduleProbe */)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/sack_recovery.go", "new_path": "pkg/tcpip/transport/tcp/sack_recovery.go", "diff": "@@ -116,5 +116,5 @@ func (sr *sackRecovery) DoRecovery(rcvdSeg *segment, fastRetransmit bool) {\n// RFC 6675 recovery algorithm step C 1-5.\nend := snd.sndUna.Add(snd.sndWnd)\ndataSent := sr.handleSACKRecovery(snd.maxPayloadSize, end)\n- snd.postXmit(dataSent)\n+ snd.postXmit(dataSent, true /* shouldScheduleProbe */)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -966,7 +966,7 @@ func (s *sender) disableZeroWindowProbing() {\ns.resendTimer.disable()\n}\n-func (s *sender) postXmit(dataSent bool) {\n+func (s *sender) postXmit(dataSent bool, shouldScheduleProbe bool) {\nif dataSent {\n// We sent data, so we should stop the keepalive timer to ensure\n// that no keepalives are sent while there is pending data.\n@@ -980,13 +980,22 @@ func (s *sender) postXmit(dataSent bool) {\ns.enableZeroWindowProbing()\n}\n- // Enable the timer if we have pending data and it's not enabled yet.\n- if !s.resendTimer.enabled() && s.sndUna != s.sndNxt {\n- s.resendTimer.enable(s.rto)\n- }\n// If we have no more pending data, start the keepalive timer.\nif s.sndUna == s.sndNxt {\ns.ep.resetKeepaliveTimer(false)\n+ } else {\n+ // Enable timers if we have pending data.\n+ if shouldScheduleProbe && s.shouldSchedulePTO() {\n+ // Schedule PTO after transmitting new data that wasn't itself a TLP probe.\n+ s.schedulePTO()\n+ } else if !s.resendTimer.enabled() {\n+ s.probeTimer.disable()\n+ if s.outstanding > 0 {\n+ // Enable the resend timer if it's not enabled yet and there is\n+ // outstanding data.\n+ s.resendTimer.enable(s.rto)\n+ }\n+ }\n}\n}\n@@ -1029,7 +1038,7 @@ func (s *sender) sendData() {\ns.writeNext = seg.Next()\n}\n- s.postXmit(dataSent)\n+ s.postXmit(dataSent, true /* shouldScheduleProbe */)\n}\nfunc (s *sender) enterRecovery() {\n@@ -1052,6 +1061,10 @@ func (s *sender) enterRecovery() {\ns.ep.stack.Stats().TCP.SACKRecovery.Increment()\n// Set TLPRxtOut to false according to\n// https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.6.1.\n+ if s.rc.tlpRxtOut {\n+ // The tail loss probe triggered recovery.\n+ s.ep.stack.Stats().TCP.TLPRecovery.Increment()\n+ }\ns.rc.tlpRxtOut = false\nreturn\n}\n@@ -1415,9 +1428,16 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\ns.updateRTO(elapsed)\n}\n+ if s.shouldSchedulePTO() {\n+ // Schedule PTO upon receiving an ACK that cumulatively acknowledges data.\n+ // See https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.5.1.\n+ s.schedulePTO()\n+ } else {\n// When an ack is received we must rearm the timer.\n// RFC 6298 5.3\n+ s.probeTimer.disable()\ns.resendTimer.enable(s.rto)\n+ }\n// Remove all acknowledged data from the write list.\nacked := s.sndUna.Size(ack)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "diff": "@@ -159,7 +159,7 @@ func TestRACKDetectReorder(t *testing.T) {\n<-probeDone\n}\n-func sendAndReceive(t *testing.T, c *context.Context, numPackets int, enableRACK bool) []byte {\n+func sendAndReceiveWithSACK(t *testing.T, c *context.Context, numPackets int, enableRACK bool) []byte {\nsetStackSACKPermitted(t, c, true)\nif enableRACK {\nsetStackRACKPermitted(t, c)\n@@ -213,6 +213,291 @@ func addDSACKSeenCheckerProbe(t *testing.T, c *context.Context, numACK int, prob\n})\n}\n+// TestRACKTLPRecovery tests that RACK sends a tail loss probe (TLP) in the\n+// case of a tail loss. This simulates a situation where the TLP is able to\n+// insinuate the SACK holes and sender is able to retransmit the rest.\n+func TestRACKTLPRecovery(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ // Send 8 packets.\n+ numPackets := 8\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Packets [6-8] are lost. Send cumulative ACK for [1-5].\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // PTO should fire and send #8 packet as a TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 7*maxPayload, maxPayload, tsOptionSize)\n+ var info tcpip.TCPInfoOption\n+ if err := c.EP.GetSockOpt(&info); err != nil {\n+ t.Fatalf(\"GetSockOpt failed: %v\", err)\n+ }\n+\n+ // Send the SACK after RTT because RACK RFC states that if the ACK for a\n+ // retransmission arrives before the smoothed RTT then the sender should not\n+ // update RACK state as it could be a spurious inference.\n+ time.Sleep(info.RTT)\n+\n+ // Okay, let the sender know we got #8 using a SACK block.\n+ eighthPStart := c.IRS.Add(1 + seqnum.Size(7*maxPayload))\n+ eighthPEnd := eighthPStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{eighthPStart, eighthPEnd}})\n+\n+ // The sender should be entering RACK based loss-recovery and sending #6 and\n+ // #7 one after another.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+ bytesRead += maxPayload\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+ bytesRead += 2 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ // One fast retransmit after the SACK.\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 1},\n+ // Recovery should be SACK recovery.\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 1},\n+ // Packets 6, 7 and 8 were retransmitted.\n+ {tcpStats.Retransmits, \"stats.TCP.Retransmits\", 3},\n+ // TLP recovery should have been detected.\n+ {tcpStats.TLPRecovery, \"stats.TCP.TLPRecovery\", 1},\n+ // No RTOs should have occurred.\n+ {tcpStats.Timeouts, \"stats.TCP.Timeouts\", 0},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n+\n+// TestRACKTLPFallbackRTO tests that RACK sends a tail loss probe (TLP) in the\n+// case of a tail loss. This simulates a situation where either the TLP or its\n+// ACK is lost. The sender should retransmit when RTO fires.\n+func TestRACKTLPFallbackRTO(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ // Send 8 packets.\n+ numPackets := 8\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Packets [6-8] are lost. Send cumulative ACK for [1-5].\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // PTO should fire and send #8 packet as a TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 7*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Either the TLP or the ACK the receiver sent with SACK blocks was lost.\n+\n+ // Confirm that RTO fires and retransmits packet #6.\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ // No fast retransmits happened.\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 0},\n+ // No SACK recovery happened.\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 0},\n+ // TLP was unsuccessful.\n+ {tcpStats.TLPRecovery, \"stats.TCP.TLPRecovery\", 0},\n+ // RTO should have fired.\n+ {tcpStats.Timeouts, \"stats.TCP.Timeouts\", 1},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n+\n+// TestNoTLPRecoveryOnDSACK tests the scenario where the sender speculates a\n+// tail loss and sends a TLP. Everything is received and acked. The probe\n+// segment is DSACKed. No fast recovery should be triggered in this case.\n+func TestNoTLPRecoveryOnDSACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ // Send 8 packets.\n+ numPackets := 8\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Packets [1-5] are received first. [6-8] took a detour and will take a\n+ // while to arrive. Ack [1-5].\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // The tail loss probe (#8 packet) is received.\n+ c.ReceiveAndCheckPacketWithOptions(data, 7*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Now that all 8 packets are received + duplicate 8th packet, send ack.\n+ bytesRead += 3 * maxPayload\n+ eighthPStart := c.IRS.Add(1 + seqnum.Size(7*maxPayload))\n+ eighthPEnd := eighthPStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{eighthPStart, eighthPEnd}})\n+\n+ // Wait for RTO and make sure that nothing else is received.\n+ var info tcpip.TCPInfoOption\n+ if err := c.EP.GetSockOpt(&info); err != nil {\n+ t.Fatalf(\"GetSockOpt failed: %v\", err)\n+ }\n+ if p := c.GetPacketWithTimeout(info.RTO); p != nil {\n+ t.Errorf(\"received an unexpected packet: %v\", p)\n+ }\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ // Make sure no recovery was entered.\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 0},\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 0},\n+ {tcpStats.TLPRecovery, \"stats.TCP.TLPRecovery\", 0},\n+ // RTO should not have fired.\n+ {tcpStats.Timeouts, \"stats.TCP.Timeouts\", 0},\n+ // Only #8 was retransmitted.\n+ {tcpStats.Retransmits, \"stats.TCP.Retransmits\", 1},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n+\n+// TestNoTLPOnSACK tests the scenario where there is not exactly a tail loss\n+// due to the presence of multiple SACK holes. In such a scenario, TLP should\n+// not be sent.\n+func TestNoTLPOnSACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ // Send 8 packets.\n+ numPackets := 8\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Packets [1-5] and #7 were received. #6 and #8 were dropped.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 5 * maxPayload\n+ seventhStart := c.IRS.Add(1 + seqnum.Size(6*maxPayload))\n+ seventhEnd := seventhStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{seventhStart, seventhEnd}})\n+\n+ // The sender should retransmit #6. If the sender sends a TLP, then #8 will\n+ // received and fail this test.\n+ c.ReceiveAndCheckPacketWithOptions(data, 5*maxPayload, maxPayload, tsOptionSize)\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ // #6 was retransmitted due to SACK recovery.\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 1},\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 1},\n+ {tcpStats.TLPRecovery, \"stats.TCP.TLPRecovery\", 0},\n+ // RTO should not have fired.\n+ {tcpStats.Timeouts, \"stats.TCP.Timeouts\", 0},\n+ // Only #6 was retransmitted.\n+ {tcpStats.Retransmits, \"stats.TCP.Retransmits\", 1},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n+\n+// TestRACKOnePacketTailLoss tests the trivial case of a tail loss of only one\n+// packet. The probe should itself repairs the loss instead of having to go\n+// into any recovery.\n+func TestRACKOnePacketTailLoss(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ // Send 3 packets.\n+ numPackets := 3\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Packets [1-2] are received. #3 is lost.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ bytesRead := 2 * maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ // PTO should fire and send #3 packet as a TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 2*maxPayload, maxPayload, tsOptionSize)\n+ bytesRead += maxPayload\n+ c.SendAck(seq, bytesRead)\n+\n+ metricPollFn := func() error {\n+ tcpStats := c.Stack().Stats().TCP\n+ stats := []struct {\n+ stat *tcpip.StatCounter\n+ name string\n+ want uint64\n+ }{\n+ // #3 was retransmitted as TLP.\n+ {tcpStats.FastRetransmit, \"stats.TCP.FastRetransmit\", 0},\n+ {tcpStats.SACKRecovery, \"stats.TCP.SACKRecovery\", 0},\n+ {tcpStats.TLPRecovery, \"stats.TCP.TLPRecovery\", 0},\n+ // RTO should not have fired.\n+ {tcpStats.Timeouts, \"stats.TCP.Timeouts\", 0},\n+ // Only #3 was retransmitted.\n+ {tcpStats.Retransmits, \"stats.TCP.Retransmits\", 1},\n+ }\n+ for _, s := range stats {\n+ if got, want := s.stat.Value(), s.want; got != want {\n+ return fmt.Errorf(\"got %s.Value() = %d, want = %d\", s.name, got, want)\n+ }\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n+}\n+\n// TestRACKDetectDSACK tests that RACK detects DSACK with duplicate segments.\n// See: https://tools.ietf.org/html/rfc2883#section-4.1.1.\nfunc TestRACKDetectDSACK(t *testing.T) {\n@@ -224,22 +509,24 @@ func TestRACKDetectDSACK(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 8\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n- // Cumulative ACK for [1-5] packets.\n+ // Cumulative ACK for [1-5] packets and SACK #8 packet (to prevent TLP).\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nbytesRead := 5 * maxPayload\n- c.SendAck(seq, bytesRead)\n+ eighthPStart := c.IRS.Add(1 + seqnum.Size(7*maxPayload))\n+ eighthPEnd := eighthPStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{eighthPStart, eighthPEnd}})\n- // Expect retransmission of #6 packet.\n+ // Expect retransmission of #6 packet after RTO expires.\nc.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n// Send DSACK block for #6 packet indicating both\n// initial and retransmitted packet are received and\n- // packets [1-7] are received.\n- start := c.IRS.Add(seqnum.Size(bytesRead))\n+ // packets [1-8] are received.\n+ start := c.IRS.Add(1 + seqnum.Size(bytesRead))\nend := start.Add(maxPayload)\n- bytesRead += 2 * maxPayload\n+ bytesRead += 3 * maxPayload\nc.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}})\n// Wait for the probe function to finish processing the\n@@ -265,12 +552,14 @@ func TestRACKDetectDSACKWithOutOfOrder(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 10\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n- // Cumulative ACK for [1-5] packets.\n+ // Cumulative ACK for [1-5] packets and SACK for #7 packet (to prevent TLP).\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nbytesRead := 5 * maxPayload\n- c.SendAck(seq, bytesRead)\n+ seventhPStart := c.IRS.Add(1 + seqnum.Size(6*maxPayload))\n+ seventhPEnd := seventhPStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{seventhPStart, seventhPEnd}})\n// Expect retransmission of #6 packet.\nc.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n@@ -278,12 +567,12 @@ func TestRACKDetectDSACKWithOutOfOrder(t *testing.T) {\n// Send DSACK block for #6 packet indicating both\n// initial and retransmitted packet are received and\n// packets [1-7] are received.\n- start := c.IRS.Add(seqnum.Size(bytesRead))\n+ start := c.IRS.Add(1 + seqnum.Size(bytesRead))\nend := start.Add(maxPayload)\nbytesRead += 2 * maxPayload\n- // Send DSACK block for #6 along with out of\n- // order #9 packet is received.\n- start1 := c.IRS.Add(seqnum.Size(bytesRead) + maxPayload)\n+ // Send DSACK block for #6 along with SACK for out of\n+ // order #9 packet.\n+ start1 := c.IRS.Add(1 + seqnum.Size(bytesRead) + maxPayload)\nend1 := start1.Add(maxPayload)\nc.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start, end}, {start1, end1}})\n@@ -310,7 +599,7 @@ func TestRACKDetectDSACKWithOutOfOrderDup(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 10\n- sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// ACK [1-5] packets.\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n@@ -354,7 +643,7 @@ func TestRACKDetectDSACKSingleDup(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 4\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// Send ACK for #1 packet.\nbytesRead := maxPayload\n@@ -403,7 +692,7 @@ func TestRACKDetectDSACKDupWithCumulativeACK(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 6\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// Send ACK for #1 packet.\nbytesRead := maxPayload\n@@ -457,7 +746,7 @@ func TestRACKDetectDSACKDup(t *testing.T) {\naddDSACKSeenCheckerProbe(t, c, ackNumToVerify, probeDone)\nnumPackets := 7\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// Send ACK for #1 packet.\nbytesRead := maxPayload\n@@ -525,12 +814,14 @@ func TestRACKWithInvalidDSACKBlock(t *testing.T) {\n})\nnumPackets := 10\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n- // Cumulative ACK for [1-5] packets.\n+ // Cumulative ACK for [1-5] packets and SACK for #7 packet (to prevent TLP).\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nbytesRead := 5 * maxPayload\n- c.SendAck(seq, bytesRead)\n+ seventhPStart := c.IRS.Add(1 + seqnum.Size(6*maxPayload))\n+ seventhPEnd := seventhPStart.Add(maxPayload)\n+ c.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{seventhPStart, seventhPEnd}})\n// Expect retransmission of #6 packet.\nc.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n@@ -538,12 +829,12 @@ func TestRACKWithInvalidDSACKBlock(t *testing.T) {\n// Send DSACK block for #6 packet indicating both\n// initial and retransmitted packet are received and\n// packets [1-7] are received.\n- start := c.IRS.Add(seqnum.Size(bytesRead))\n+ start := c.IRS.Add(1 + seqnum.Size(bytesRead))\nend := start.Add(maxPayload)\nbytesRead += 2 * maxPayload\n- // Send DSACK block as second block.\n- start1 := c.IRS.Add(seqnum.Size(bytesRead) + maxPayload)\n+ // Send DSACK block as second block. The first block is a SACK for #9 packet.\n+ start1 := c.IRS.Add(1 + seqnum.Size(bytesRead) + maxPayload)\nend1 := start1.Add(maxPayload)\nc.SendAckWithSACK(seq, bytesRead, []header.SACKBlock{{start1, end1}, {start, end}})\n@@ -588,7 +879,7 @@ func TestRACKCheckReorderWindow(t *testing.T) {\naddReorderWindowCheckerProbe(c, ackNumToVerify, probeDone)\nconst numPackets = 7\n- sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// Send ACK for #1 packet.\nbytesRead := maxPayload\n@@ -617,7 +908,7 @@ func TestRACKWithDuplicateACK(t *testing.T) {\ndefer c.Cleanup()\nconst numPackets = 4\n- data := sendAndReceive(t, c, numPackets, true /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n// Send three duplicate ACKs to trigger fast recovery. The first\n// segment is considered as lost and will be retransmitted after\n@@ -680,7 +971,7 @@ func TestRACKUpdateSackedOut(t *testing.T) {\nackNum++\n})\n- sendAndReceive(t, c, 8, true /* enableRACK */)\n+ sendAndReceiveWithSACK(t, c, 8, true /* enableRACK */)\n// ACK for [3-5] packets.\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_sack_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_sack_test.go", "diff": "@@ -409,6 +409,7 @@ func TestSACKRecovery(t *testing.T) {\n}\n// Do slow start for a few iterations.\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nexpected := tcp.InitialCwnd\nbytesRead := 0\nfor i := 0; i < iterations; i++ {\n@@ -416,7 +417,7 @@ func TestSACKRecovery(t *testing.T) {\nif i > 0 {\n// Acknowledge all the data received so far if not on\n// first iteration.\n- c.SendAck(790, bytesRead)\n+ c.SendAck(seq, bytesRead)\n}\n// Read all packets expected on this iteration. Don't\n@@ -438,7 +439,7 @@ func TestSACKRecovery(t *testing.T) {\nstart := c.IRS.Add(seqnum.Size(rtxOffset) + 30 + 1)\nend := start.Add(10)\nfor i := 0; i < 3; i++ {\n- c.SendAckWithSACK(790, rtxOffset, []header.SACKBlock{{start, end}})\n+ c.SendAckWithSACK(seq, rtxOffset, []header.SACKBlock{{start, end}})\nend = end.Add(10)\n}\n@@ -475,7 +476,7 @@ func TestSACKRecovery(t *testing.T) {\n// the cwnd at this point after entering recovery should be half of the\n// outstanding number of packets in flight.\nfor i := 0; i < 7; i++ {\n- c.SendAckWithSACK(790, rtxOffset, []header.SACKBlock{{start, end}})\n+ c.SendAckWithSACK(seq, rtxOffset, []header.SACKBlock{{start, end}})\nend = end.Add(10)\n}\n@@ -497,7 +498,7 @@ func TestSACKRecovery(t *testing.T) {\n// segment is retransmitted per ACK.\nstart = c.IRS.Add(seqnum.Size(rtxOffset) + 30 + 1)\nend = start.Add(60)\n- c.SendAckWithSACK(790, rtxOffset, []header.SACKBlock{{start, end}})\n+ c.SendAckWithSACK(seq, rtxOffset, []header.SACKBlock{{start, end}})\n// At this point, we acked expected/2 packets and we SACKED 6 packets and\n// 3 segments were considered lost due to the SACK block we sent.\n@@ -557,7 +558,7 @@ func TestSACKRecovery(t *testing.T) {\nc.CheckNoPacketTimeout(\"More packets received than expected during recovery after partial ack for this cwnd.\", 50*time.Millisecond)\n// Acknowledge all pending data to recover point.\n- c.SendAck(790, recover)\n+ c.SendAck(seq, recover)\n// At this point, the cwnd should reset to expected/2 and there are 9\n// packets outstanding.\n@@ -579,7 +580,7 @@ func TestSACKRecovery(t *testing.T) {\nc.CheckNoPacketTimeout(fmt.Sprintf(\"More packets received(after deflation) than expected %d for this cwnd and iteration: %d.\", expected, i), 50*time.Millisecond)\n// Acknowledge all the data received so far.\n- c.SendAck(790, bytesRead)\n+ c.SendAck(seq, bytesRead)\n// In cogestion avoidance, the packets trains increase by 1 in\n// each iteration.\n@@ -603,7 +604,7 @@ func TestRecoveryEntry(t *testing.T) {\ndefer c.Cleanup()\nnumPackets := 5\n- data := sendAndReceive(t, c, numPackets, false /* enableRACK */)\n+ data := sendAndReceiveWithSACK(t, c, numPackets, false /* enableRACK */)\n// Ack #1 packet.\nseq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n" } ]
Go
Apache License 2.0
google/gvisor
[rack] TLP: ACK Processing and PTO scheduling. This change implements TLP details enumerated in https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.5.3 Fixes #5085 PiperOrigin-RevId: 357125037
259,853
12.02.2021 10:56:15
28,800
a6d813ad55ae80a2c4173fc3fd3961236327cf8b
tests: getsockname expects that addrlen will be initialized
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket.cc", "new_path": "test/syscalls/linux/udp_socket.cc", "diff": "@@ -2131,8 +2131,8 @@ TEST(UdpInet6SocketTest, ConnectInet4Sockaddr) {\nreinterpret_cast<const struct sockaddr*>(&connect_sockaddr),\nsizeof(sockaddr_in)),\nSyscallSucceeds());\n- socklen_t len;\nsockaddr_storage sockname;\n+ socklen_t len = sizeof(sockaddr_storage);\nASSERT_THAT(getsockname(sock_.get(),\nreinterpret_cast<struct sockaddr*>(&sockname), &len),\nSyscallSucceeds());\n" } ]
Go
Apache License 2.0
google/gvisor
tests: getsockname expects that addrlen will be initialized PiperOrigin-RevId: 357224877
259,975
12.02.2021 11:25:53
28,800
ba51999fa65d9a5a87b4d9848a6e2573a8812e8d
Fix bug with iperf and don't profile runc. Fix issue with iperf where b.N wasn't changing across runs. Also, if the given runtime is runc/not given, don't run a profile against it.
[ { "change_type": "MODIFY", "old_path": "pkg/test/dockerutil/container.go", "new_path": "pkg/test/dockerutil/container.go", "diff": "@@ -216,7 +216,7 @@ func (c *Container) Create(ctx context.Context, r RunOpts, args ...string) error\n}\nfunc (c *Container) create(ctx context.Context, profileImage string, conf *container.Config, hostconf *container.HostConfig, netconf *network.NetworkingConfig) error {\n- if c.runtime != \"\" {\n+ if c.runtime != \"\" && c.runtime != \"runc\" {\n// Use the image name as provided here; which normally represents the\n// unmodified \"basic/alpine\" image name. This should be easy to grok.\nc.profileInit(profileImage)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -25,10 +25,6 @@ import (\n)\nfunc BenchmarkIperf(b *testing.B) {\n- iperf := tools.Iperf{\n- Num: b.N,\n- }\n-\nclientMachine, err := harness.GetMachine()\nif err != nil {\nb.Fatalf(\"failed to get machine: %v\", err)\n@@ -93,6 +89,10 @@ func BenchmarkIperf(b *testing.B) {\nb.Fatalf(\"failed to wait for server: %v\", err)\n}\n+ iperf := tools.Iperf{\n+ Num: b.N,\n+ }\n+\n// Run the client.\nb.ResetTimer()\nout, err := client.Run(ctx, dockerutil.RunOpts{\n@@ -103,6 +103,7 @@ func BenchmarkIperf(b *testing.B) {\n}\nb.StopTimer()\niperf.Report(b, out)\n+ b.StartTimer()\n})\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix bug with iperf and don't profile runc. Fix issue with iperf where b.N wasn't changing across runs. Also, if the given runtime is runc/not given, don't run a profile against it. PiperOrigin-RevId: 357231450
259,985
12.02.2021 12:11:03
28,800
c99ad8d541670e7fec7480b97d6d258460f041e3
Add reference to gsoc 2021 proposal page for website.
[ { "change_type": "MODIFY", "old_path": "g3doc/proposals/BUILD", "new_path": "g3doc/proposals/BUILD", "diff": "@@ -10,7 +10,7 @@ doc(\nsrc = \"gsoc-2021-ideas.md\",\ncategory = \"Project\",\ninclude_in_menu = False,\n- permalink = \"/community/gsoc_2021\",\n+ permalink = \"/community/gsoc_2021/\",\nsubcategory = \"Community\",\nweight = \"99\",\n)\n" }, { "change_type": "MODIFY", "old_path": "website/BUILD", "new_path": "website/BUILD", "diff": "@@ -147,6 +147,7 @@ docs(\n\"//g3doc/architecture_guide:platforms\",\n\"//g3doc/architecture_guide:resources\",\n\"//g3doc/architecture_guide:security\",\n+ \"//g3doc/proposals:gsoc_2021\",\n\"//g3doc/user_guide:FAQ\",\n\"//g3doc/user_guide:checkpoint_restore\",\n\"//g3doc/user_guide:compatibility\",\n" } ]
Go
Apache License 2.0
google/gvisor
Add reference to gsoc 2021 proposal page for website. PiperOrigin-RevId: 357241880
259,975
12.02.2021 12:53:51
28,800
58a0a66900b6f38c8eee638a7c249bcc0a1bd9be
Rename params for iperf and tensorflow. Rename operation params in iperf and tensorflow to match other similar benchmarks.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/BUILD", "new_path": "test/benchmarks/ml/BUILD", "diff": "@@ -18,5 +18,6 @@ benchmark_test(\ndeps = [\n\"//pkg/test/dockerutil\",\n\"//test/benchmarks/harness\",\n+ \"//test/benchmarks/tools\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/ml/tensorflow_test.go", "new_path": "test/benchmarks/ml/tensorflow_test.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/test/dockerutil\"\n\"gvisor.dev/gvisor/test/benchmarks/harness\"\n+ \"gvisor.dev/gvisor/test/benchmarks/tools\"\n)\n// BenchmarkTensorflow runs workloads from a TensorFlow tutorial.\n@@ -43,7 +44,15 @@ func BenchmarkTensorflow(b *testing.B) {\ndefer machine.CleanUp()\nfor name, workload := range workloads {\n- b.Run(name, func(b *testing.B) {\n+ runName, err := tools.ParametersToName(tools.Parameter{\n+ Name: \"operation\",\n+ Value: name,\n+ })\n+ if err != nil {\n+ b.Fatalf(\"Faile to parse param: %v\", err)\n+ }\n+\n+ b.Run(runName, func(b *testing.B) {\nctx := context.Background()\nb.ResetTimer()\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -56,7 +56,14 @@ func BenchmarkIperf(b *testing.B) {\nserverFunc: serverMachine.GetContainer,\n},\n} {\n- b.Run(bm.name, func(b *testing.B) {\n+ name, err := tools.ParametersToName(tools.Parameter{\n+ Name: \"operation\",\n+ Value: bm.name,\n+ })\n+ if err != nil {\n+ b.Fatalf(\"Failed to parse parameters: %v\", err)\n+ }\n+ b.Run(name, func(b *testing.B) {\n// Set up the containers.\nserver := bm.serverFunc(ctx, b)\ndefer server.CleanUp(ctx)\n" } ]
Go
Apache License 2.0
google/gvisor
Rename params for iperf and tensorflow. Rename operation params in iperf and tensorflow to match other similar benchmarks. PiperOrigin-RevId: 357250304
259,896
12.02.2021 15:23:52
28,800
33c617cae3d6e5261e67090faf52c4101f5b7713
Remove packetimpact test tcp_reordering Remove flaky tcp_reordering_test as it does not check reordering. We have added new reorder tests in tcp_rack_test.go
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/runner/defs.bzl", "new_path": "test/packetimpact/runner/defs.bzl", "diff": "@@ -180,11 +180,6 @@ ALL_TESTS = [\nPacketimpactTestInfo(\nname = \"udp_icmp_error_propagation\",\n),\n- PacketimpactTestInfo(\n- name = \"tcp_reordering\",\n- # TODO(b/139368047): Fix netstack then remove the line below.\n- expect_netstack_failure = True,\n- ),\nPacketimpactTestInfo(\nname = \"tcp_window_shrink\",\n),\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -59,17 +59,6 @@ packetimpact_testbench(\n],\n)\n-packetimpact_testbench(\n- name = \"tcp_reordering\",\n- srcs = [\"tcp_reordering_test.go\"],\n- deps = [\n- \"//pkg/tcpip/header\",\n- \"//pkg/tcpip/seqnum\",\n- \"//test/packetimpact/testbench\",\n- \"@org_golang_x_sys//unix:go_default_library\",\n- ],\n-)\n-\npacketimpact_testbench(\nname = \"tcp_window_shrink\",\nsrcs = [\"tcp_window_shrink_test.go\"],\n" }, { "change_type": "DELETE", "old_path": "test/packetimpact/tests/tcp_reordering_test.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 reordering_test\n-\n-import (\n- \"flag\"\n- \"testing\"\n- \"time\"\n-\n- \"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/tcpip/header\"\n- \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n- \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n-)\n-\n-func init() {\n- testbench.Initialize(flag.CommandLine)\n-}\n-\n-func TestReorderingWindow(t *testing.T) {\n- dut := testbench.NewDUT(t)\n- listenFd, remotePort := dut.CreateListener(t, unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n- defer dut.Close(t, listenFd)\n- conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{SrcPort: &remotePort})\n- defer conn.Close(t)\n-\n- // Enable SACK.\n- opts := make([]byte, 40)\n- optsOff := 0\n- optsOff += header.EncodeNOP(opts[optsOff:])\n- optsOff += header.EncodeNOP(opts[optsOff:])\n- optsOff += header.EncodeSACKPermittedOption(opts[optsOff:])\n-\n- // Ethernet guarantees that the MTU is at least 1500 bytes.\n- const minMTU = 1500\n- const mss = minMTU - header.IPv4MinimumSize - header.TCPMinimumSize\n- optsOff += header.EncodeMSSOption(mss, opts[optsOff:])\n-\n- conn.ConnectWithOptions(t, opts[:optsOff])\n-\n- acceptFd, _ := dut.Accept(t, listenFd)\n- defer dut.Close(t, acceptFd)\n-\n- if testbench.Native {\n- // Linux has changed its handling of reordering, force the old behavior.\n- dut.SetSockOpt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_CONGESTION, []byte(\"reno\"))\n- }\n-\n- pls := dut.GetSockOptInt(t, acceptFd, unix.IPPROTO_TCP, unix.TCP_MAXSEG)\n- if !testbench.Native {\n- // netstack does not impliment TCP_MAXSEG correctly. Fake it\n- // here. Netstack uses the max SACK size which is 32. The MSS\n- // option is 8 bytes, making the total 36 bytes.\n- pls = mss - 36\n- }\n-\n- payload := make([]byte, pls)\n-\n- seqNum1 := *conn.RemoteSeqNum(t)\n- const numPkts = 10\n- // Send some packets, checking that we receive each.\n- for i, sn := 0, seqNum1; i < numPkts; i++ {\n- dut.Send(t, acceptFd, payload, 0)\n-\n- gotOne, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(sn))}, time.Second)\n- sn.UpdateForward(seqnum.Size(len(payload)))\n- if err != nil {\n- t.Fatalf(\"Expect #%d: %s\", i+1, err)\n- continue\n- }\n- if gotOne == nil {\n- t.Fatalf(\"#%d: expected a packet within a second but got none\", i+1)\n- }\n- }\n-\n- seqNum2 := *conn.RemoteSeqNum(t)\n-\n- // SACK packets #2-4.\n- sackBlock := make([]byte, 40)\n- sbOff := 0\n- sbOff += header.EncodeNOP(sackBlock[sbOff:])\n- sbOff += header.EncodeNOP(sackBlock[sbOff:])\n- sbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n- seqNum1.Add(seqnum.Size(len(payload))),\n- seqNum1.Add(seqnum.Size(4 * len(payload))),\n- }}, sackBlock[sbOff:])\n- conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1)), Options: sackBlock[:sbOff]})\n-\n- // ACK first packet.\n- conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum1) + uint32(len(payload)))})\n-\n- // Check for retransmit.\n- gotOne, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(seqNum1))}, time.Second)\n- if err != nil {\n- t.Error(\"Expect for retransmit:\", err)\n- }\n- if gotOne == nil {\n- t.Error(\"expected a retransmitted packet within a second but got none\")\n- }\n-\n- // ACK all send packets with a DSACK block for packet #1. This tells\n- // the other end that we got both the original and retransmit for\n- // packet #1.\n- dsackBlock := make([]byte, 40)\n- dsbOff := 0\n- dsbOff += header.EncodeNOP(dsackBlock[dsbOff:])\n- dsbOff += header.EncodeNOP(dsackBlock[dsbOff:])\n- dsbOff += header.EncodeSACKBlocks([]header.SACKBlock{{\n- seqNum1.Add(seqnum.Size(len(payload))),\n- seqNum1.Add(seqnum.Size(4 * len(payload))),\n- }}, dsackBlock[dsbOff:])\n-\n- conn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck), AckNum: testbench.Uint32(uint32(seqNum2)), Options: dsackBlock[:dsbOff]})\n-\n- // Send half of the original window of packets, checking that we\n- // received each.\n- for i, sn := 0, seqNum2; i < numPkts/2; i++ {\n- dut.Send(t, acceptFd, payload, 0)\n-\n- gotOne, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(sn))}, time.Second)\n- sn.UpdateForward(seqnum.Size(len(payload)))\n- if err != nil {\n- t.Fatalf(\"Expect #%d: %s\", i+1, err)\n- continue\n- }\n- if gotOne == nil {\n- t.Fatalf(\"#%d: expected a packet within a second but got none\", i+1)\n- }\n- }\n-\n- if !testbench.Native {\n- // The window should now be halved, so we should receive any\n- // more, even if we send them.\n- dut.Send(t, acceptFd, payload, 0)\n- if got, err := conn.Expect(t, testbench.TCP{}, 100*time.Millisecond); got != nil || err == nil {\n- t.Fatalf(\"expected no packets within 100 millisecond, but got one: %s\", got)\n- }\n- return\n- }\n-\n- // Linux reduces the window by three. Check that we can receive the rest.\n- for i, sn := 0, seqNum2.Add(seqnum.Size(numPkts/2*len(payload))); i < 2; i++ {\n- dut.Send(t, acceptFd, payload, 0)\n-\n- gotOne, err := conn.Expect(t, testbench.TCP{SeqNum: testbench.Uint32(uint32(sn))}, time.Second)\n- sn.UpdateForward(seqnum.Size(len(payload)))\n- if err != nil {\n- t.Fatalf(\"Expect #%d: %s\", i+1, err)\n- continue\n- }\n- if gotOne == nil {\n- t.Fatalf(\"#%d: expected a packet within a second but got none\", i+1)\n- }\n- }\n-\n- // The window should now be full.\n- dut.Send(t, acceptFd, payload, 0)\n- if got, err := conn.Expect(t, testbench.TCP{}, 100*time.Millisecond); got != nil || err == nil {\n- t.Fatalf(\"expected no packets within 100 millisecond, but got one: %s\", got)\n- }\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove packetimpact test tcp_reordering Remove flaky tcp_reordering_test as it does not check reordering. We have added new reorder tests in tcp_rack_test.go PiperOrigin-RevId: 357278769
259,858
12.02.2021 17:11:14
28,800
3ef012944d32313cee4df244585f48e8d4fd8e9e
Stop the control server only once. Operations are now shut down automatically by the main Stop command, and it is not necessary to call Stop during Destroy. Fixes
[ { "change_type": "MODIFY", "old_path": "runsc/boot/loader.go", "new_path": "runsc/boot/loader.go", "diff": "@@ -477,14 +477,16 @@ func createProcessArgs(id string, spec *specs.Spec, creds *auth.Credentials, k *\n// been closed. For that reason, this should NOT be called in a defer, because\n// a panic in a control server rpc would then hang forever.\nfunc (l *Loader) Destroy() {\n- if l.ctrl != nil {\n- l.ctrl.srv.Stop()\n- }\nif l.stopSignalForwarding != nil {\nl.stopSignalForwarding()\n}\nl.watchdog.Stop()\n+ // Stop the control server. This will indirectly stop any\n+ // long-running control operations that are in flight, e.g.\n+ // profiling operations.\n+ l.ctrl.stop()\n+\n// Release all kernel resources. This is only safe after we can no longer\n// save/restore.\nl.k.Release()\n@@ -1055,9 +1057,6 @@ func (l *Loader) WaitExit() kernel.ExitStatus {\n// Wait for container.\nl.k.WaitExited()\n- // Stop the control server.\n- l.ctrl.stop()\n-\n// Check all references.\nrefs.OnExit()\n" } ]
Go
Apache License 2.0
google/gvisor
Stop the control server only once. Operations are now shut down automatically by the main Stop command, and it is not necessary to call Stop during Destroy. Fixes #5454 PiperOrigin-RevId: 357295930
259,896
17.02.2021 14:23:15
28,800
3145fe1d1e99746fe39aa68e6e00f77f6fd27fb9
Use TCP_INFO to get RTO in tcp_retransmits_test TCP_INFO is used to get the RTO instead of calculating it manually.
[ { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/BUILD", "new_path": "test/packetimpact/tests/BUILD", "diff": "@@ -103,7 +103,10 @@ packetimpact_testbench(\nname = \"tcp_retransmits\",\nsrcs = [\"tcp_retransmits_test.go\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/usermem\",\n\"//test/packetimpact/testbench\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n" }, { "change_type": "MODIFY", "old_path": "test/packetimpact/tests/tcp_retransmits_test.go", "new_path": "test/packetimpact/tests/tcp_retransmits_test.go", "diff": "@@ -20,7 +20,10 @@ import (\n\"time\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n@@ -28,6 +31,16 @@ func init() {\ntestbench.Initialize(flag.CommandLine)\n}\n+func getRTO(t *testing.T, dut testbench.DUT, acceptFd int32) (rto time.Duration) {\n+ info := linux.TCPInfo{}\n+ infoBytes := dut.GetSockOpt(t, acceptFd, unix.SOL_TCP, unix.TCP_INFO, int32(linux.SizeOfTCPInfo))\n+ if got, want := len(infoBytes), linux.SizeOfTCPInfo; got != want {\n+ t.Fatalf(\"unexpected size for TCP_INFO, got %d bytes want %d bytes\", got, want)\n+ }\n+ binary.Unmarshal(infoBytes, usermem.ByteOrder, &info)\n+ return time.Duration(info.RTO) * time.Microsecond\n+}\n+\n// TestRetransmits tests retransmits occur at exponentially increasing\n// time intervals.\nfunc TestRetransmits(t *testing.T) {\n@@ -55,29 +68,29 @@ func TestRetransmits(t *testing.T) {\n// we can skip sending this ACK.\nconn.Send(t, testbench.TCP{Flags: testbench.Uint8(header.TCPFlagAck)})\n- startRTO := time.Second\n- current := startRTO\n- first := time.Now()\n+ const timeoutCorrection = time.Second\n+ const diffCorrection = time.Millisecond\n+ rto := getRTO(t, dut, acceptFd)\n+ timeout := rto + timeoutCorrection\n+\n+ startTime := time.Now()\ndut.Send(t, acceptFd, sampleData, 0)\nseq := testbench.Uint32(uint32(*conn.RemoteSeqNum(t)))\n- if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: seq}, samplePayload, startRTO); err != nil {\n+ if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: seq}, samplePayload, timeout); err != nil {\nt.Fatalf(\"expected payload was not received: %s\", err)\n}\n+\n// Expect retransmits of the same segment.\nfor i := 0; i < 5; i++ {\n- start := time.Now()\n- if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: seq}, samplePayload, 2*current); err != nil {\n- t.Fatalf(\"expected payload was not received: %s loop %d\", err, i)\n- }\n- if i == 0 {\n- startRTO = time.Now().Sub(first)\n- current = 2 * startRTO\n- continue\n+ if _, err := conn.ExpectData(t, &testbench.TCP{SeqNum: seq}, samplePayload, timeout); err != nil {\n+ t.Fatalf(\"expected payload was not received within %d loop %d err %s\", timeout, i, err)\n}\n- // Check if the probes came at exponentially increasing intervals.\n- if p := time.Since(start); p < current-startRTO {\n- t.Fatalf(\"retransmit came sooner interval %d probe %d\", p, i)\n+\n+ if diff := time.Since(startTime); diff+diffCorrection < rto {\n+ t.Fatalf(\"retransmit came sooner got: %d want: >= %d probe %d\", diff, rto, i)\n}\n- current *= 2\n+ startTime = time.Now()\n+ rto = getRTO(t, dut, acceptFd)\n+ timeout = rto + timeoutCorrection\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use TCP_INFO to get RTO in tcp_retransmits_test - TCP_INFO is used to get the RTO instead of calculating it manually. PiperOrigin-RevId: 358032487
259,885
17.02.2021 15:32:02
28,800
4bc7daf91a0d9102fa477b199964e7db45066da1
Check for directory emptiness in VFS1 overlay rmdir(). Note that this CL reorders overlayEntry.copyMu before overlayEntry.dirCacheMu in the overlayFileOperations.IterateDir() => readdirEntries() path - but this lock ordering is already required by overlayRemove/Bind() => overlayEntry.markDirectoryDirty(), so this actually just fixes an inconsistency.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/file_overlay.go", "new_path": "pkg/sentry/fs/file_overlay.go", "diff": "@@ -177,10 +177,16 @@ func (f *overlayFileOperations) Readdir(ctx context.Context, file *File, seriali\n// IterateDir implements DirIterator.IterateDir.\nfunc (f *overlayFileOperations) IterateDir(ctx context.Context, d *Dirent, dirCtx *DirCtx, offset int) (int, error) {\no := d.Inode.overlay\n+ o.copyMu.RLock()\n+ defer o.copyMu.RUnlock()\n+ return overlayIterateDirLocked(ctx, o, d, dirCtx, offset)\n+}\n+// Preconditions: o.copyMu must be locked.\n+func overlayIterateDirLocked(ctx context.Context, o *overlayEntry, d *Dirent, dirCtx *DirCtx, offset int) (int, error) {\nif !d.Inode.MountSource.CacheReaddir() {\n// Can't use the dirCache. Simply read the entries.\n- entries, err := readdirEntries(ctx, o)\n+ entries, err := readdirEntriesLocked(ctx, o)\nif err != nil {\nreturn offset, err\n}\n@@ -198,15 +204,6 @@ func (f *overlayFileOperations) IterateDir(ctx context.Context, d *Dirent, dirCt\n}\no.dirCacheMu.RUnlock()\n- // readdirEntries holds o.copyUpMu to ensure that copy-up does not\n- // occur while calculating the readdir results.\n- //\n- // However, it is possible for a copy-up to occur after the call to\n- // readdirEntries, but before setting o.dirCache. This is OK, since\n- // copy-up does not change the children in a way that would affect the\n- // children returned in dirCache. Copy-up only moves files/directories\n- // between layers in the overlay.\n- //\n// We must hold dirCacheMu around both readdirEntries and setting\n// o.dirCache to synchronize with dirCache invalidations done by\n// Create, Remove, Rename.\n@@ -216,7 +213,7 @@ func (f *overlayFileOperations) IterateDir(ctx context.Context, d *Dirent, dirCt\n// chance that a racing call managed to just set it, in which case we\n// can use that new value.\nif o.dirCache == nil {\n- dirCache, err := readdirEntries(ctx, o)\n+ dirCache, err := readdirEntriesLocked(ctx, o)\nif err != nil {\no.dirCacheMu.Unlock()\nreturn offset, err\n@@ -444,12 +441,11 @@ func (f *overlayFileOperations) SetFifoSize(size int64) (rv int64, err error) {\nreturn sz.SetFifoSize(size)\n}\n-// readdirEntries returns a sorted map of directory entries from the\n+// readdirEntriesLocked returns a sorted map of directory entries from the\n// upper and/or lower filesystem.\n-func readdirEntries(ctx context.Context, o *overlayEntry) (*SortedDentryMap, error) {\n- o.copyMu.RLock()\n- defer o.copyMu.RUnlock()\n-\n+//\n+// Preconditions: o.copyMu must be locked.\n+func readdirEntriesLocked(ctx context.Context, o *overlayEntry) (*SortedDentryMap, error) {\n// Assert that there is at least one upper or lower entry.\nif o.upper == nil && o.lower == nil {\npanic(\"invalid overlayEntry, needs at least one Inode\")\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode_overlay.go", "new_path": "pkg/sentry/fs/inode_overlay.go", "diff": "@@ -333,6 +333,19 @@ func overlayRemove(ctx context.Context, o *overlayEntry, parent *Dirent, child *\n}\nchild.Inode.overlay.copyMu.RLock()\ndefer child.Inode.overlay.copyMu.RUnlock()\n+ if child.Inode.StableAttr.Type == Directory {\n+ // RemoveDirectory requires that the directory is empty.\n+ ser := &CollectEntriesSerializer{}\n+ dirCtx := &DirCtx{\n+ Serializer: ser,\n+ }\n+ if _, err := overlayIterateDirLocked(ctx, child.Inode.overlay, child, dirCtx, 0); err != nil {\n+ return err\n+ }\n+ if ser.Written() != 0 {\n+ return syserror.ENOTEMPTY\n+ }\n+ }\nif child.Inode.overlay.upper != nil {\nif child.Inode.StableAttr.Type == Directory {\nif err := o.upper.InodeOperations.RemoveDirectory(ctx, o.upper, child.name); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Check for directory emptiness in VFS1 overlay rmdir(). Note that this CL reorders overlayEntry.copyMu before overlayEntry.dirCacheMu in the overlayFileOperations.IterateDir() => readdirEntries() path - but this lock ordering is already required by overlayRemove/Bind() => overlayEntry.markDirectoryDirty(), so this actually just fixes an inconsistency. PiperOrigin-RevId: 358047121
259,891
17.02.2021 18:22:27
28,800
1fc2c5f750bc90d75a3ac19fc95145a748a3811f
Move Name() out of netstack Matcher. It can live in the sentry.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/extensions.go", "new_path": "pkg/sentry/socket/netfilter/extensions.go", "diff": "@@ -40,13 +40,17 @@ type matchMaker interface {\nname() string\n// marshal converts from a stack.Matcher to an ABI struct.\n- marshal(matcher stack.Matcher) []byte\n+ marshal(matcher matcher) []byte\n// unmarshal converts from the ABI matcher struct to an\n// stack.Matcher.\nunmarshal(buf []byte, filter stack.IPHeaderFilter) (stack.Matcher, error)\n}\n+type matcher interface {\n+ name() string\n+}\n+\n// matchMakers maps the name of supported matchers to the matchMaker that\n// marshals and unmarshals it. It is immutable after package initialization.\nvar matchMakers = map[string]matchMaker{}\n@@ -60,8 +64,9 @@ func registerMatchMaker(mm matchMaker) {\nmatchMakers[mm.name()] = mm\n}\n-func marshalMatcher(matcher stack.Matcher) []byte {\n- matchMaker, ok := matchMakers[matcher.Name()]\n+func marshalMatcher(mr stack.Matcher) []byte {\n+ matcher := mr.(matcher)\n+ matchMaker, ok := matchMakers[matcher.name()]\nif !ok {\npanic(fmt.Sprintf(\"Unknown matcher of type %T.\", matcher))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/owner_matcher.go", "new_path": "pkg/sentry/socket/netfilter/owner_matcher.go", "diff": "@@ -38,7 +38,7 @@ func (ownerMarshaler) name() string {\n}\n// marshal implements matchMaker.marshal.\n-func (ownerMarshaler) marshal(mr stack.Matcher) []byte {\n+func (ownerMarshaler) marshal(mr matcher) []byte {\nmatcher := mr.(*OwnerMatcher)\niptOwnerInfo := linux.IPTOwnerInfo{\nUID: matcher.uid,\n@@ -106,8 +106,8 @@ type OwnerMatcher struct {\ninvertGID bool\n}\n-// Name implements Matcher.Name.\n-func (*OwnerMatcher) Name() string {\n+// name implements matcher.name.\n+func (*OwnerMatcher) name() string {\nreturn matcherNameOwner\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/tcp_matcher.go", "new_path": "pkg/sentry/socket/netfilter/tcp_matcher.go", "diff": "@@ -39,7 +39,7 @@ func (tcpMarshaler) name() string {\n}\n// marshal implements matchMaker.marshal.\n-func (tcpMarshaler) marshal(mr stack.Matcher) []byte {\n+func (tcpMarshaler) marshal(mr matcher) []byte {\nmatcher := mr.(*TCPMatcher)\nxttcp := linux.XTTCP{\nSourcePortStart: matcher.sourcePortStart,\n@@ -90,8 +90,8 @@ type TCPMatcher struct {\ndestinationPortEnd uint16\n}\n-// Name implements Matcher.Name.\n-func (*TCPMatcher) Name() string {\n+// name implements matcher.name.\n+func (*TCPMatcher) name() string {\nreturn matcherNameTCP\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/udp_matcher.go", "new_path": "pkg/sentry/socket/netfilter/udp_matcher.go", "diff": "@@ -39,7 +39,7 @@ func (udpMarshaler) name() string {\n}\n// marshal implements matchMaker.marshal.\n-func (udpMarshaler) marshal(mr stack.Matcher) []byte {\n+func (udpMarshaler) marshal(mr matcher) []byte {\nmatcher := mr.(*UDPMatcher)\nxtudp := linux.XTUDP{\nSourcePortStart: matcher.sourcePortStart,\n@@ -87,8 +87,8 @@ type UDPMatcher struct {\ndestinationPortEnd uint16\n}\n-// Name implements Matcher.Name.\n-func (*UDPMatcher) Name() string {\n+// name implements Matcher.name.\n+func (*UDPMatcher) name() string {\nreturn matcherNameUDP\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/iptables_types.go", "new_path": "pkg/tcpip/stack/iptables_types.go", "diff": "@@ -332,9 +332,6 @@ func filterAddress(addr, mask, filterAddr tcpip.Address, invert bool) bool {\n// A Matcher is the interface for matching packets.\ntype Matcher interface {\n- // Name returns the name of the Matcher.\n- Name() string\n-\n// Match returns whether the packet matches and whether the packet\n// should be \"hotdropped\", i.e. dropped immediately. This is usually\n// used for suspicious packets.\n" } ]
Go
Apache License 2.0
google/gvisor
Move Name() out of netstack Matcher. It can live in the sentry. PiperOrigin-RevId: 358078157
259,907
17.02.2021 19:26:45
28,800
dea894238bf404523a6c78819e242e0fb727e225
[infra] Update JDK11 version for java runtime tests.
[ { "change_type": "MODIFY", "old_path": "images/runtimes/java11/Dockerfile", "new_path": "images/runtimes/java11/Dockerfile", "diff": "@@ -11,9 +11,9 @@ RUN apt-get update && apt-get install -y \\\n# Download the JDK test library.\nWORKDIR /root\nRUN set -ex \\\n- && curl -fsSL --retry 10 -o /tmp/jdktests.tar.gz http://hg.openjdk.java.net/jdk/jdk11/archive/76072a077ee1.tar.gz/test \\\n+ && curl -fsSL --retry 10 -o /tmp/jdktests.tar.gz http://hg.openjdk.java.net/jdk-updates/jdk11u/archive/8b3498547395.tar.gz/test \\\n&& tar -xzf /tmp/jdktests.tar.gz \\\n- && mv jdk11-76072a077ee1/test test \\\n+ && mv jdk11u-8b3498547395/test test \\\n&& rm -f /tmp/jdktests.tar.gz\n# Install jtreg and add to PATH.\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/exclude/java11.csv", "new_path": "test/runtimes/exclude/java11.csv", "diff": "@@ -2,6 +2,7 @@ test name,bug id,comment\ncom/sun/crypto/provider/Cipher/PBE/PKCS12Cipher.java,,Fails in Docker\ncom/sun/jdi/InvokeHangTest.java,https://bugs.openjdk.java.net/browse/JDK-8218463,\ncom/sun/jdi/NashornPopFrameTest.java,,\n+com/sun/jdi/OnJcmdTest.java,b/180542784,\ncom/sun/jdi/ProcessAttachTest.java,,\ncom/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java,,Fails in Docker\ncom/sun/management/OperatingSystemMXBean/GetCommittedVirtualMemorySize.java,,\n@@ -20,6 +21,8 @@ java/lang/ClassLoader/nativeLibrary/NativeLibraryTest.java,,Fails in Docker\njava/lang/module/ModuleDescriptorTest.java,,\njava/lang/String/nativeEncoding/StringPlatformChars.java,,\njava/net/CookieHandler/B6791927.java,,java.lang.RuntimeException: Expiration date shouldn't be 0\n+java/net/DatagramSocket/SetGetReceiveBufferSize.java,b/180507650,\n+java/net/httpclient/websocket/WebSocketProxyTest.java,,Times out on runc too\njava/net/ipv6tests/TcpTest.java,,java.net.ConnectException: Connection timed out (Connection timed out)\njava/net/ipv6tests/UdpTest.java,,Times out\njava/net/Inet6Address/B6558853.java,,Times out\n@@ -150,12 +153,14 @@ jdk/jfr/event/runtime/TestModuleEvents.java,,java.lang.RuntimeException: assertE\njdk/jfr/event/runtime/TestNetworkUtilizationEvent.java,,\njdk/jfr/event/runtime/TestThreadParkEvent.java,,\njdk/jfr/event/sampling/TestNative.java,,\n+jdk/jfr/javaagent/TestLoadedAgent.java,b/180542638,\njdk/jfr/jcmd/TestJcmdChangeLogLevel.java,,\njdk/jfr/jcmd/TestJcmdConfigure.java,,\njdk/jfr/jcmd/TestJcmdDump.java,,\njdk/jfr/jcmd/TestJcmdDumpGeneratedFilename.java,,\njdk/jfr/jcmd/TestJcmdDumpLimited.java,,\njdk/jfr/jcmd/TestJcmdDumpPathToGCRoots.java,,\n+jdk/jfr/jcmd/TestJcmdDumpWithFileName.java,b/180542783,\njdk/jfr/jcmd/TestJcmdLegacy.java,,\njdk/jfr/jcmd/TestJcmdSaveToFile.java,,\njdk/jfr/jcmd/TestJcmdStartDirNotExist.java,,\n@@ -165,6 +170,7 @@ jdk/jfr/jcmd/TestJcmdStartStopDefault.java,,\njdk/jfr/jcmd/TestJcmdStartWithOptions.java,,\njdk/jfr/jcmd/TestJcmdStartWithSettings.java,,\njdk/jfr/jcmd/TestJcmdStopInvalidFile.java,,\n+jdk/jfr/jmx/TestGetRecordings.java,b/180542639,\njdk/jfr/jvm/TestGetAllEventClasses.java,,Compilation failed\njdk/jfr/jvm/TestJfrJavaBase.java,,\njdk/jfr/startupargs/TestStartRecording.java,,\n@@ -190,6 +196,7 @@ sun/tools/jhsdb/AlternateHashingTest.java,,\nsun/tools/jhsdb/BasicLauncherTest.java,,\nsun/tools/jhsdb/HeapDumpTest.java,,\nsun/tools/jhsdb/heapconfig/JMapHeapConfigTest.java,,\n+sun/tools/jhsdb/JShellHeapDumpTest.java,,Fails on runc too\nsun/tools/jinfo/BasicJInfoTest.java,,\nsun/tools/jinfo/JInfoTest.java,,\nsun/tools/jmap/BasicJMapTest.java,,\n@@ -208,5 +215,6 @@ tools/jlink/plugins/IncludeLocalesPluginTest.java,,\ntools/jmod/hashes/HashesTest.java,,\ntools/launcher/BigJar.java,b/111611473,\ntools/launcher/HelpFlagsTest.java,,java.lang.AssertionError: HelpFlagsTest failed: Tool jfr not covered by this test. Add specification to jdkTools array!\n+tools/launcher/JliLaunchTest.java,,Fails on runc too\ntools/launcher/VersionCheck.java,,java.lang.AssertionError: VersionCheck failed: testToolVersion: [jfr];\ntools/launcher/modules/patch/systemmodules/PatchSystemModules.java,,\n" } ]
Go
Apache License 2.0
google/gvisor
[infra] Update JDK11 version for java runtime tests. PiperOrigin-RevId: 358085809
259,992
18.02.2021 10:17:07
28,800
582f7bf6c0ccccaeb1215a232709df38d5d409f7
Remove side effect from pty tests Individual test cases must not rely on being executed in a clean environment.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pty.cc", "new_path": "test/syscalls/linux/pty.cc", "diff": "@@ -1316,7 +1316,10 @@ class JobControlTest : public ::testing::Test {\n// In the gVisor test environment, this test will be run as the session\n// leader already (as the sentry init process).\nif (!IsRunningOnGvisor()) {\n- ASSERT_THAT(setsid(), SyscallSucceeds());\n+ // Ignore failure because setsid(2) fails if the process is already the\n+ // session leader.\n+ setsid();\n+ ioctl(replica_.get(), TIOCNOTTY);\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Remove side effect from pty tests Individual test cases must not rely on being executed in a clean environment. PiperOrigin-RevId: 358207468
259,967
18.02.2021 11:37:46
28,800
bb5db80448c268f4d3eed932a01e78fcab7fb5d1
Remove deprecated NUD types Failed and FailedEntryLookups Completes the soft migration to Unreachable state by removing the Failed state and the the FailedEntryLookups StatCounter. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_cache.go", "new_path": "pkg/tcpip/stack/neighbor_cache.go", "diff": "@@ -25,10 +25,6 @@ const neighborCacheSize = 512 // max entries per interface\n// NeighborStats holds metrics for the neighbor table.\ntype NeighborStats struct {\n- // FailedEntryLookups is deprecated; UnreachableEntryLookups should be used\n- // instead.\n- FailedEntryLookups *tcpip.StatCounter\n-\n// UnreachableEntryLookups counts the number of lookups performed on an\n// entry in Unreachable state.\nUnreachableEntryLookups *tcpip.StatCounter\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighbor_entry.go", "new_path": "pkg/tcpip/stack/neighbor_entry.go", "diff": "@@ -68,11 +68,6 @@ const (\n// Static describes entries that have been explicitly added by the user. They\n// do not expire and are not deleted until explicitly removed.\nStatic\n- // Failed is deprecated and should no longer be used.\n- //\n- // TODO(gvisor.dev/issue/4667): Remove this once all references to Failed\n- // are removed from Fuchsia.\n- Failed\n// Unreachable means reachability confirmation failed; the maximum number of\n// reachability probes has been sent and no replies have been received.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/neighborstate_string.go", "new_path": "pkg/tcpip/stack/neighborstate_string.go", "diff": "@@ -29,13 +29,12 @@ func _() {\n_ = x[Delay-4]\n_ = x[Probe-5]\n_ = x[Static-6]\n- _ = x[Failed-7]\n- _ = x[Unreachable-8]\n+ _ = x[Unreachable-7]\n}\n-const _NeighborState_name = \"UnknownIncompleteReachableStaleDelayProbeStaticFailedUnreachable\"\n+const _NeighborState_name = \"UnknownIncompleteReachableStaleDelayProbeStaticUnreachable\"\n-var _NeighborState_index = [...]uint8{0, 7, 17, 26, 31, 36, 41, 47, 53, 64}\n+var _NeighborState_index = [...]uint8{0, 7, 17, 26, 31, 36, 41, 47, 58}\nfunc (i NeighborState) String() string {\nif i >= NeighborState(len(_NeighborState_index)-1) {\n" } ]
Go
Apache License 2.0
google/gvisor
Remove deprecated NUD types Failed and FailedEntryLookups Completes the soft migration to Unreachable state by removing the Failed state and the the FailedEntryLookups StatCounter. Fixes #4667 PiperOrigin-RevId: 358226380
259,975
18.02.2021 12:59:22
28,800
ec20f4f38ef49efc8756595e6ec3fb3e578cc097
Make b.N increase by KB not bytes on iperf. Currently, iperf runs a client that scales by bytes sent. In practice, this causes b.N to scale slowly and have several short lived containers. Instead, scale by KB to more quickly reach required time.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/network/iperf_test.go", "new_path": "test/benchmarks/network/iperf_test.go", "diff": "@@ -97,7 +97,7 @@ func BenchmarkIperf(b *testing.B) {\n}\niperf := tools.Iperf{\n- Num: b.N,\n+ Num: b.N, // KB for the client to send.\n}\n// Run the client.\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/iperf.go", "new_path": "test/benchmarks/tools/iperf.go", "diff": "@@ -26,7 +26,7 @@ const length = 64 * 1024\n// Iperf is for the client side of `iperf`.\ntype Iperf struct {\n- Num int\n+ Num int // Number of bytes to send in KB.\n}\n// MakeCmd returns a iperf client command.\n@@ -35,7 +35,7 @@ func (i *Iperf) MakeCmd(ip net.IP, port int) []string {\n\"iperf\",\n\"--format\", \"K\", // Output in KBytes.\n\"--realtime\", // Measured in realtime.\n- \"--num\", fmt.Sprintf(\"%d\", i.Num),\n+ \"--num\", fmt.Sprintf(\"%dK\", i.Num), // Number of bytes to send in KB.\n\"--length\", fmt.Sprintf(\"%d\", length),\n\"--client\", ip.String(),\n\"--port\", fmt.Sprintf(\"%d\", port),\n" } ]
Go
Apache License 2.0
google/gvisor
Make b.N increase by KB not bytes on iperf. Currently, iperf runs a client that scales by bytes sent. In practice, this causes b.N to scale slowly and have several short lived containers. Instead, scale by KB to more quickly reach required time. PiperOrigin-RevId: 358244926
259,881
18.02.2021 15:29:15
28,800
f80a857a4f5f57908c64a22f5de0e07df722227d
Bump build constraints to Go 1.18 These are bumped to allow early testing of Go 1.17. Use will be audited closer to the 1.17 release.
[ { "change_type": "MODIFY", "old_path": "pkg/gohacks/gohacks_unsafe.go", "new_path": "pkg/gohacks/gohacks_unsafe.go", "diff": "// limitations under the License.\n// +build go1.13\n-// +build !go1.17\n+// +build !go1.18\n// Check type signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/goid/goid.go", "new_path": "pkg/goid/goid.go", "diff": "// limitations under the License.\n// +build go1.12\n-// +build !go1.17\n+// +build !go1.18\n// Check type signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/procid/procid_amd64.s", "new_path": "pkg/procid/procid_amd64.s", "diff": "// +build amd64\n// +build go1.8\n-// +build !go1.17\n+// +build !go1.18\n#include \"textflag.h\"\n" }, { "change_type": "MODIFY", "old_path": "pkg/procid/procid_arm64.s", "new_path": "pkg/procid/procid_arm64.s", "diff": "// +build arm64\n// +build go1.8\n-// +build !go1.17\n+// +build !go1.18\n#include \"textflag.h\"\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_unsafe.go", "diff": "// limitations under the License.\n// +build go1.12\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_unsafe.go", "new_path": "pkg/sentry/platform/kvm/machine_unsafe.go", "diff": "// limitations under the License.\n// +build go1.12\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ptrace/subprocess_unsafe.go", "new_path": "pkg/sentry/platform/ptrace/subprocess_unsafe.go", "diff": "// limitations under the License.\n// +build go1.12\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/goyield_unsafe.go", "new_path": "pkg/sync/goyield_unsafe.go", "diff": "// license that can be found in the LICENSE file.\n// +build go1.14\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/mutex_unsafe.go", "new_path": "pkg/sync/mutex_unsafe.go", "diff": "// license that can be found in the LICENSE file.\n// +build go1.13\n-// +build !go1.17\n+// +build !go1.18\n// When updating the build constraint (above), check that syncMutex matches the\n// standard library sync.Mutex definition.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/runtime_unsafe.go", "new_path": "pkg/sync/runtime_unsafe.go", "diff": "// license that can be found in the LICENSE file.\n// +build go1.13\n-// +build !go1.17\n+// +build !go1.18\n-// Check function signatures and constants when updating Go version.\n+// Check go:linkname function signatures, type definitions, and constants when\n+// updating Go version.\npackage sync\n@@ -95,6 +96,7 @@ func MapKeyHasher(m interface{}) func(unsafe.Pointer, uintptr) uintptr {\nreturn mtyp.hasher\n}\n+// maptype is equivalent to the beginning of runtime.maptype.\ntype maptype struct {\nsize uintptr\nptrdata uintptr\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/rawfile/blockingpoll_yield_unsafe.go", "new_path": "pkg/tcpip/link/rawfile/blockingpoll_yield_unsafe.go", "diff": "// +build linux,amd64 linux,arm64\n// +build go1.12\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/time_unsafe.go", "new_path": "pkg/tcpip/time_unsafe.go", "diff": "// limitations under the License.\n// +build go1.9\n-// +build !go1.17\n+// +build !go1.18\n// Check go:linkname function signatures when updating Go version.\n" } ]
Go
Apache License 2.0
google/gvisor
Bump build constraints to Go 1.18 These are bumped to allow early testing of Go 1.17. Use will be audited closer to the 1.17 release. PiperOrigin-RevId: 358278615
259,962
18.02.2021 15:58:50
28,800
ec7f44f36b57c8472a692cdd736ad721c5170ee2
Make socketops reflect correct sndbuf value for host UDS. Also skips a test if the setsockopt to increase send buffer did not result in an increase. This is possible when the underlying socket is a host backed unix domain socket as in such cases gVisor does not permit increasing SO_SNDBUF.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/transport/connectioned.go", "new_path": "pkg/sentry/socket/unix/transport/connectioned.go", "diff": "@@ -364,7 +364,9 @@ func (e *connectionedEndpoint) Connect(ctx context.Context, server BoundEndpoint\ne.connected = ce\n// Make sure the newly created connected endpoint's write queue is updated\n// to reflect this endpoint's send buffer size.\n- e.connected.SetSendBufferSize(e.ops.GetSendBufferSize())\n+ if bufSz := e.connected.SetSendBufferSize(e.ops.GetSendBufferSize()); bufSz != e.ops.GetSendBufferSize() {\n+ e.ops.SetSendBufferSize(bufSz, false /* notify */)\n+ }\n}\nreturn server.BidirectionalConnect(ctx, e, returnConnect)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_unix_seqpacket.cc", "new_path": "test/syscalls/linux/socket_unix_seqpacket.cc", "diff": "@@ -91,7 +91,20 @@ TEST_P(SeqpacketUnixSocketPairTest, IncreasedSocketSendBufUnblocksWrites) {\nsetsockopt(sock, SOL_SOCKET, SO_SNDBUF, &buf_size, sizeof(buf_size)),\nSyscallSucceeds());\n- // The send should succeed again.\n+ // Skip test if the setsockopt didn't increase the sendbuf. This happens for\n+ // tests where the socket is a host fd where gVisor does not permit increasing\n+ // send buffer size.\n+ int new_buf_size = 0;\n+ buf_size_len = sizeof(new_buf_size);\n+ ASSERT_THAT(\n+ getsockopt(sock, SOL_SOCKET, SO_SNDBUF, &new_buf_size, &buf_size_len),\n+ SyscallSucceeds());\n+ if (IsRunningOnGvisor() && (new_buf_size <= buf_size)) {\n+ GTEST_SKIP() << \"Skipping test new send buffer size \" << new_buf_size\n+ << \" is the same as the value before setsockopt, \"\n+ << \" socket is probably a host backed socket.\" << std ::endl;\n+ }\n+ // send should succeed again.\nASSERT_THAT(RetryEINTR(send)(sock, buf.data(), buf.size(), 0),\nSyscallSucceeds());\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Make socketops reflect correct sndbuf value for host UDS. Also skips a test if the setsockopt to increase send buffer did not result in an increase. This is possible when the underlying socket is a host backed unix domain socket as in such cases gVisor does not permit increasing SO_SNDBUF. PiperOrigin-RevId: 358285158
259,985
19.02.2021 00:50:40
28,800
599579d0e554eea3b2a1bc5390026a6226e5e979
Add a few more project ideas to the gsoc 2021 list
[ { "change_type": "MODIFY", "old_path": "g3doc/proposals/gsoc-2021-ideas.md", "new_path": "g3doc/proposals/gsoc-2021-ideas.md", "diff": "@@ -13,9 +13,54 @@ If you're interested in contributing to gVisor through Google Summer of Code\n[roadmap](../roadmap.md) for areas of development, and get in touch through our\n[mailing list][gvisor-mailing-list] or [chat][gvisor-chat]!\n+## Implement the `setns` syscall\n+\n+Estimated complexity: *easy*\n+\n+This project involves implementing the [`setns`][man-setns] syscall. gVisor\n+currently supports manipulation of namespaces through the `clone` and `unshare`\n+syscalls. These two syscalls essentially implement the requisite logic for\n+`setns`, but there is currently no way to obtain a file descriptor referring to\n+a namespace in gVisor. As described in the `setns` man page, the two typical\n+ways of obtaining such a file descriptor in Linux are by opening a file in\n+`/proc/[pid]/ns`, or through the `pidfd_open` syscall.\n+\n+For gVisor, we recommend implementing the `/proc/[pid]/ns` mechanism first,\n+which would involve implementing a trivial namespace file type in procfs.\n+\n+## Implement `fanotify`\n+\n+Estimated complexity: *medium*\n+\n+Implement [`fanotify`][man-fanotify] in gVisor, which is a filesystem event\n+notification mechanism. gVisor currently supports `inotify`, which is a similar\n+mechanism with slightly different capabilities, but which should serve as a good\n+reference.\n+\n+The `fanotify` interface adds two new syscalls:\n+\n+- `fanotify_init` creates a new notification group, which is a collection of\n+ filesystem objects watched by the kernel. The group is represented by a file\n+ descriptor returned by this syscall. Events on the watched objects can be\n+ retrieved by reading from this file descriptor.\n+\n+- `fanotify_mark` adds a filesystem object to a watch group, or modifies the\n+ parameters of an existing watch.\n+\n+Unlike `inotify`, `fanotify` can set watches on filesystems and mount points,\n+which will require some additional data tracking on the corresponding filesystem\n+objects within the sentry.\n+\n+A well-designed implementation should reuse the notifications from `inotify` for\n+files and directories (this is also how Linux implements these mechanisms), and\n+should implement the necessary tracking and notifications for filesystems and\n+mount points.\n+\n## Implement `io_uring`\n-`io_uring` is the lastest asynchronous I/O API in Linux. This project will\n+Estimated complexity: *hard*\n+\n+`io_uring` is the latest asynchronous I/O API in Linux. This project will\ninvolve implementing the system interfaces required to support `io_uring` in\ngVisor. A successful implementation should have similar relatively performance\nand scalability characteristics compared to synchronous I/O syscalls, as in\n@@ -55,7 +100,7 @@ supported operations, it should be implemented in two stages:\nIn the first stage, a simplified version of the `io_uring_setup` and\n`io_uring_enter` syscalls should be implemented, which will only support a\nminimal set of arguments and just one or two simple opcodes. This simplified\n-implementation can be used to figure out how to integreate `io_uring` with\n+implementation can be used to figure out how to integrate `io_uring` with\ngVisor's virtual filesystem and memory management subsystems, as well as\nbenchmark the implementation to ensure it has the desired performance\ncharacteristics. The goal in this stage should be to implement the smallest\n@@ -65,7 +110,37 @@ In the second stage, support can be added for all the I/O operations supported\nby Linux, as well as advanced `io_uring` features such as fixed files and\nbuffers (via `io_uring_register`), polled I/O and kernel-side request polling.\n+A single contributor can expect to make reasonable progress on the first stage\n+within the scope of Google Summer of Code. The second stage, while not\n+necessarily difficult, is likely to be very time consuming. However it also\n+lends itself well to parallel development by multiple contributors.\n+\n+## Implement message queues\n+\n+Estimated complexity: *hard*\n+\n+Linux provides two alternate message queues:\n+[System V message queues][man-sysvmq] and [POSIX message queues][man-posixmq].\n+gVisor currently doesn't implement either.\n+\n+Both mechanisms add multiple syscalls for managing and using the message queues,\n+see the relevant man pages above for their full description.\n+\n+The core of both mechanisms are very similar, it may be possible to back both\n+mechanisms with a common implementation in gVisor. Linux however has two\n+distinct implementations.\n+\n+An individual contributor can reasonably implement a minimal version of one of\n+these two mechanisms within the scope of Google Summer of Code. The System V\n+queue may be slightly easier to implement, as gVisor already implements System V\n+semaphores and shared memory regions, so the code for managing IPC objects and\n+the registry already exist.\n+\n[gsoc-2021-site]: https://summerofcode.withgoogle.com\n[gvisor-chat]: https://gitter.im/gvisor/community\n[gvisor-mailing-list]: https://groups.google.com/g/gvisor-dev\n[io-uring-doc]: https://kernel.dk/io_uring.pdf\n+[man-fanotify]: https://man7.org/linux/man-pages/man7/fanotify.7.html\n+[man-sysvmq]: https://man7.org/linux/man-pages/man7/sysvipc.7.html\n+[man-posixmq]: https://man7.org/linux/man-pages//man7/mq_overview.7.html\n+[man-setns]: https://man7.org/linux/man-pages/man2/setns.2.html\n" } ]
Go
Apache License 2.0
google/gvisor
Add a few more project ideas to the gsoc 2021 list PiperOrigin-RevId: 358354414
259,975
19.02.2021 17:10:27
28,800
7544eeb242d0aba2da054a1663e043feaedb9618
Correctly set and respect b.N in fio benchmark. fio should scale by written/read bytes and not iterate runs of the fio container.
[ { "change_type": "MODIFY", "old_path": "test/benchmarks/fs/fio_test.go", "new_path": "test/benchmarks/fs/fio_test.go", "diff": "@@ -34,37 +34,31 @@ func BenchmarkFio(b *testing.B) {\ntestCases := []tools.Fio{\n{\nTest: \"write\",\n- Size: b.N,\nBlockSize: 4,\nIODepth: 4,\n},\n{\nTest: \"write\",\n- Size: b.N,\nBlockSize: 1024,\nIODepth: 4,\n},\n{\nTest: \"read\",\n- Size: b.N,\nBlockSize: 4,\nIODepth: 4,\n},\n{\nTest: \"read\",\n- Size: b.N,\nBlockSize: 1024,\nIODepth: 4,\n},\n{\nTest: \"randwrite\",\n- Size: b.N,\nBlockSize: 4,\nIODepth: 4,\n},\n{\nTest: \"randread\",\n- Size: b.N,\nBlockSize: 4,\nIODepth: 4,\n},\n@@ -95,6 +89,8 @@ func BenchmarkFio(b *testing.B) {\nb.Fatalf(\"Failed to parser paramters: %v\", err)\n}\nb.Run(name, func(b *testing.B) {\n+ b.StopTimer()\n+ tc.Size = b.N\nctx := context.Background()\ncontainer := machine.GetContainer(ctx, b)\ndefer container.CleanUp(ctx)\n@@ -141,10 +137,6 @@ func BenchmarkFio(b *testing.B) {\n}\ncmd := tc.MakeCmd(outfile)\n- b.ResetTimer()\n- b.StopTimer()\n-\n- for i := 0; i < b.N; i++ {\nif err := harness.DropCaches(machine); err != nil {\nb.Fatalf(\"failed to drop caches: %v\", err)\n}\n@@ -156,9 +148,7 @@ func BenchmarkFio(b *testing.B) {\nb.Fatalf(\"failed to run cmd %v: %v\", cmd, err)\n}\nb.StopTimer()\n- b.SetBytes(1024 * 1024) // Bytes for go reporting (Size is in megabytes).\ntc.Report(b, data)\n- }\n})\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/benchmarks/tools/fio.go", "new_path": "test/benchmarks/tools/fio.go", "diff": "@@ -62,18 +62,15 @@ func (f *Fio) Report(b *testing.B, output string) {\n// parseBandwidth reports the bandwidth in b/s.\nfunc (f *Fio) parseBandwidth(data string, isRead bool) (float64, error) {\n+ op := \"write\"\nif isRead {\n- result, err := f.parseFioJSON(data, \"read\", \"bw\")\n- if err != nil {\n- return 0, err\n- }\n- return 1024 * result, nil\n+ op = \"read\"\n}\n- result, err := f.parseFioJSON(data, \"write\", \"bw\")\n+ result, err := f.parseFioJSON(data, op, \"bw\")\nif err != nil {\nreturn 0, err\n}\n- return 1024 * result, nil\n+ return result * 1024, nil\n}\n// parseIOps reports the write IO per second metric.\n" } ]
Go
Apache License 2.0
google/gvisor
Correctly set and respect b.N in fio benchmark. fio should scale by written/read bytes and not iterate runs of the fio container. PiperOrigin-RevId: 358511771
259,853
22.02.2021 11:37:13
28,800
c5a4e100085ccbd063df36706cccf93951439cb7
unix: sendmmsg and recvmsg have to cap a number of message to UIO_MAXIOV Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -657,6 +657,10 @@ func RecvMMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.EINVAL\n}\n+ if vlen > linux.UIO_MAXIOV {\n+ vlen = linux.UIO_MAXIOV\n+ }\n+\n// Reject flags that we don't handle yet.\nif flags & ^(baseRecvFlags|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE) != 0 {\nreturn 0, nil, syserror.EINVAL\n@@ -938,6 +942,10 @@ func SendMMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.EINVAL\n}\n+ if vlen > linux.UIO_MAXIOV {\n+ vlen = linux.UIO_MAXIOV\n+ }\n+\n// Get socket from the file descriptor.\nfile := t.GetFile(fd)\nif file == nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/socket.go", "diff": "@@ -660,6 +660,10 @@ func RecvMMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.EINVAL\n}\n+ if vlen > linux.UIO_MAXIOV {\n+ vlen = linux.UIO_MAXIOV\n+ }\n+\n// Reject flags that we don't handle yet.\nif flags & ^(baseRecvFlags|linux.MSG_CMSG_CLOEXEC|linux.MSG_ERRQUEUE) != 0 {\nreturn 0, nil, syserror.EINVAL\n@@ -941,6 +945,10 @@ func SendMMsg(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.EINVAL\n}\n+ if vlen > linux.UIO_MAXIOV {\n+ vlen = linux.UIO_MAXIOV\n+ }\n+\n// Get socket from the file descriptor.\nfile := t.GetFileVFS2(fd)\nif file == nil {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2305,7 +2305,7 @@ cc_library(\nname = \"socket_generic_test_cases\",\ntestonly = 1,\nsrcs = [\n- \"socket_generic.cc\",\n+ \"socket_generic_test_cases.cc\",\n],\nhdrs = [\n\"socket_generic.h\",\n" }, { "change_type": "RENAME", "old_path": "test/syscalls/linux/socket_generic.cc", "new_path": "test/syscalls/linux/socket_generic_test_cases.cc", "diff": "@@ -98,6 +98,27 @@ TEST_P(AllSocketPairTest, BasicSendmmsg) {\nEXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));\n}\n+TEST_P(AllSocketPairTest, SendmmsgIsLimitedByMAXIOV) {\n+ std::unique_ptr<SocketPair> sockets =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ char c = 0;\n+\n+ std::vector<struct mmsghdr> msgs(UIO_MAXIOV + 1);\n+ std::vector<struct iovec> iovs(msgs.size());\n+ for (size_t i = 0; i < msgs.size(); i++) {\n+ iovs[i].iov_len = 1;\n+ iovs[i].iov_base = &c;\n+ msgs[i].msg_hdr.msg_iov = &iovs[i];\n+ msgs[i].msg_hdr.msg_iovlen = 1;\n+ }\n+\n+ int n;\n+ ASSERT_THAT(n = RetryEINTR(sendmmsg)(sockets->first_fd(), msgs.data(),\n+ msgs.size(), MSG_DONTWAIT),\n+ SyscallSucceeds());\n+ EXPECT_LE(n, UIO_MAXIOV);\n+}\n+\nTEST_P(AllSocketPairTest, BasicRecvmmsg) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nchar sent_data[200];\n" } ]
Go
Apache License 2.0
google/gvisor
unix: sendmmsg and recvmsg have to cap a number of message to UIO_MAXIOV Reported-by: [email protected] PiperOrigin-RevId: 358866218
259,992
22.02.2021 15:54:58
28,800
34e2cda9ad6a20861844776abfbb45052d20c3fa
Return nicer error message when cgroups v1 isn't available Updates Closes
[ { "change_type": "MODIFY", "old_path": "runsc/cgroup/BUILD", "new_path": "runsc/cgroup/BUILD", "diff": "@@ -11,6 +11,7 @@ go_library(\n\"//pkg/log\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n\"@com_github_opencontainers_runtime_spec//specs-go:go_default_library\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "runsc/cgroup/cgroup.go", "new_path": "runsc/cgroup/cgroup.go", "diff": "@@ -32,6 +32,7 @@ import (\n\"github.com/cenkalti/backoff\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/log\"\n)\n@@ -59,6 +60,16 @@ var controllers = map[string]config{\n\"systemd\": {ctrlr: &noop{}},\n}\n+// IsOnlyV2 checks whether cgroups V2 is enabled and V1 is not.\n+func IsOnlyV2() bool {\n+ var stat unix.Statfs_t\n+ if err := unix.Statfs(cgroupRoot, &stat); err != nil {\n+ // It's not used for anything important, assume not V2 on failure.\n+ return false\n+ }\n+ return stat.Type == unix.CGROUP2_SUPER_MAGIC\n+}\n+\nfunc setOptionalValueInt(path, name string, val *int64) error {\nif val == nil || *val == 0 {\nreturn nil\n" }, { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -230,7 +230,6 @@ func New(conf *config.Config, args Args) (*Container, error) {\nif args.Spec.Linux.CgroupsPath == \"\" && !conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\nargs.Spec.Linux.CgroupsPath = \"/\" + args.ID\n}\n-\n// Create and join cgroup before processes are created to ensure they are\n// part of the cgroup from the start (and all their children processes).\ncg, err := cgroup.New(args.Spec)\n@@ -238,6 +237,10 @@ func New(conf *config.Config, args Args) (*Container, error) {\nreturn nil, err\n}\nif cg != nil {\n+ // TODO(gvisor.dev/issue/3481): Remove when cgroups v2 is supported.\n+ if !conf.Rootless && cgroup.IsOnlyV2() {\n+ return nil, fmt.Errorf(\"cgroups V2 is not yet supported. Enable cgroups V1 and retry\")\n+ }\n// If there is cgroup config, install it before creating sandbox process.\nif err := cg.Install(args.Spec.Linux.Resources); err != nil {\nswitch {\n" } ]
Go
Apache License 2.0
google/gvisor
Return nicer error message when cgroups v1 isn't available Updates #3481 Closes #5430 PiperOrigin-RevId: 358923208
259,975
22.02.2021 16:00:33
28,800
24ea8003a49dbbcdfbbf2e5969c4bf8002063b86
Only detect mds for mitigate. Only detect and mitigate on mds for the mitigate command.
[ { "change_type": "MODIFY", "old_path": "runsc/mitigate/cpu.go", "new_path": "runsc/mitigate/cpu.go", "diff": "@@ -23,15 +23,10 @@ import (\n)\nconst (\n- // constants of coomm\n- meltdown = \"cpu_meltdown\"\n- l1tf = \"l1tf\"\n+ // mds is the only bug we care about.\nmds = \"mds\"\n- swapgs = \"swapgs\"\n- taa = \"taa\"\n-)\n-const (\n+ // Constants for parsing /proc/cpuinfo.\nprocessorKey = \"processor\"\nvendorIDKey = \"vendor_id\"\ncpuFamilyKey = \"cpu family\"\n@@ -39,9 +34,8 @@ const (\nphysicalIDKey = \"physical id\"\ncoreIDKey = \"core id\"\nbugsKey = \"bugs\"\n-)\n-const (\n+ // Path to shutdown a CPU.\ncpuOnlineTemplate = \"/sys/devices/system/cpu/cpu%d/online\"\n)\n@@ -249,24 +243,10 @@ func (t *thread) shutdown() error {\nreturn ioutil.WriteFile(cpuPath, []byte{'0'}, 0644)\n}\n-// List of pertinent side channel vulnerablilites.\n-// For mds, see: https://www.kernel.org/doc/html/latest/admin-guide/hw-vuln/mds.html.\n-var vulnerabilities = []string{\n- meltdown,\n- l1tf,\n- mds,\n- swapgs,\n- taa,\n-}\n-\n-// isVulnerable checks if a CPU is vulnerable to pertinent bugs.\n+// isVulnerable checks if a CPU is vulnerable to mds.\nfunc (t *thread) isVulnerable() bool {\n- for _, bug := range vulnerabilities {\n- if _, ok := t.bugs[bug]; ok {\n- return true\n- }\n- }\n- return false\n+ _, ok := t.bugs[mds]\n+ return ok\n}\n// isActive checks if a CPU is active from /sys/devices/system/cpu/cpu{N}/online\n" }, { "change_type": "MODIFY", "old_path": "runsc/mitigate/mitigate.go", "new_path": "runsc/mitigate/mitigate.go", "diff": "@@ -36,11 +36,7 @@ type Mitigate struct {\nfunc (m Mitigate) Usage() string {\nusageString := `mitigate [flags]\n-This command mitigates an underlying system against side channel attacks.\n-The command checks /proc/cpuinfo for cpus having key vulnerablilities (meltdown,\n-l1tf, mds, swapgs, taa). If cpus are found to have one of the vulnerabilities,\n-all but one cpu is shutdown on each core via\n-/sys/devices/system/cpu/cpu{N}/online.\n+Mitigate mitigates a system to the \"MDS\" vulnerability by implementing a manual shutdown of SMT. The command checks /proc/cpuinfo for cpus having the MDS vulnerability, and if found, shutdown all but one CPU per hyperthread pair via /sys/devices/system/cpu/cpu{N}/online. CPUs can be restored by writing \"2\" to each file in /sys/devices/system/cpu/cpu{N}/online or performing a system reboot.\n`\nreturn usageString + m.other.usage()\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Only detect mds for mitigate. Only detect and mitigate on mds for the mitigate command. PiperOrigin-RevId: 358924466
259,860
24.02.2021 01:46:44
28,800
6e000d3424c0eed685483f54348c6b0a752a0435
Use async task context for async IO.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/error.go", "new_path": "pkg/sentry/syscalls/linux/error.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"io\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n@@ -36,16 +37,16 @@ var (\n// errors, we may consume the error and return only the partial read/write.\n//\n// op and f are used only for panics.\n-func HandleIOErrorVFS2(t *kernel.Task, partialResult bool, ioerr, intr error, op string, f *vfs.FileDescription) error {\n- known, err := handleIOErrorImpl(t, partialResult, ioerr, intr, op)\n+func HandleIOErrorVFS2(ctx context.Context, partialResult bool, ioerr, intr error, op string, f *vfs.FileDescription) error {\n+ known, err := handleIOErrorImpl(ctx, partialResult, ioerr, intr, op)\nif err != nil {\nreturn err\n}\nif !known {\n// An unknown error is encountered with a partial read/write.\nfs := f.Mount().Filesystem().VirtualFilesystem()\n- root := vfs.RootFromContext(t)\n- name, _ := fs.PathnameWithDeleted(t, root, f.VirtualDentry())\n+ root := vfs.RootFromContext(ctx)\n+ name, _ := fs.PathnameWithDeleted(ctx, root, f.VirtualDentry())\nlog.Traceback(\"Invalid request partialResult %v and err (type %T) %v for %s operation on %q\", partialResult, ioerr, ioerr, op, name)\npartialResultOnce.Do(partialResultMetric.Increment)\n}\n@@ -56,8 +57,8 @@ func HandleIOErrorVFS2(t *kernel.Task, partialResult bool, ioerr, intr error, op\n// errors, we may consume the error and return only the partial read/write.\n//\n// op and f are used only for panics.\n-func handleIOError(t *kernel.Task, partialResult bool, ioerr, intr error, op string, f *fs.File) error {\n- known, err := handleIOErrorImpl(t, partialResult, ioerr, intr, op)\n+func handleIOError(ctx context.Context, partialResult bool, ioerr, intr error, op string, f *fs.File) error {\n+ known, err := handleIOErrorImpl(ctx, partialResult, ioerr, intr, op)\nif err != nil {\nreturn err\n}\n@@ -74,7 +75,7 @@ func handleIOError(t *kernel.Task, partialResult bool, ioerr, intr error, op str\n// errors, we may consume the error and return only the partial read/write.\n//\n// Returns false if error is unknown.\n-func handleIOErrorImpl(t *kernel.Task, partialResult bool, err, intr error, op string) (bool, error) {\n+func handleIOErrorImpl(ctx context.Context, partialResult bool, err, intr error, op string) (bool, error) {\nswitch err {\ncase nil:\n// Typical successful syscall.\n@@ -85,6 +86,10 @@ func handleIOErrorImpl(t *kernel.Task, partialResult bool, err, intr error, op s\n// they will see 0.\nreturn true, nil\ncase syserror.ErrExceedsFileSizeLimit:\n+ t := kernel.TaskFromContext(ctx)\n+ if t == nil {\n+ panic(\"I/O error should only occur from a context associated with a Task\")\n+ }\n// Ignore partialResult because this error only applies to\n// normal files, and for those files we cannot accumulate\n// write results.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/aio.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/aio.go", "diff": "@@ -177,7 +177,7 @@ func getAIOCallback(t *kernel.Task, fd, eventFD *vfs.FileDescription, cbAddr use\n// Update the result.\nif err != nil {\n- err = slinux.HandleIOErrorVFS2(t, ev.Result != 0 /* partial */, err, nil /* never interrupted */, \"aio\", fd)\n+ err = slinux.HandleIOErrorVFS2(ctx, ev.Result != 0 /* partial */, err, nil /* never interrupted */, \"aio\", fd)\nev.Result = -int64(kernel.ExtractErrno(err, 0))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Use async task context for async IO. PiperOrigin-RevId: 359235699
259,853
24.02.2021 11:34:08
28,800
055073f11813a7b675cb19aa6c540a667cd746a5
runsc/filters: permit clock_nanosleep for race Syzkaller hosts contains many audit messages that runsc tries to call the clock_nanosleep syscall.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/filter/extra_filters_race.go", "new_path": "runsc/boot/filter/extra_filters_race.go", "diff": "@@ -27,6 +27,7 @@ func instrumentationFilters() seccomp.SyscallRules {\nReport(\"TSAN is enabled: syscall filters less restrictive!\")\nreturn seccomp.SyscallRules{\nsyscall.SYS_BRK: {},\n+ syscall.SYS_CLOCK_NANOSLEEP: {},\nsyscall.SYS_CLONE: {},\nsyscall.SYS_FUTEX: {},\nsyscall.SYS_MMAP: {},\n" }, { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/extra_filters_race.go", "new_path": "runsc/fsgofer/filter/extra_filters_race.go", "diff": "@@ -28,6 +28,7 @@ func instrumentationFilters() seccomp.SyscallRules {\nlog.Warningf(\"*** SECCOMP WARNING: TSAN is enabled: syscall filters less restrictive!\")\nreturn seccomp.SyscallRules{\nsyscall.SYS_BRK: {},\n+ syscall.SYS_CLOCK_NANOSLEEP: {},\nsyscall.SYS_CLONE: {},\nsyscall.SYS_FUTEX: {},\nsyscall.SYS_MADVISE: {},\n" } ]
Go
Apache License 2.0
google/gvisor
runsc/filters: permit clock_nanosleep for race Syzkaller hosts contains many audit messages that runsc tries to call the clock_nanosleep syscall. PiperOrigin-RevId: 359331413
259,951
24.02.2021 16:54:11
28,800
1d2975ffbe0e32ebcd2fe9307544799b2f9ae632
Validate MLD packets Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -260,12 +260,31 @@ func getTargetLinkAddr(it header.NDPOptionIterator) (tcpip.LinkAddress, bool) {\n})\n}\n-func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool) {\n+func isMLDValid(pkt *stack.PacketBuffer, iph header.IPv6, routerAlert *header.IPv6RouterAlertOption) bool {\n+ // As per RFC 2710 section 3:\n+ // All MLD messages described in this document are sent with a link-local\n+ // IPv6 Source Address, an IPv6 Hop Limit of 1, and an IPv6 Router Alert\n+ // option in a Hop-by-Hop Options header.\n+ if routerAlert == nil || routerAlert.Value != header.IPv6RouterAlertMLD {\n+ return false\n+ }\n+ if pkt.Data.Size() < header.ICMPv6HeaderSize+header.MLDMinimumSize {\n+ return false\n+ }\n+ if iph.HopLimit() != header.MLDHopLimit {\n+ return false\n+ }\n+ if !header.IsV6LinkLocalAddress(iph.SourceAddress()) {\n+ return false\n+ }\n+ return true\n+}\n+\n+func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, routerAlert *header.IPv6RouterAlertOption) {\nsent := e.stats.icmp.packetsSent\nreceived := e.stats.icmp.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+ // TODO(gvisor.dev/issue/170): ICMP packets don't have their TransportHeader\n+ // fields set. See icmp/protocol.go:protocol.Parse for a full explanation.\nv, ok := pkt.Data.PullUp(header.ICMPv6HeaderSize)\nif !ok {\nreceived.invalid.Increment()\n@@ -823,7 +842,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool) {\npanic(fmt.Sprintf(\"unrecognized MLD message = %d\", icmpType))\n}\n- if pkt.Data.Size()-header.ICMPv6HeaderSize < header.MLDMinimumSize {\n+ if !isMLDValid(pkt, iph, routerAlert) {\nreceived.invalid.Increment()\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -48,6 +48,8 @@ const (\n// Extra time to use when waiting for an async event to occur.\ndefaultAsyncPositiveEventTimeout = 30 * time.Second\n+\n+ arbitraryHopLimit = 42\n)\nvar (\n@@ -157,19 +159,28 @@ func (*testInterface) CheckLocalAddress(tcpip.NetworkProtocolNumber, tcpip.Addre\nreturn false\n}\n-func handleICMPInIPv6(ep stack.NetworkEndpoint, src, dst tcpip.Address, icmp header.ICMPv6) {\n- ip := buffer.NewView(header.IPv6MinimumSize)\n+func handleICMPInIPv6(ep stack.NetworkEndpoint, src, dst tcpip.Address, icmp header.ICMPv6, hopLimit uint8, includeRouterAlert bool) {\n+ var extensionHeaders header.IPv6ExtHdrSerializer\n+ if includeRouterAlert {\n+ extensionHeaders = header.IPv6ExtHdrSerializer{\n+ header.IPv6SerializableHopByHopExtHdr{\n+ &header.IPv6RouterAlertOption{Value: header.IPv6RouterAlertMLD},\n+ },\n+ }\n+ }\n+ ip := buffer.NewView(header.IPv6MinimumSize + extensionHeaders.Length())\nheader.IPv6(ip).Encode(&header.IPv6Fields{\nPayloadLength: uint16(len(icmp)),\nTransportProtocol: header.ICMPv6ProtocolNumber,\n- HopLimit: header.NDPHopLimit,\n+ HopLimit: hopLimit,\nSrcAddr: src,\nDstAddr: dst,\n+ ExtensionHeaders: extensionHeaders,\n})\n+\nvv := ip.ToVectorisedView()\nvv.AppendView(buffer.View(icmp))\nep.HandlePacket(stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.IPv6MinimumSize,\nData: vv,\n}))\n}\n@@ -224,64 +235,83 @@ func TestICMPCounts(t *testing.T) {\ntypes := []struct {\ntyp header.ICMPv6Type\n+ hopLimit uint8\n+ includeRouterAlert bool\nsize int\nextraData []byte\n}{\n{\ntyp: header.ICMPv6DstUnreachable,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6DstUnreachableMinimumSize,\n},\n{\ntyp: header.ICMPv6PacketTooBig,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6PacketTooBigMinimumSize,\n},\n{\ntyp: header.ICMPv6TimeExceeded,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6MinimumSize,\n},\n{\ntyp: header.ICMPv6ParamProblem,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6MinimumSize,\n},\n{\ntyp: header.ICMPv6EchoRequest,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6EchoMinimumSize,\n},\n{\ntyp: header.ICMPv6EchoReply,\n+ hopLimit: arbitraryHopLimit,\nsize: header.ICMPv6EchoMinimumSize,\n},\n{\ntyp: header.ICMPv6RouterSolicit,\n+ hopLimit: header.NDPHopLimit,\nsize: header.ICMPv6MinimumSize,\n},\n{\ntyp: header.ICMPv6RouterAdvert,\n+ hopLimit: header.NDPHopLimit,\nsize: header.ICMPv6HeaderSize + header.NDPRAMinimumSize,\n},\n{\ntyp: header.ICMPv6NeighborSolicit,\n+ hopLimit: header.NDPHopLimit,\nsize: header.ICMPv6NeighborSolicitMinimumSize,\n},\n{\ntyp: header.ICMPv6NeighborAdvert,\n+ hopLimit: header.NDPHopLimit,\nsize: header.ICMPv6NeighborAdvertMinimumSize,\nextraData: tllData[:],\n},\n{\ntyp: header.ICMPv6RedirectMsg,\n+ hopLimit: header.NDPHopLimit,\nsize: header.ICMPv6MinimumSize,\n},\n{\ntyp: header.ICMPv6MulticastListenerQuery,\n+ hopLimit: header.MLDHopLimit,\n+ includeRouterAlert: true,\nsize: header.MLDMinimumSize + header.ICMPv6HeaderSize,\n},\n{\ntyp: header.ICMPv6MulticastListenerReport,\n+ hopLimit: header.MLDHopLimit,\n+ includeRouterAlert: true,\nsize: header.MLDMinimumSize + header.ICMPv6HeaderSize,\n},\n{\ntyp: header.ICMPv6MulticastListenerDone,\n+ hopLimit: header.MLDHopLimit,\n+ includeRouterAlert: true,\nsize: header.MLDMinimumSize + header.ICMPv6HeaderSize,\n},\n{\n@@ -295,12 +325,12 @@ func TestICMPCounts(t *testing.T) {\ncopy(icmp[typ.size:], typ.extraData)\nicmp.SetType(typ.typ)\nicmp.SetChecksum(header.ICMPv6Checksum(icmp[:typ.size], lladdr0, lladdr1, buffer.View(typ.extraData).ToVectorisedView()))\n- handleICMPInIPv6(ep, lladdr1, lladdr0, icmp)\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, icmp, typ.hopLimit, typ.includeRouterAlert)\n}\n// Construct an empty ICMP packet so that\n// Stats().ICMP.ICMPv6ReceivedPacketStats.Invalid is incremented.\n- handleICMPInIPv6(ep, lladdr1, lladdr0, header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)))\n+ handleICMPInIPv6(ep, lladdr1, lladdr0, header.ICMPv6(buffer.NewView(header.IPv6MinimumSize)), arbitraryHopLimit, false)\nicmpv6Stats := s.Stats().ICMP.V6.PacketsReceived\nvisitStats(reflect.ValueOf(&icmpv6Stats).Elem(), func(name string, s *tcpip.StatCounter) {\n@@ -1632,7 +1662,7 @@ func TestCallsToNeighborCache(t *testing.T) {\nicmp := test.createPacket()\nicmp.SetChecksum(header.ICMPv6Checksum(icmp, test.source, test.destination, buffer.VectorisedView{}))\n- handleICMPInIPv6(ep, test.source, test.destination, icmp)\n+ handleICMPInIPv6(ep, test.source, test.destination, icmp, header.NDPHopLimit, false)\n// Confirm the endpoint calls the correct NUDHandler method.\nif testInterface.probeCount != test.wantProbeCount {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -1001,7 +1001,6 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nvv.AppendView(pkt.TransportHeader().View())\nvv.Append(pkt.Data)\nit := header.MakeIPv6PayloadIterator(header.IPv6ExtensionHeaderIdentifier(h.NextHeader()), vv)\n- hasFragmentHeader := false\n// iptables filtering. All packets that reach here are intended for\n// this machine and need not be forwarded.\n@@ -1012,6 +1011,11 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n+ var (\n+ hasFragmentHeader bool\n+ routerAlert *header.IPv6RouterAlertOption\n+ )\n+\nfor {\n// Keep track of the start of the previous header so we can report the\n// special case of a Hop by Hop at a location other than at the start.\n@@ -1049,8 +1053,20 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nbreak\n}\n- // We currently do not support any IPv6 Hop By Hop extension header\n- // options.\n+ switch opt := opt.(type) {\n+ case *header.IPv6RouterAlertOption:\n+ if routerAlert != nil {\n+ // As per RFC 2711 section 3, there should be at most one Router\n+ // Alert option per packet.\n+ //\n+ // There MUST only be one option of this type, regardless of\n+ // value, per Hop-by-Hop header.\n+ stats.MalformedPacketsReceived.Increment()\n+ return\n+ }\n+ routerAlert = opt\n+ stats.OptionRouterAlertReceived.Increment()\n+ default:\nswitch opt.UnknownAction() {\ncase header.IPv6OptionUnknownActionSkip:\ncase header.IPv6OptionUnknownActionDiscard:\n@@ -1061,14 +1077,13 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\n}\nfallthrough\ncase header.IPv6OptionUnknownActionDiscardSendICMP:\n- // This case satisfies a requirement of RFC 8200 section 4.2\n- // which states that an unknown option starting with bits [10] should:\n+ // This case satisfies a requirement of RFC 8200 section 4.2 which\n+ // states that an unknown option starting with bits [10] should:\n//\n// discard the packet and, regardless of whether or not the\n// packet's Destination Address was a multicast address, send an\n// ICMP Parameter Problem, Code 2, message to the packet's\n// Source Address, pointing to the unrecognized Option Type.\n- //\n_ = e.protocol.returnError(&icmpReasonParameterProblem{\ncode: header.ICMPv6UnknownOption,\npointer: it.ParseOffset() + optsIt.OptionOffset(),\n@@ -1079,6 +1094,7 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\npanic(fmt.Sprintf(\"unrecognized action for an unrecognized Hop By Hop extension header option = %d\", opt))\n}\n}\n+ }\ncase header.IPv6RoutingExtHdr:\n// As per RFC 8200 section 4.4, if a node encounters a routing header with\n@@ -1303,7 +1319,7 @@ func (e *endpoint) handlePacket(pkt *stack.PacketBuffer) {\nstats.PacketsDelivered.Increment()\nif p := tcpip.TransportProtocolNumber(extHdr.Identifier); p == header.ICMPv6ProtocolNumber {\npkt.TransportProtocolNumber = p\n- e.handleICMP(pkt, hasFragmentHeader)\n+ e.handleICMP(pkt, hasFragmentHeader, routerAlert)\n} else {\nstats.PacketsDelivered.Increment()\nswitch res := e.dispatcher.DeliverTransportPacket(p, pkt); res {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "new_path": "pkg/tcpip/network/ipv6/ipv6_test.go", "diff": "@@ -385,6 +385,7 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\nname string\nextHdr func(nextHdr uint8) ([]byte, uint8)\nshouldAccept bool\n+ countersToBeIncremented func(*tcpip.Stats) []*tcpip.StatCounter\n// Should we expect an ICMP response and if so, with what contents?\nexpectICMP bool\nICMPType header.ICMPv6Type\n@@ -398,6 +399,42 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\nshouldAccept: true,\nexpectICMP: false,\n},\n+ {\n+ name: \"hopbyhop with router alert option\",\n+ extHdr: func(nextHdr uint8) ([]byte, uint8) {\n+ return []byte{\n+ nextHdr, 0,\n+\n+ // Router Alert option.\n+ 5, 2, 0, 0, 0, 0,\n+ }, hopByHopExtHdrID\n+ },\n+ shouldAccept: true,\n+ countersToBeIncremented: func(stats *tcpip.Stats) []*tcpip.StatCounter {\n+ return []*tcpip.StatCounter{stats.IP.OptionRouterAlertReceived}\n+ },\n+ },\n+ {\n+ name: \"hopbyhop with two router alert options\",\n+ extHdr: func(nextHdr uint8) ([]byte, uint8) {\n+ return []byte{\n+ nextHdr, 1,\n+\n+ // Router Alert option.\n+ 5, 2, 0, 0, 0, 0,\n+\n+ // Router Alert option.\n+ 5, 2, 0, 0, 0, 0, 0, 0,\n+ }, hopByHopExtHdrID\n+ },\n+ shouldAccept: false,\n+ countersToBeIncremented: func(stats *tcpip.Stats) []*tcpip.StatCounter {\n+ return []*tcpip.StatCounter{\n+ stats.IP.OptionRouterAlertReceived,\n+ stats.IP.MalformedPacketsReceived,\n+ }\n+ },\n+ },\n{\nname: \"hopbyhop with unknown option skippable action\",\nextHdr: func(nextHdr uint8) ([]byte, uint8) {\n@@ -924,14 +961,32 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\nDstAddr: dstAddr,\n})\n+ stats := s.Stats()\n+ var counters []*tcpip.StatCounter\n+ // Make sure that the counters we expect to be incremented are initially\n+ // set to zero.\n+ if fn := test.countersToBeIncremented; fn != nil {\n+ counters = fn(&stats)\n+ }\n+ for i := range counters {\n+ if got := counters[i].Value(); got != 0 {\n+ t.Errorf(\"before writing packet: got test.countersToBeIncremented(&stats)[%d].Value() = %d, want = 0\", i, got)\n+ }\n+ }\n+\ne.InjectInbound(ProtocolNumber, stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: hdr.View().ToVectorisedView(),\n}))\n- stats := s.Stats().UDP.PacketsReceived\n+ for i := range counters {\n+ if got := counters[i].Value(); got != 1 {\n+ t.Errorf(\"after writing packet: got test.countersToBeIncremented(&stats)[%d].Value() = %d, want = 1\", i, got)\n+ }\n+ }\n+ udpReceiveStat := stats.UDP.PacketsReceived\nif !test.shouldAccept {\n- if got := stats.Value(); got != 0 {\n+ if got := udpReceiveStat.Value(); got != 0 {\nt.Errorf(\"got UDP Rx Packets = %d, want = 0\", got)\n}\n@@ -977,7 +1032,7 @@ func TestReceiveIPv6ExtHdrs(t *testing.T) {\n}\n// Expect a UDP packet.\n- if got := stats.Value(); got != 1 {\n+ if got := udpReceiveStat.Value(); got != 1 {\nt.Errorf(\"got UDP Rx Packets = %d, want = 1\", got)\n}\nvar buf bytes.Buffer\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/mld_test.go", "new_path": "pkg/tcpip/network/ipv6/mld_test.go", "diff": "@@ -48,8 +48,7 @@ func validateMLDPacket(t *testing.T, p buffer.View, localAddress, remoteAddress\n),\nchecker.SrcAddr(localAddress),\nchecker.DstAddr(remoteAddress),\n- // Hop Limit for an MLD message must be 1 as per RFC 2710 section 3.\n- checker.TTL(1),\n+ checker.TTL(header.MLDHopLimit),\nchecker.MLD(mldType, header.MLDMinimumSize,\nchecker.MLDMaxRespDelay(0),\nchecker.MLDMulticastAddress(groupAddress),\n@@ -295,3 +294,153 @@ func TestSendQueuedMLDReports(t *testing.T) {\n})\n}\n}\n+\n+// createAndInjectMLDPacket creates and injects an MLD packet with the\n+// specified fields.\n+func createAndInjectMLDPacket(e *channel.Endpoint, mldType header.ICMPv6Type, hopLimit uint8, srcAddress tcpip.Address, withRouterAlertOption bool, routerAlertValue header.IPv6RouterAlertValue) {\n+ var extensionHeaders header.IPv6ExtHdrSerializer\n+ if withRouterAlertOption {\n+ extensionHeaders = header.IPv6ExtHdrSerializer{\n+ header.IPv6SerializableHopByHopExtHdr{\n+ &header.IPv6RouterAlertOption{Value: routerAlertValue},\n+ },\n+ }\n+ }\n+\n+ extensionHeadersLength := extensionHeaders.Length()\n+ payloadLength := extensionHeadersLength + header.ICMPv6HeaderSize + header.MLDMinimumSize\n+ buf := buffer.NewView(header.IPv6MinimumSize + payloadLength)\n+\n+ ip := header.IPv6(buf)\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLength),\n+ HopLimit: hopLimit,\n+ TransportProtocol: header.ICMPv6ProtocolNumber,\n+ SrcAddr: srcAddress,\n+ DstAddr: header.IPv6AllNodesMulticastAddress,\n+ ExtensionHeaders: extensionHeaders,\n+ })\n+\n+ icmp := header.ICMPv6(ip.Payload()[extensionHeadersLength:])\n+ icmp.SetType(mldType)\n+ mld := header.MLD(icmp.MessageBody())\n+ mld.SetMaximumResponseDelay(0)\n+ mld.SetMulticastAddress(header.IPv6Any)\n+ icmp.SetChecksum(header.ICMPv6Checksum(icmp, srcAddress, header.IPv6AllNodesMulticastAddress, buffer.VectorisedView{}))\n+\n+ e.InjectInbound(ipv6.ProtocolNumber, &stack.PacketBuffer{\n+ Data: buf.ToVectorisedView(),\n+ })\n+}\n+\n+func TestMLDPacketValidation(t *testing.T) {\n+ const (\n+ nicID = 1\n+ linkLocalAddr2 = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\n+ )\n+\n+ tests := []struct {\n+ name string\n+ messageType header.ICMPv6Type\n+ srcAddr tcpip.Address\n+ includeRouterAlertOption bool\n+ routerAlertValue header.IPv6RouterAlertValue\n+ hopLimit uint8\n+ expectValidMLD bool\n+ getMessageTypeStatValue func(tcpip.Stats) uint64\n+ }{\n+ {\n+ name: \"valid\",\n+ messageType: header.ICMPv6MulticastListenerQuery,\n+ includeRouterAlertOption: true,\n+ routerAlertValue: header.IPv6RouterAlertMLD,\n+ srcAddr: linkLocalAddr2,\n+ hopLimit: header.MLDHopLimit,\n+ expectValidMLD: true,\n+ getMessageTypeStatValue: func(stats tcpip.Stats) uint64 { return stats.ICMP.V6.PacketsReceived.MulticastListenerQuery.Value() },\n+ },\n+ {\n+ name: \"bad hop limit\",\n+ messageType: header.ICMPv6MulticastListenerReport,\n+ includeRouterAlertOption: true,\n+ routerAlertValue: header.IPv6RouterAlertMLD,\n+ srcAddr: linkLocalAddr2,\n+ hopLimit: header.MLDHopLimit + 1,\n+ expectValidMLD: false,\n+ getMessageTypeStatValue: func(stats tcpip.Stats) uint64 { return stats.ICMP.V6.PacketsReceived.MulticastListenerReport.Value() },\n+ },\n+ {\n+ name: \"src ip not link local\",\n+ messageType: header.ICMPv6MulticastListenerReport,\n+ includeRouterAlertOption: true,\n+ routerAlertValue: header.IPv6RouterAlertMLD,\n+ srcAddr: globalAddr,\n+ hopLimit: header.MLDHopLimit,\n+ expectValidMLD: false,\n+ getMessageTypeStatValue: func(stats tcpip.Stats) uint64 { return stats.ICMP.V6.PacketsReceived.MulticastListenerReport.Value() },\n+ },\n+ {\n+ name: \"missing router alert ip option\",\n+ messageType: header.ICMPv6MulticastListenerDone,\n+ includeRouterAlertOption: false,\n+ srcAddr: linkLocalAddr2,\n+ hopLimit: header.MLDHopLimit,\n+ expectValidMLD: false,\n+ getMessageTypeStatValue: func(stats tcpip.Stats) uint64 { return stats.ICMP.V6.PacketsReceived.MulticastListenerDone.Value() },\n+ },\n+ {\n+ name: \"incorrect router alert value\",\n+ messageType: header.ICMPv6MulticastListenerDone,\n+ includeRouterAlertOption: true,\n+ routerAlertValue: header.IPv6RouterAlertRSVP,\n+ srcAddr: linkLocalAddr2,\n+ hopLimit: header.MLDHopLimit,\n+ expectValidMLD: false,\n+ getMessageTypeStatValue: func(stats tcpip.Stats) uint64 { return stats.ICMP.V6.PacketsReceived.MulticastListenerDone.Value() },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{\n+ MLD: ipv6.MLDOptions{\n+ Enabled: true,\n+ },\n+ })},\n+ })\n+ e := channel.New(nicID, header.IPv6MinimumMTU, \"\")\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ stats := s.Stats()\n+ // Verify that every relevant stats is zero'd before we send a packet.\n+ if got := test.getMessageTypeStatValue(s.Stats()); got != 0 {\n+ t.Errorf(\"got test.getMessageTypeStatValue(s.Stats()) = %d, want = 0\", got)\n+ }\n+ if got := stats.ICMP.V6.PacketsReceived.Invalid.Value(); got != 0 {\n+ t.Errorf(\"got stats.ICMP.V6.PacketsReceived.Invalid.Value() = %d, want = 0\", got)\n+ }\n+ if got := stats.IP.PacketsDelivered.Value(); got != 0 {\n+ t.Fatalf(\"got stats.IP.PacketsDelivered.Value() = %d, want = 0\", got)\n+ }\n+ createAndInjectMLDPacket(e, test.messageType, test.hopLimit, test.srcAddr, test.includeRouterAlertOption, test.routerAlertValue)\n+ // We always expect the packet to pass IP validation.\n+ if got := stats.IP.PacketsDelivered.Value(); got != 1 {\n+ t.Fatalf(\"got stats.IP.PacketsDelivered.Value() = %d, want = 1\", got)\n+ }\n+ // Even when the MLD-specific validation checks fail, we expect the\n+ // corresponding MLD counter to be incremented.\n+ if got := test.getMessageTypeStatValue(s.Stats()); got != 1 {\n+ t.Errorf(\"got test.getMessageTypeStatValue(s.Stats()) = %d, want = 1\", got)\n+ }\n+ var expectedInvalidCount uint64\n+ if !test.expectValidMLD {\n+ expectedInvalidCount = 1\n+ }\n+ if got := stats.ICMP.V6.PacketsReceived.Invalid.Value(); got != expectedInvalidCount {\n+ t.Errorf(\"got stats.ICMP.V6.PacketsReceived.Invalid.Value() = %d, want = %d\", got, expectedInvalidCount)\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/multicast_group_test.go", "new_path": "pkg/tcpip/network/multicast_group_test.go", "diff": "@@ -37,7 +37,8 @@ const (\nstackIPv4Addr = tcpip.Address(\"\\x0a\\x00\\x00\\x01\")\ndefaultIPv4PrefixLength = 24\n- ipv6Addr = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n+ linkLocalIPv6Addr1 = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n+ linkLocalIPv6Addr2 = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\nipv4MulticastAddr1 = tcpip.Address(\"\\xe0\\x00\\x00\\x03\")\nipv4MulticastAddr2 = tcpip.Address(\"\\xe0\\x00\\x00\\x04\")\n@@ -69,7 +70,7 @@ var (\nreturn uint8(ipv4.UnsolicitedReportIntervalMax / decisecond)\n}()\n- ipv6AddrSNMC = header.SolicitedNodeAddr(ipv6Addr)\n+ ipv6AddrSNMC = header.SolicitedNodeAddr(linkLocalIPv6Addr1)\n)\n// validateMLDPacket checks that a passed PacketInfo is an IPv6 MLD packet\n@@ -82,7 +83,7 @@ func validateMLDPacket(t *testing.T, p channel.PacketInfo, remoteAddress tcpip.A\nchecker.IPv6ExtHdr(\nchecker.IPv6HopByHopExtensionHeader(checker.IPv6RouterAlert(header.IPv6RouterAlertMLD)),\n),\n- checker.SrcAddr(ipv6Addr),\n+ checker.SrcAddr(linkLocalIPv6Addr1),\nchecker.DstAddr(remoteAddress),\n// Hop Limit for an MLD message must be 1 as per RFC 2710 section 3.\nchecker.TTL(1),\n@@ -153,8 +154,8 @@ func createStackWithLinkEndpoint(t *testing.T, v4, mgpEnabled bool, e stack.Link\nif err := s.AddAddressWithPrefix(nicID, ipv4.ProtocolNumber, addr); err != nil {\nt.Fatalf(\"AddAddressWithPrefix(%d, %d, %s): %s\", nicID, ipv4.ProtocolNumber, addr, err)\n}\n- if err := s.AddAddress(nicID, ipv6.ProtocolNumber, ipv6Addr); err != nil {\n- t.Fatalf(\"AddAddress(%d, %d, %s): %s\", nicID, ipv6.ProtocolNumber, ipv6Addr, err)\n+ if err := s.AddAddress(nicID, ipv6.ProtocolNumber, linkLocalIPv6Addr1); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s): %s\", nicID, ipv6.ProtocolNumber, linkLocalIPv6Addr1, err)\n}\nreturn s, clock\n@@ -236,29 +237,33 @@ func createAndInjectIGMPPacket(e *channel.Endpoint, igmpType byte, maxRespTime b\n// createAndInjectMLDPacket creates and injects an MLD packet with the\n// specified fields.\n-//\n-// Note, the router alert option is not included in this packet.\n-//\n-// TODO(b/162198658): set the router alert option.\nfunc createAndInjectMLDPacket(e *channel.Endpoint, mldType uint8, maxRespDelay byte, groupAddress tcpip.Address) {\n- icmpSize := header.ICMPv6HeaderSize + header.MLDMinimumSize\n- buf := buffer.NewView(header.IPv6MinimumSize + icmpSize)\n+ extensionHeaders := header.IPv6ExtHdrSerializer{\n+ header.IPv6SerializableHopByHopExtHdr{\n+ &header.IPv6RouterAlertOption{Value: header.IPv6RouterAlertMLD},\n+ },\n+ }\n+\n+ extensionHeadersLength := extensionHeaders.Length()\n+ payloadLength := extensionHeadersLength + header.ICMPv6HeaderSize + header.MLDMinimumSize\n+ buf := buffer.NewView(header.IPv6MinimumSize + payloadLength)\nip := header.IPv6(buf)\nip.Encode(&header.IPv6Fields{\n- PayloadLength: uint16(icmpSize),\n+ PayloadLength: uint16(payloadLength),\nHopLimit: header.MLDHopLimit,\nTransportProtocol: header.ICMPv6ProtocolNumber,\n- SrcAddr: header.IPv4Any,\n+ SrcAddr: linkLocalIPv6Addr2,\nDstAddr: header.IPv6AllNodesMulticastAddress,\n+ ExtensionHeaders: extensionHeaders,\n})\n- icmp := header.ICMPv6(buf[header.IPv6MinimumSize:])\n+ icmp := header.ICMPv6(ip.Payload()[extensionHeadersLength:])\nicmp.SetType(header.ICMPv6Type(mldType))\nmld := header.MLD(icmp.MessageBody())\nmld.SetMaximumResponseDelay(uint16(maxRespDelay))\nmld.SetMulticastAddress(groupAddress)\n- icmp.SetChecksum(header.ICMPv6Checksum(icmp, header.IPv6Any, header.IPv6AllNodesMulticastAddress, buffer.VectorisedView{}))\n+ icmp.SetChecksum(header.ICMPv6Checksum(icmp, linkLocalIPv6Addr2, header.IPv6AllNodesMulticastAddress, buffer.VectorisedView{}))\ne.InjectInbound(ipv6.ProtocolNumber, &stack.PacketBuffer{\nData: buf.ToVectorisedView(),\n" } ]
Go
Apache License 2.0
google/gvisor
Validate MLD packets Fixes #5490 PiperOrigin-RevId: 359401532
259,858
25.02.2021 10:54:14
28,800
56053f084f06e61e963b0007e7bf99e69a0f9144
Strip all non-numeric characters from version. This will fix debian packaging. Updates
[ { "change_type": "MODIFY", "old_path": "tools/bazeldefs/BUILD", "new_path": "tools/bazeldefs/BUILD", "diff": "@@ -41,7 +41,7 @@ config_setting(\ngenrule(\nname = \"version\",\nouts = [\"version.txt\"],\n- cmd = \"cat bazel-out/stable-status.txt | grep STABLE_VERSION | cut -d' ' -f2- >$@\",\n+ cmd = \"cat bazel-out/stable-status.txt | grep STABLE_VERSION | cut -d' ' -f2- | sed 's/^[^[:digit:]]*//g' >$@\",\nstamp = True,\nvisibility = [\"//:sandbox\"],\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Strip all non-numeric characters from version. This will fix debian packaging. Updates #5510 PiperOrigin-RevId: 359563378
259,875
25.02.2021 12:54:36
28,800
e50ee26207a99930be966bd48e04f5bccd85cc05
Implement SEM_STAT_ANY cmd of semctl.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/semaphore/semaphore.go", "new_path": "pkg/sentry/kernel/semaphore/semaphore.go", "diff": "@@ -381,15 +381,24 @@ func (s *Set) Change(ctx context.Context, creds *auth.Credentials, owner fs.File\n// GetStat extracts semid_ds information from the set.\nfunc (s *Set) GetStat(creds *auth.Credentials) (*linux.SemidDS, error) {\n+ // \"The calling process must have read permission on the semaphore set.\"\n+ return s.semStat(creds, fs.PermMask{Read: true})\n+}\n+\n+// GetStatAny extracts semid_ds information from the set without requiring read access.\n+func (s *Set) GetStatAny(creds *auth.Credentials) (*linux.SemidDS, error) {\n+ return s.semStat(creds, fs.PermMask{})\n+}\n+\n+func (s *Set) semStat(creds *auth.Credentials, permMask fs.PermMask) (*linux.SemidDS, error) {\ns.mu.Lock()\ndefer s.mu.Unlock()\n- // \"The calling process must have read permission on the semaphore set.\"\n- if !s.checkPerms(creds, fs.PermMask{Read: true}) {\n+ if !s.checkPerms(creds, permMask) {\nreturn nil, syserror.EACCES\n}\n- ds := &linux.SemidDS{\n+ return &linux.SemidDS{\nSemPerm: linux.IPCPerm{\nKey: uint32(s.key),\nUID: uint32(creds.UserNamespace.MapFromKUID(s.owner.UID)),\n@@ -402,8 +411,7 @@ func (s *Set) GetStat(creds *auth.Credentials) (*linux.SemidDS, error) {\nSemOTime: s.opTime.TimeT(),\nSemCTime: s.changeTime.TimeT(),\nSemNSems: uint64(s.Size()),\n- }\n- return ds, nil\n+ }, nil\n}\n// SetVal overrides a semaphore value, waking up waiters as needed.\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_STAT_ANY not supported.\", nil),\n+ 66: syscalls.Supported(\"semctl\", Semctl),\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_STAT_ANY not supported.\", nil),\n+ 191: syscalls.Supported(\"semctl\", Semctl),\n192: syscalls.Supported(\"semtimedop\", Semtimedop),\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": "@@ -220,8 +220,16 @@ func Semctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn uintptr(semid), nil, err\ncase linux.SEM_STAT_ANY:\n- t.Kernel().EmitUnimplementedEvent(t)\n- fallthrough\n+ arg := args[3].Pointer()\n+ // id is an index in SEM_STAT.\n+ semid, ds, err := semStatAny(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\ndefault:\nreturn 0, nil, syserror.EINVAL\n@@ -272,7 +280,23 @@ func semStat(t *kernel.Task, index int32) (int32, *linux.SemidDS, error) {\n}\ncreds := auth.CredentialsFromContext(t)\nds, err := set.GetStat(creds)\n- return set.ID, ds, err\n+ if err != nil {\n+ return 0, ds, err\n+ }\n+ return set.ID, ds, nil\n+}\n+\n+func semStatAny(t *kernel.Task, index int32) (int32, *linux.SemidDS, error) {\n+ set := t.IPCNamespace().SemaphoreRegistry().FindByIndex(index)\n+ if set == nil {\n+ return 0, nil, syserror.EINVAL\n+ }\n+ creds := auth.CredentialsFromContext(t)\n+ ds, err := set.GetStatAny(creds)\n+ if err != nil {\n+ return 0, ds, err\n+ }\n+ return set.ID, ds, nil\n}\nfunc setVal(t *kernel.Task, id int32, num int32, val int16) error {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/semaphore.cc", "new_path": "test/syscalls/linux/semaphore.cc", "diff": "@@ -68,6 +68,15 @@ class AutoSem {\nint id_ = -1;\n};\n+bool operator==(struct semid_ds const& a, struct semid_ds const& b) {\n+ return a.sem_perm.__key == b.sem_perm.__key &&\n+ a.sem_perm.uid == b.sem_perm.uid && a.sem_perm.gid == b.sem_perm.gid &&\n+ a.sem_perm.cuid == b.sem_perm.cuid &&\n+ a.sem_perm.cgid == b.sem_perm.cgid &&\n+ a.sem_perm.mode == b.sem_perm.mode && a.sem_otime == b.sem_otime &&\n+ a.sem_ctime == b.sem_ctime && a.sem_nsems == b.sem_nsems;\n+}\n+\nTEST(SemaphoreTest, SemGet) {\n// Test creation and lookup.\nAutoSem sem(semget(1, 10, IPC_CREAT));\n@@ -843,6 +852,10 @@ TEST(SemaphoreTest, SemopGetncntOnSignal_NoRandomSave) {\nEXPECT_EQ(semctl(sem.get(), 0, GETNCNT), 0);\n}\n+#ifndef SEM_STAT_ANY\n+#define SEM_STAT_ANY 20\n+#endif // SEM_STAT_ANY\n+\nTEST(SemaphoreTest, IpcInfo) {\nconstexpr int kLoops = 5;\nstd::set<int> sem_ids;\n@@ -868,15 +881,7 @@ TEST(SemaphoreTest, IpcInfo) {\nif (sem_ids.find(sem_id) != sem_ids.end()) {\nstruct semid_ds ipc_stat_ds;\nASSERT_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+ EXPECT_TRUE(ds == ipc_stat_ds);\n// Remove the semaphore set's read permission.\nstruct semid_ds ipc_set_ds;\n@@ -884,9 +889,21 @@ TEST(SemaphoreTest, IpcInfo) {\nipc_set_ds.sem_perm.gid = getgid();\n// Keep the semaphore set's write permission so that it could be removed.\nipc_set_ds.sem_perm.mode = 0200;\n+ // IPC_SET command here updates sem_ctime member of the sem.\nASSERT_THAT(semctl(sem_id, 0, IPC_SET, &ipc_set_ds), SyscallSucceeds());\nASSERT_THAT(semctl(i, 0, SEM_STAT, &ds), SyscallFailsWithErrno(EACCES));\n-\n+ int val = semctl(i, 0, SEM_STAT_ANY, &ds);\n+ if (val == -1) {\n+ // Only if the kernel doesn't support the command SEM_STAT_ANY.\n+ EXPECT_TRUE(errno == EINVAL || errno == EFAULT);\n+ } else {\n+ EXPECT_EQ(sem_id, val);\n+ EXPECT_LE(ipc_stat_ds.sem_ctime, ds.sem_ctime);\n+ ipc_stat_ds.sem_ctime = 0;\n+ ipc_stat_ds.sem_perm.mode = 0200;\n+ ds.sem_ctime = 0;\n+ EXPECT_TRUE(ipc_stat_ds == ds);\n+ }\nsem_ids_before_max_index.insert(sem_id);\n}\n}\n@@ -946,15 +963,7 @@ TEST(SemaphoreTest, SemInfo) {\nif (sem_ids.find(sem_id) != sem_ids.end()) {\nstruct semid_ds ipc_stat_ds;\nASSERT_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+ EXPECT_TRUE(ds == ipc_stat_ds);\n// Remove the semaphore set's read permission.\nstruct semid_ds ipc_set_ds;\n@@ -962,9 +971,22 @@ TEST(SemaphoreTest, SemInfo) {\nipc_set_ds.sem_perm.gid = getgid();\n// Keep the semaphore set's write permission so that it could be removed.\nipc_set_ds.sem_perm.mode = 0200;\n+ // IPC_SET command here updates sem_ctime member of the sem.\nASSERT_THAT(semctl(sem_id, 0, IPC_SET, &ipc_set_ds), SyscallSucceeds());\nASSERT_THAT(semctl(i, 0, SEM_STAT, &ds), SyscallFailsWithErrno(EACCES));\n-\n+ int val = semctl(i, 0, SEM_STAT_ANY, &ds);\n+\n+ if (val == -1) {\n+ // Only if the kernel doesn't support the command SEM_STAT_ANY.\n+ EXPECT_TRUE(errno == EINVAL || errno == EFAULT);\n+ } else {\n+ EXPECT_EQ(val, sem_id);\n+ EXPECT_LE(ipc_stat_ds.sem_ctime, ds.sem_ctime);\n+ ipc_stat_ds.sem_ctime = 0;\n+ ipc_stat_ds.sem_perm.mode = 0200;\n+ ds.sem_ctime = 0;\n+ EXPECT_TRUE(ipc_stat_ds == ds);\n+ }\nsem_ids_before_max_index.insert(sem_id);\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement SEM_STAT_ANY cmd of semctl. PiperOrigin-RevId: 359591577
259,896
25.02.2021 16:27:30
28,800
f3de211bb764d4e720879509debf918d37a71ce7
RACK: recovery logic should check for receive window before re-transmitting. Use maybeSendSegment while sending segments in RACK recovery which checks if the receiver has space and splits the segments when the segment size is greater than MSS.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/rack.go", "new_path": "pkg/tcpip/transport/tcp/rack.go", "diff": "@@ -475,9 +475,11 @@ func (rc *rackControl) DoRecovery(_ *segment, fastRetransmit bool) {\nbreak\n}\n- snd.outstanding++\n+ if sent := snd.maybeSendSegment(seg, int(snd.ep.scoreboard.SMSS()), snd.sndUna.Add(snd.sndWnd)); !sent {\n+ break\n+ }\ndataSent = true\n- snd.sendSegment(seg)\n+ snd.outstanding += snd.pCount(seg, snd.maxPayloadSize)\n}\nsnd.postXmit(dataSent, true /* shouldScheduleProbe */)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_rack_test.go", "diff": "@@ -987,3 +987,71 @@ func TestRACKUpdateSackedOut(t *testing.T) {\n// test completes.\n<-probeDone\n}\n+\n+// TestRACKWithWindowFull tests that RACK honors the receive window size.\n+func TestRACKWithWindowFull(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ setStackSACKPermitted(t, c, true)\n+ setStackRACKPermitted(t, c)\n+ createConnectedWithSACKAndTS(c)\n+\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ const numPkts = 10\n+ data := make([]byte, numPkts*maxPayload)\n+ for i := range data {\n+ data[i] = byte(i)\n+ }\n+\n+ // Write the data.\n+ var r bytes.Reader\n+ r.Reset(data)\n+ if _, err := c.EP.Write(&r, tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+\n+ bytesRead := 0\n+ for i := 0; i < numPkts; i++ {\n+ c.ReceiveAndCheckPacketWithOptions(data, bytesRead, maxPayload, tsOptionSize)\n+ bytesRead += maxPayload\n+ if i == 0 {\n+ // Send ACK for the first packet to establish RTT.\n+ c.SendAck(seq, maxPayload)\n+ }\n+ }\n+\n+ // SACK for #10 packet.\n+ start := c.IRS.Add(seqnum.Size(1 + (numPkts-1)*maxPayload))\n+ end := start.Add(seqnum.Size(maxPayload))\n+ c.SendAckWithSACK(seq, 2*maxPayload, []header.SACKBlock{{start, end}})\n+\n+ var info tcpip.TCPInfoOption\n+ if err := c.EP.GetSockOpt(&info); err != nil {\n+ t.Fatalf(\"GetSockOpt failed: %v\", err)\n+ }\n+ // Wait for RTT to trigger recovery.\n+ time.Sleep(info.RTT)\n+\n+ // Expect retransmission of #2 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, 2*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Send ACK for #2 packet.\n+ c.SendAck(seq, 3*maxPayload)\n+\n+ // Expect retransmission of #3 packet.\n+ c.ReceiveAndCheckPacketWithOptions(data, 3*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Send ACK with zero window size.\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: seq,\n+ AckNum: c.IRS.Add(1 + 4*maxPayload),\n+ RcvWnd: 0,\n+ })\n+\n+ // No packet should be received as the receive window size is zero.\n+ c.CheckNoPacket(\"unexpected packet received after userTimeout has expired\")\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
RACK: recovery logic should check for receive window before re-transmitting. Use maybeSendSegment while sending segments in RACK recovery which checks if the receiver has space and splits the segments when the segment size is greater than MSS. PiperOrigin-RevId: 359641097