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,951 | 04.10.2021 13:55:19 | 25,200 | 6c1237da03bf52d51284e15e6c6c2b6776cd7da6 | Reply to invalid ACKs even when accept queue is full
Before checking if there is space in the accept queue, the listener
should verify that the cookie is valid. If it is not, instead of
silently dropping the packet, reply with an RST.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -583,23 +583,6 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nreturn nil\ncase s.flags.Contains(header.TCPFlagAck):\n- // Keep hold of acceptMu until the new endpoint is in the accept queue (or\n- // if there is an error), to guarantee that we will keep our spot in the\n- // queue even if another handshake from the syn queue completes.\n- e.acceptMu.Lock()\n- if e.acceptQueue.isFull() {\n- // Silently drop the ack as the application can't accept\n- // the connection at this point. The ack will be\n- // retransmitted by the sender anyway and we can\n- // complete the connection at the time of retransmit if\n- // the backlog has space.\n- e.acceptMu.Unlock()\n- e.stack.Stats().TCP.ListenOverflowAckDrop.Increment()\n- e.stats.ReceiveErrors.ListenOverflowAckDrop.Increment()\n- e.stack.Stats().DroppedPackets.Increment()\n- return nil\n- }\n-\niss := s.ackNumber - 1\nirs := s.sequenceNumber - 1\n@@ -615,7 +598,6 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\n// Validate the cookie.\ndata, ok := ctx.isCookieValid(s.id, iss, irs)\nif !ok || int(data) >= len(mssTable) {\n- e.acceptMu.Unlock()\ne.stack.Stats().TCP.ListenOverflowInvalidSynCookieRcvd.Increment()\ne.stack.Stats().DroppedPackets.Increment()\n@@ -636,6 +618,24 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\n// ACK was received from the sender.\nreturn replyWithReset(e.stack, s, e.sendTOS, e.ttl)\n}\n+\n+ // Keep hold of acceptMu until the new endpoint is in the accept queue (or\n+ // if there is an error), to guarantee that we will keep our spot in the\n+ // queue even if another handshake from the syn queue completes.\n+ e.acceptMu.Lock()\n+ if e.acceptQueue.isFull() {\n+ // Silently drop the ack as the application can't accept\n+ // the connection at this point. The ack will be\n+ // retransmitted by the sender anyway and we can\n+ // complete the connection at the time of retransmit if\n+ // the backlog has space.\n+ e.acceptMu.Unlock()\n+ e.stack.Stats().TCP.ListenOverflowAckDrop.Increment()\n+ e.stats.ReceiveErrors.ListenOverflowAckDrop.Increment()\n+ e.stack.Stats().DroppedPackets.Increment()\n+ return nil\n+ }\n+\ne.stack.Stats().TCP.ListenOverflowSynCookieRcvd.Increment()\n// Create newly accepted endpoint and deliver it.\nrcvdSynOptions := header.TCPSynOptions{\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/tcp_listen_backlog_test.go",
"new_path": "test/packetimpact/tests/tcp_listen_backlog_test.go",
"diff": "@@ -150,18 +150,11 @@ func TestTCPListenBacklog(t *testing.T) {\nconn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{})\ndefer conn.Close(t)\nconn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\n- if !dut.Uname.IsLinux() {\n- // TODO(https://gvisor.dev/issues/6683): Expect a RST.\n- if got, err := conn.Expect(t, testbench.TCP{}, time.Second); err == nil {\n- t.Errorf(\"expected no TCP frame, got %s\", got)\n- }\n- } else {\nif got, err := conn.Expect(t, testbench.TCP{}, time.Second); err != nil {\nt.Errorf(\"expected TCP frame: %s\", err)\n} else if got, want := *got.Flags, header.TCPFlagRst; got != want {\nt.Errorf(\"got %s, want %s\", got, want)\n}\n- }\n}()\nfunc() {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Reply to invalid ACKs even when accept queue is full
Before checking if there is space in the accept queue, the listener
should verify that the cookie is valid. If it is not, instead of
silently dropping the packet, reply with an RST.
Fixes #6683
PiperOrigin-RevId: 400807346 |
259,907 | 06.10.2021 11:27:58 | 25,200 | a259115490332409b284868a0d25e39f2d63a3fe | Add global lisafs kernel flag. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -78,11 +78,19 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n-// VFS2Enabled is set to true when VFS2 is enabled. Added as a global for allow\n-// easy access everywhere. To be removed once VFS2 becomes the default.\n+// VFS2Enabled is set to true when VFS2 is enabled. Added as a global to allow\n+// easy access everywhere.\n+//\n+// TODO(gvisor.dev/issue/1624): Remove when VFS1 is no longer used.\nvar VFS2Enabled = false\n-// FUSEEnabled is set to true when FUSE is enabled. Added as a global for allow\n+// LISAFSEnabled is set to true when lisafs protocol is enabled. Added as a\n+// global to allow easy access everywhere.\n+//\n+// TODO(gvisor.dev/issue/6319): Remove when lisafs is default.\n+var LISAFSEnabled = false\n+\n+// FUSEEnabled is set to true when FUSE is enabled. Added as a global to allow\n// easy access everywhere. To be removed once FUSE is completed.\nvar FUSEEnabled = false\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -241,10 +241,8 @@ func New(args Args) (*Loader, error) {\n// Is this a VFSv2 kernel?\nif args.Conf.VFS2 {\nkernel.VFS2Enabled = true\n- if args.Conf.FUSE {\n- kernel.FUSEEnabled = true\n- }\n-\n+ kernel.FUSEEnabled = args.Conf.FUSE\n+ kernel.LISAFSEnabled = args.Conf.Lisafs\nvfs2.Override()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add global lisafs kernel flag.
PiperOrigin-RevId: 401296116 |
260,004 | 07.10.2021 15:30:09 | 25,200 | 3517d070cc3128ad3439e10b8abb42b7df60c2b2 | Track UDP packets performing REDIRECT NAT | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -132,36 +132,12 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, address\npanic(\"redirect target is supported only on output and prerouting hooks\")\n}\n- switch protocol := pkt.TransportProtocolNumber; protocol {\n- case header.UDPProtocolNumber:\n- udpHeader := header.UDP(pkt.TransportHeader().View())\n-\n- if hook == Output {\n- // Only calculate the checksum if offloading isn't supported.\n- requiresChecksum := r.RequiresTXTransportChecksum()\n- rewritePacket(\n- pkt.Network(),\n- udpHeader,\n- false, /* updateSRCFields */\n- requiresChecksum,\n- requiresChecksum,\n- rt.Port,\n- address,\n- )\n- } else {\n- udpHeader.SetDestinationPort(rt.Port)\n- }\n-\n- pkt.NatDone = true\n- case header.TCPProtocolNumber:\nif t := pkt.tuple; t != nil {\nt.conn.performNAT(pkt, hook, r, rt.Port, address, true /* dnat */)\n- }\n- default:\n- return RuleDrop, 0\n+ return RuleAccept, 0\n}\n- return RuleAccept, 0\n+ return RuleDrop, 0\n}\n// SNATTarget modifies the source port/IP in the outgoing packets.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Track UDP packets performing REDIRECT NAT
PiperOrigin-RevId: 401620449 |
259,853 | 07.10.2021 15:47:05 | 25,200 | 710e51372dc822501769d700531ec6f0f81221e6 | tests: use a proper path to the kvm device | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm.go",
"new_path": "pkg/sentry/platform/kvm/kvm.go",
"diff": "@@ -77,7 +77,11 @@ var (\n// OpenDevice opens the KVM device at /dev/kvm and returns the File.\nfunc OpenDevice() (*os.File, error) {\n- f, err := os.OpenFile(\"/dev/kvm\", unix.O_RDWR, 0)\n+ dev, ok := os.LookupEnv(\"GVISOR_KVM_DEV\")\n+ if !ok {\n+ dev = \"/dev/kvm\"\n+ }\n+ f, err := os.OpenFile(dev, unix.O_RDWR, 0)\nif err != nil {\nreturn nil, fmt.Errorf(\"error opening /dev/kvm: %v\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | tests: use a proper path to the kvm device
PiperOrigin-RevId: 401624134 |
259,962 | 07.10.2021 16:29:09 | 25,200 | 0743a862e5e90368291ad4ef9061f3c4ca3a065f | Update compat list for tcpdump.
A libpcap change broke tcpdump support in gvisor. As a result tcpdump
w/ libpcap> 1.10 fails with gvisor.
Updates | [
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/compatibility.md",
"new_path": "g3doc/user_guide/compatibility.md",
"diff": "@@ -42,6 +42,9 @@ Most common utilities work. Note that:\n* Some tools, such as `tcpdump` and old versions of `ping`, require explicitly\nenabling raw sockets via the unsafe `--net-raw` runsc flag.\n+ * In case of tcpdump the following invocations will work\n+ * tcpdump -i any\n+ * tcpdump -i \\<device-name\\> -p (-p disables promiscuous mode)\n* Different Docker images can behave differently. For example, Alpine Linux\nand Ubuntu have different `ip` binaries.\n@@ -82,7 +85,7 @@ Most common utilities work. Note that:\n| sshd | Partially working. Job control [in progress](https://gvisor.dev/issue/154). |\n| strace | Working. |\n| tar | Working. |\n-| tcpdump | Working. [Promiscuous mode in progress](https://gvisor.dev/issue/3333). |\n+| tcpdump | Working [only with libpcap versions < 1.10](https://github.com/google/gvisor/issues/6699), [Promiscuous mode in progress](https://gvisor.dev/issue/3333). |\n| top | Working. |\n| uptime | Working. |\n| vim | Working. |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update compat list for tcpdump.
A libpcap change broke tcpdump support in gvisor. As a result tcpdump
w/ libpcap> 1.10 fails with gvisor.
Updates #6664, #6699
PiperOrigin-RevId: 401633061 |
259,896 | 07.10.2021 16:48:28 | 25,200 | 487651ac46f302592ccffc9e5a4336a331010e42 | Add a new metric to detect the number of spurious loss recoveries.
Implements RFC 3522 (Eifel detection algorithm) to detect if the connection
entered loss recovery unnecessarily.
Added a new metric to count the total number of spurious loss recoveries.
Added tests to verify the new metric. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -274,6 +274,7 @@ var Metrics = tcpip.Stats{\nChecksumErrors: mustCreateMetric(\"/netstack/tcp/checksum_errors\", \"Number of segments dropped due to bad checksums.\"),\nFailedPortReservations: mustCreateMetric(\"/netstack/tcp/failed_port_reservations\", \"Number of time TCP failed to reserve a port.\"),\nSegmentsAckedWithDSACK: mustCreateMetric(\"/netstack/tcp/segments_acked_with_dsack\", \"Number of segments for which DSACK was received.\"),\n+ SpuriousRecovery: mustCreateMetric(\"/netstack/tcp/spurious_recovery\", \"Number of times the connection entered loss recovery spuriously.\"),\n},\nUDP: tcpip.UDPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/udp/packets_received\", \"Number of UDP datagrams received via HandlePacket.\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/tcp.go",
"new_path": "pkg/tcpip/stack/tcp.go",
"diff": "@@ -289,6 +289,12 @@ type TCPSenderState struct {\n// RACKState holds the state related to RACK loss detection algorithm.\nRACKState TCPRACKState\n+\n+ // RetransmitTS records the timestamp used to detect spurious recovery.\n+ RetransmitTS uint32\n+\n+ // SpuriousRecovery indicates if the sender entered recovery spuriously.\n+ SpuriousRecovery bool\n}\n// TCPSACKInfo holds TCP SACK related information for a given TCP endpoint.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -1865,6 +1865,10 @@ type TCPStats struct {\n// SegmentsAckedWithDSACK is the number of segments acknowledged with\n// DSACK.\nSegmentsAckedWithDSACK *StatCounter\n+\n+ // SpuriousRecovery is the number of times the connection entered loss\n+ // recovery spuriously.\n+ SpuriousRecovery *StatCounter\n}\n// UDPStats collects UDP-specific stats.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2999,6 +2999,8 @@ func (e *endpoint) completeStateLocked() stack.TCPEndpointState {\n}\ns.Sender.RACKState = e.snd.rc.TCPRACKState\n+ s.Sender.RetransmitTS = e.snd.retransmitTS\n+ s.Sender.SpuriousRecovery = e.snd.spuriousRecovery\nreturn s\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -144,6 +144,15 @@ type sender struct {\n// probeTimer and probeWaker are used to schedule PTO for RACK TLP algorithm.\nprobeTimer timer `state:\"nosave\"`\nprobeWaker sleep.Waker `state:\"nosave\"`\n+\n+ // spuriousRecovery indicates whether the sender entered recovery\n+ // spuriously as described in RFC3522 Section 3.2.\n+ spuriousRecovery bool\n+\n+ // retransmitTS is the timestamp at which the sender sends retransmitted\n+ // segment after entering an RTO for the first time as described in\n+ // RFC3522 Section 3.2.\n+ retransmitTS uint32\n}\n// rtt is a synchronization wrapper used to appease stateify. See the comment\n@@ -425,6 +434,13 @@ func (s *sender) retransmitTimerExpired() bool {\nreturn true\n}\n+ // Initialize the variables used to detect spurious recovery after\n+ // entering RTO.\n+ //\n+ // See: https://www.rfc-editor.org/rfc/rfc3522.html#section-3.2 Step 1.\n+ s.spuriousRecovery = false\n+ s.retransmitTS = 0\n+\n// TODO(b/147297758): Band-aid fix, retransmitTimer can fire in some edge cases\n// when writeList is empty. Remove this once we have a proper fix for this\n// issue.\n@@ -495,6 +511,10 @@ func (s *sender) retransmitTimerExpired() bool {\ns.leaveRecovery()\n}\n+ // Record retransmitTS if the sender is not in recovery as per:\n+ // https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 2\n+ s.recordRetransmitTS()\n+\ns.state = tcpip.RTORecovery\ns.cc.HandleRTOExpired()\n@@ -958,6 +978,13 @@ func (s *sender) sendData() {\n}\nfunc (s *sender) enterRecovery() {\n+ // Initialize the variables used to detect spurious recovery after\n+ // entering recovery.\n+ //\n+ // See: https://www.rfc-editor.org/rfc/rfc3522.html#section-3.2 Step 1.\n+ s.spuriousRecovery = false\n+ s.retransmitTS = 0\n+\ns.FastRecovery.Active = true\n// Save state to reflect we're now in fast recovery.\n//\n@@ -972,6 +999,11 @@ func (s *sender) enterRecovery() {\ns.FastRecovery.MaxCwnd = s.SndCwnd + s.Outstanding\ns.FastRecovery.HighRxt = s.SndUna\ns.FastRecovery.RescueRxt = s.SndUna\n+\n+ // Record retransmitTS if the sender is not in recovery as per:\n+ // https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 2\n+ s.recordRetransmitTS()\n+\nif s.ep.SACKPermitted {\ns.state = tcpip.SACKRecovery\ns.ep.stack.Stats().TCP.SACKRecovery.Increment()\n@@ -1147,13 +1179,15 @@ func (s *sender) isDupAck(seg *segment) bool {\n// Iterate the writeList and update RACK for each segment which is newly acked\n// either cumulatively or selectively. Loop through the segments which are\n// sacked, and update the RACK related variables and check for reordering.\n+// Returns true when the DSACK block has been detected in the received ACK.\n//\n// See: https://tools.ietf.org/html/draft-ietf-tcpm-rack-08#section-7.2\n// steps 2 and 3.\n-func (s *sender) walkSACK(rcvdSeg *segment) {\n+func (s *sender) walkSACK(rcvdSeg *segment) bool {\ns.rc.setDSACKSeen(false)\n// Look for DSACK block.\n+ hasDSACK := false\nidx := 0\nn := len(rcvdSeg.parsedOptions.SACKBlocks)\nif checkDSACK(rcvdSeg) {\n@@ -1167,10 +1201,11 @@ func (s *sender) walkSACK(rcvdSeg *segment) {\ns.rc.setDSACKSeen(true)\nidx = 1\nn--\n+ hasDSACK = true\n}\nif n == 0 {\n- return\n+ return hasDSACK\n}\n// Sort the SACK blocks. The first block is the most recent unacked\n@@ -1193,6 +1228,7 @@ func (s *sender) walkSACK(rcvdSeg *segment) {\nseg = seg.Next()\n}\n}\n+ return hasDSACK\n}\n// checkDSACK checks if a DSACK is reported.\n@@ -1239,6 +1275,85 @@ func checkDSACK(rcvdSeg *segment) bool {\nreturn false\n}\n+func (s *sender) recordRetransmitTS() {\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2\n+ //\n+ // The Eifel detection algorithm is used, only upon initiation of loss\n+ // recovery, i.e., when either the timeout-based retransmit or the fast\n+ // retransmit is sent. The Eifel detection algorithm MUST NOT be\n+ // reinitiated after loss recovery has already started. In particular,\n+ // it must not be reinitiated upon subsequent timeouts for the same\n+ // segment, and not upon retransmitting segments other than the oldest\n+ // outstanding segment, e.g., during selective loss recovery.\n+ if s.inRecovery() {\n+ return\n+ }\n+\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 2\n+ //\n+ // Set a \"RetransmitTS\" variable to the value of the Timestamp Value\n+ // field of the Timestamps option included in the retransmit sent when\n+ // loss recovery is initiated. A TCP sender must ensure that\n+ // RetransmitTS does not get overwritten as loss recovery progresses,\n+ // e.g., in case of a second timeout and subsequent second retransmit of\n+ // the same octet.\n+ s.retransmitTS = s.ep.tsValNow()\n+}\n+\n+func (s *sender) detectSpuriousRecovery(hasDSACK bool, tsEchoReply uint32) {\n+ // Return if the sender has already detected spurious recovery.\n+ if s.spuriousRecovery {\n+ return\n+ }\n+\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 4\n+ //\n+ // If the value of the Timestamp Echo Reply field of the acceptable ACK's\n+ // Timestamps option is smaller than the value of RetransmitTS, then\n+ // proceed to next step, else return.\n+ if tsEchoReply >= s.retransmitTS {\n+ return\n+ }\n+\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 5\n+ //\n+ // If the acceptable ACK carries a DSACK option [RFC2883], then return.\n+ if hasDSACK {\n+ return\n+ }\n+\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 5\n+ //\n+ // If during the lifetime of the TCP connection the TCP sender has\n+ // previously received an ACK with a DSACK option, or the acceptable ACK\n+ // does not acknowledge all outstanding data, then proceed to next step,\n+ // else return.\n+ numDSACK := s.ep.stack.Stats().TCP.SegmentsAckedWithDSACK.Value()\n+ if numDSACK == 0 && s.SndUna == s.SndNxt {\n+ return\n+ }\n+\n+ // See: https://datatracker.ietf.org/doc/html/rfc3522#section-3.2 Step 6\n+ //\n+ // If the loss recovery has been initiated with a timeout-based\n+ // retransmit, then set\n+ // SpuriousRecovery <- SPUR_TO (equal 1),\n+ // else set\n+ // SpuriousRecovery <- dupacks+1\n+ // Set the spurious recovery variable to true as we do not differentiate\n+ // between fast, SACK or RTO recovery.\n+ s.spuriousRecovery = true\n+ s.ep.stack.Stats().TCP.SpuriousRecovery.Increment()\n+}\n+\n+// Check if the sender is in RTORecovery, FastRecovery or SACKRecovery state.\n+func (s *sender) inRecovery() bool {\n+ if s.state == tcpip.RTORecovery || s.state == tcpip.FastRecovery || s.state == tcpip.SACKRecovery {\n+ return true\n+ }\n+ return false\n+}\n+\n// handleRcvdSegment is called when a segment is received; it is responsible for\n// updating the send-related state.\nfunc (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n@@ -1254,6 +1369,7 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n}\n// Insert SACKBlock information into our scoreboard.\n+ hasDSACK := false\nif s.ep.SACKPermitted {\nfor _, sb := range rcvdSeg.parsedOptions.SACKBlocks {\n// Only insert the SACK block if the following holds\n@@ -1288,7 +1404,7 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// RACK.fack, then the corresponding packet has been\n// reordered and RACK.reord is set to TRUE.\nif s.ep.tcpRecovery&tcpip.TCPRACKLossDetection != 0 {\n- s.walkSACK(rcvdSeg)\n+ hasDSACK = s.walkSACK(rcvdSeg)\n}\ns.SetPipe()\n}\n@@ -1418,6 +1534,11 @@ func (s *sender) handleRcvdSegment(rcvdSeg *segment) {\n// Clear SACK information for all acked data.\ns.ep.scoreboard.Delete(s.SndUna)\n+ // Detect if the sender entered recovery spuriously.\n+ if s.inRecovery() {\n+ s.detectSpuriousRecovery(hasDSACK, rcvdSeg.parsedOptions.TSEcr)\n+ }\n+\n// If we are not in fast recovery then update the congestion\n// window based on the number of acknowledged packets.\nif !s.FastRecovery.Active {\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": "@@ -23,6 +23,7 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -702,3 +703,257 @@ func TestRecoveryEntry(t *testing.T) {\nt.Error(err)\n}\n}\n+\n+func verifySpuriousRecoveryMetric(t *testing.T, c *context.Context, numSpuriousRecovery uint64) {\n+ t.Helper()\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.SpuriousRecovery, \"stats.TCP.SpuriousRecovery\", numSpuriousRecovery},\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+\n+func checkReceivedPacket(t *testing.T, c *context.Context, tcpHdr header.TCP, bytesRead uint32, b, data []byte) {\n+ payloadLen := uint32(len(tcpHdr.Payload()))\n+ checker.IPv4(t, b,\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPSeqNum(uint32(c.IRS)+1+bytesRead),\n+ checker.TCPAckNum(context.TestInitialSequenceNumber+1),\n+ checker.TCPFlagsMatch(header.TCPFlagAck, ^header.TCPFlagPsh),\n+ ),\n+ )\n+ pdata := data[bytesRead : bytesRead+payloadLen]\n+ if p := tcpHdr.Payload(); !bytes.Equal(pdata, p) {\n+ t.Fatalf(\"got data = %v, want = %v\", p, pdata)\n+ }\n+}\n+\n+func buildTSOptionFromHeader(tcpHdr header.TCP) []byte {\n+ parsedOpts := tcpHdr.ParsedOptions()\n+ tsOpt := [12]byte{header.TCPOptionNOP, header.TCPOptionNOP}\n+ header.EncodeTSOption(parsedOpts.TSEcr+1, parsedOpts.TSVal, tsOpt[2:])\n+ return tsOpt[:]\n+}\n+\n+func TestDetectSpuriousRecoveryWithRTO(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ probeDone := make(chan struct{})\n+ c.Stack().AddTCPProbe(func(s stack.TCPEndpointState) {\n+ if s.Sender.RetransmitTS == 0 {\n+ t.Fatalf(\"RetransmitTS did not get updated, got: 0 want > 0\")\n+ }\n+ if !s.Sender.SpuriousRecovery {\n+ t.Fatalf(\"Spurious recovery was not detected\")\n+ }\n+ close(probeDone)\n+ })\n+\n+ setStackSACKPermitted(t, c, true)\n+ createConnectedWithSACKAndTS(c)\n+ numPackets := 5\n+ data := make([]byte, numPackets*maxPayload)\n+ for i := range data {\n+ data[i] = byte(i)\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+ var options []byte\n+ var bytesRead uint32\n+ for i := 0; i < numPackets; i++ {\n+ b := c.GetPacket()\n+ tcpHdr := header.TCP(header.IPv4(b).Payload())\n+ checkReceivedPacket(t, c, tcpHdr, bytesRead, b, data)\n+\n+ // Get options only for the first packet. This will be sent with\n+ // the ACK to indicate the acknowledgement is for the original\n+ // packet.\n+ if i == 0 && c.TimeStampEnabled {\n+ options = buildTSOptionFromHeader(tcpHdr)\n+ }\n+ bytesRead += uint32(len(tcpHdr.Payload()))\n+ }\n+\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ // Expect #5 segment with TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 4*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Expect #1 segment because of RTO.\n+ c.ReceiveAndCheckPacketWithOptions(data, 0, maxPayload, tsOptionSize)\n+\n+ info := tcpip.TCPInfoOption{}\n+ if err := c.EP.GetSockOpt(&info); err != nil {\n+ t.Fatalf(\"c.EP.GetSockOpt(&%T) = %s\", info, err)\n+ }\n+\n+ if info.CcState != tcpip.RTORecovery {\n+ t.Fatalf(\"Loss recovery did not happen, got: %v want: %v\", info.CcState, tcpip.RTORecovery)\n+ }\n+\n+ // Acknowledge the data.\n+ rcvWnd := seqnum.Size(30000)\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 + seqnum.Size(maxPayload)),\n+ RcvWnd: rcvWnd,\n+ TCPOpts: options,\n+ })\n+\n+ // Wait for the probe function to finish processing the\n+ // ACK before the test completes.\n+ <-probeDone\n+\n+ verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */)\n+}\n+\n+func TestSACKDetectSpuriousRecoveryWithDupACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+\n+ numAck := 0\n+ probeDone := make(chan struct{})\n+ c.Stack().AddTCPProbe(func(s stack.TCPEndpointState) {\n+ if numAck < 3 {\n+ numAck++\n+ return\n+ }\n+\n+ if s.Sender.RetransmitTS == 0 {\n+ t.Fatalf(\"RetransmitTS did not get updated, got: 0 want > 0\")\n+ }\n+ if !s.Sender.SpuriousRecovery {\n+ t.Fatalf(\"Spurious recovery was not detected\")\n+ }\n+ close(probeDone)\n+ })\n+\n+ setStackSACKPermitted(t, c, true)\n+ createConnectedWithSACKAndTS(c)\n+ numPackets := 5\n+ data := make([]byte, numPackets*maxPayload)\n+ for i := range data {\n+ data[i] = byte(i)\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+ var options []byte\n+ var bytesRead uint32\n+ for i := 0; i < numPackets; i++ {\n+ b := c.GetPacket()\n+ tcpHdr := header.TCP(header.IPv4(b).Payload())\n+ checkReceivedPacket(t, c, tcpHdr, bytesRead, b, data)\n+\n+ // Get options only for the first packet. This will be sent with\n+ // the ACK to indicate the acknowledgement is for the original\n+ // packet.\n+ if i == 0 && c.TimeStampEnabled {\n+ options = buildTSOptionFromHeader(tcpHdr)\n+ }\n+ bytesRead += uint32(len(tcpHdr.Payload()))\n+ }\n+\n+ // Receive the retransmitted packet after TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 4*maxPayload, maxPayload, tsOptionSize)\n+\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ // Send ACK for #3 and #4 segments to avoid entering TLP.\n+ start := c.IRS.Add(3*maxPayload + 1)\n+ end := start.Add(2 * maxPayload)\n+ c.SendAckWithSACK(seq, 0, []header.SACKBlock{{start, end}})\n+\n+ c.SendAck(seq, 0 /* bytesReceived */)\n+ c.SendAck(seq, 0 /* bytesReceived */)\n+\n+ // Receive the retransmitted packet after three duplicate ACKs.\n+ c.ReceiveAndCheckPacketWithOptions(data, 0, maxPayload, tsOptionSize)\n+\n+ info := tcpip.TCPInfoOption{}\n+ if err := c.EP.GetSockOpt(&info); err != nil {\n+ t.Fatalf(\"c.EP.GetSockOpt(&%T) = %s\", info, err)\n+ }\n+\n+ if info.CcState != tcpip.SACKRecovery {\n+ t.Fatalf(\"Loss recovery did not happen, got: %v want: %v\", info.CcState, tcpip.SACKRecovery)\n+ }\n+\n+ // Acknowledge the data.\n+ rcvWnd := seqnum.Size(30000)\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 + seqnum.Size(maxPayload)),\n+ RcvWnd: rcvWnd,\n+ TCPOpts: options,\n+ })\n+\n+ // Wait for the probe function to finish processing the\n+ // ACK before the test completes.\n+ <-probeDone\n+\n+ verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */)\n+}\n+\n+func TestNoSpuriousRecoveryWithDSACK(t *testing.T) {\n+ c := context.New(t, uint32(mtu))\n+ defer c.Cleanup()\n+ setStackSACKPermitted(t, c, true)\n+ createConnectedWithSACKAndTS(c)\n+ numPackets := 5\n+ data := sendAndReceiveWithSACK(t, c, numPackets, true /* enableRACK */)\n+\n+ // Receive the retransmitted packet after TLP.\n+ c.ReceiveAndCheckPacketWithOptions(data, 4*maxPayload, maxPayload, tsOptionSize)\n+\n+ // Send ACK for #3 and #4 segments to avoid entering TLP.\n+ start := c.IRS.Add(3*maxPayload + 1)\n+ end := start.Add(2 * maxPayload)\n+ seq := seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ c.SendAckWithSACK(seq, 0, []header.SACKBlock{{start, end}})\n+\n+ c.SendAck(seq, 0 /* bytesReceived */)\n+ c.SendAck(seq, 0 /* bytesReceived */)\n+\n+ // Receive the retransmitted packet after three duplicate ACKs.\n+ c.ReceiveAndCheckPacketWithOptions(data, 0, maxPayload, tsOptionSize)\n+\n+ // Acknowledge the data with DSACK for #1 segment.\n+ start = c.IRS.Add(maxPayload + 1)\n+ end = start.Add(2 * maxPayload)\n+ seq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\n+ c.SendAckWithSACK(seq, 6*maxPayload, []header.SACKBlock{{start, end}})\n+\n+ verifySpuriousRecoveryMetric(t, c, 0 /* numSpuriousRecovery */)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a new metric to detect the number of spurious loss recoveries.
- Implements RFC 3522 (Eifel detection algorithm) to detect if the connection
entered loss recovery unnecessarily.
- Added a new metric to count the total number of spurious loss recoveries.
- Added tests to verify the new metric.
PiperOrigin-RevId: 401637359 |
259,907 | 08.10.2021 15:38:41 | 25,200 | 34e68b6b4ff04de5c7b5e2dc46e5bd44c6845e63 | Remove redundant slice copy in lisafs gofer client.
listXattr() was doing redundant work. Remove it. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -2049,16 +2049,7 @@ func (d *dentry) listXattr(ctx context.Context, size uint64) ([]string, error) {\n}\nif d.fs.opts.lisaEnabled {\n- xattrs, err := d.controlFDLisa.ListXattr(ctx, size)\n- if err != nil {\n- return nil, err\n- }\n-\n- res := make([]string, 0, len(xattrs))\n- for _, xattr := range xattrs {\n- res = append(res, xattr)\n- }\n- return res, nil\n+ return d.controlFDLisa.ListXattr(ctx, size)\n}\nxattrMap, err := d.file.listXattr(ctx, size)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove redundant slice copy in lisafs gofer client.
listXattr() was doing redundant work. Remove it.
PiperOrigin-RevId: 401871315 |
260,004 | 11.10.2021 11:44:42 | 25,200 | 4ea18a8a7b72f49734a2f89be1ff7a4be87017c7 | Support IP_PKTINFO and IPV6_RECVPKTINFO on raw sockets
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -49,6 +49,7 @@ type rawPacket struct {\nreceivedAt time.Time `state:\".(int64)\"`\n// senderAddr is the network address of the sender.\nsenderAddr tcpip.FullAddress\n+ packetInfo tcpip.IPPacketInfo\n}\n// endpoint is the raw socket implementation of tcpip.Endpoint. It is legal to\n@@ -208,6 +209,23 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\nif opts.NeedRemoteAddr {\nres.RemoteAddr = pkt.senderAddr\n}\n+ switch netProto := e.net.NetProto(); netProto {\n+ case header.IPv4ProtocolNumber:\n+ if e.ops.GetReceivePacketInfo() {\n+ res.ControlMessages.HasIPPacketInfo = true\n+ res.ControlMessages.PacketInfo = pkt.packetInfo\n+ }\n+ case header.IPv6ProtocolNumber:\n+ if e.ops.GetIPv6ReceivePacketInfo() {\n+ res.ControlMessages.HasIPv6PacketInfo = true\n+ res.ControlMessages.IPv6PacketInfo = tcpip.IPv6PacketInfo{\n+ NIC: pkt.packetInfo.NIC,\n+ Addr: pkt.packetInfo.DestinationAddr,\n+ }\n+ }\n+ default:\n+ panic(fmt.Sprintf(\"unrecognized network protocol = %d\", netProto))\n+ }\nn, err := pkt.data.ReadTo(dst, opts.Peek)\nif n == 0 && err != nil {\n@@ -435,7 +453,9 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn false\n}\n- srcAddr := pkt.Network().SourceAddress()\n+ net := pkt.Network()\n+ dstAddr := net.DestinationAddress()\n+ srcAddr := net.SourceAddress()\ninfo := e.net.Info()\nswitch state := e.net.State(); state {\n@@ -457,7 +477,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n}\n// If bound to an address, only accept data for that address.\n- if info.BindAddr != \"\" && info.BindAddr != pkt.Network().DestinationAddress() {\n+ if info.BindAddr != \"\" && info.BindAddr != dstAddr {\nreturn false\n}\ndefault:\n@@ -472,6 +492,14 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nNIC: pkt.NICID,\nAddr: srcAddr,\n},\n+ packetInfo: tcpip.IPPacketInfo{\n+ // TODO(gvisor.dev/issue/3556): dstAddr may be a multicast or broadcast\n+ // address. LocalAddr should hold a unicast address that can be\n+ // used to respond to the incoming packet.\n+ LocalAddr: dstAddr,\n+ DestinationAddr: dstAddr,\n+ NIC: pkt.NICID,\n+ },\n}\n// Raw IPv4 endpoints return the IP header, but IPv6 endpoints do not.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1980,6 +1980,7 @@ cc_binary(\ndefines = select_system(),\nlinkstatic = 1,\ndeps = [\n+ \":ip_socket_test_util\",\n\":unix_domain_socket_test_util\",\n\"//test/util:capability_util\",\n\"//test/util:file_descriptor\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket.cc",
"new_path": "test/syscalls/linux/raw_socket.cc",
"diff": "#include <algorithm>\n#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/file_descriptor.h\"\n@@ -39,6 +40,9 @@ namespace testing {\nnamespace {\n+using ::testing::IsNull;\n+using ::testing::NotNull;\n+\n// Fixture for tests parameterized by protocol.\nclass RawSocketTest : public ::testing::TestWithParam<std::tuple<int, int>> {\nprotected:\n@@ -1057,6 +1061,131 @@ TEST(RawSocketTest, BindReceive) {\nASSERT_NO_FATAL_FAILURE(TestRawSocketMaybeBindReceive(true /* do_bind */));\n}\n+TEST(RawSocketTest, ReceiveIPPacketInfo) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n+\n+ FileDescriptor raw =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_RAW, IPPROTO_UDP));\n+\n+ const sockaddr_in addr_ = {\n+ .sin_family = AF_INET,\n+ .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)},\n+ };\n+ ASSERT_THAT(\n+ bind(raw.get(), reinterpret_cast<const sockaddr*>(&addr_), sizeof(addr_)),\n+ SyscallSucceeds());\n+\n+ // Register to receive IP packet info.\n+ constexpr int one = 1;\n+ ASSERT_THAT(setsockopt(raw.get(), IPPROTO_IP, IP_PKTINFO, &one, sizeof(one)),\n+ SyscallSucceeds());\n+\n+ constexpr char send_buf[] = \"malformed UDP\";\n+ ASSERT_THAT(sendto(raw.get(), send_buf, sizeof(send_buf), 0 /* flags */,\n+ reinterpret_cast<const sockaddr*>(&addr_), sizeof(addr_)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ struct {\n+ iphdr ip;\n+ char data[sizeof(send_buf)];\n+\n+ // Extra space in the receive buffer should be unused.\n+ char unused_space;\n+ } ABSL_ATTRIBUTE_PACKED recv_buf;\n+ iovec recv_iov = {\n+ .iov_base = &recv_buf,\n+ .iov_len = sizeof(recv_buf),\n+ };\n+ in_pktinfo received_pktinfo;\n+ char recv_cmsg_buf[CMSG_SPACE(sizeof(received_pktinfo))];\n+ msghdr recv_msg = {\n+ .msg_iov = &recv_iov,\n+ .msg_iovlen = 1,\n+ .msg_control = recv_cmsg_buf,\n+ .msg_controllen = CMSG_LEN(sizeof(received_pktinfo)),\n+ };\n+ ASSERT_THAT(RetryEINTR(recvmsg)(raw.get(), &recv_msg, 0),\n+ SyscallSucceedsWithValue(sizeof(iphdr) + sizeof(send_buf)));\n+ EXPECT_EQ(memcmp(send_buf, &recv_buf.data, sizeof(send_buf)), 0);\n+ EXPECT_EQ(recv_buf.ip.version, static_cast<unsigned int>(IPVERSION));\n+ // IHL holds the number of header bytes in 4 byte units.\n+ EXPECT_EQ(recv_buf.ip.ihl, sizeof(iphdr) / 4);\n+ EXPECT_EQ(ntohs(recv_buf.ip.tot_len), sizeof(iphdr) + sizeof(send_buf));\n+ EXPECT_EQ(recv_buf.ip.protocol, IPPROTO_UDP);\n+ EXPECT_EQ(ntohl(recv_buf.ip.saddr), INADDR_LOOPBACK);\n+ EXPECT_EQ(ntohl(recv_buf.ip.daddr), INADDR_LOOPBACK);\n+\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&recv_msg);\n+ ASSERT_THAT(cmsg, NotNull());\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(received_pktinfo)));\n+ EXPECT_EQ(cmsg->cmsg_level, IPPROTO_IP);\n+ EXPECT_EQ(cmsg->cmsg_type, IP_PKTINFO);\n+ memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(received_pktinfo));\n+ EXPECT_EQ(received_pktinfo.ipi_ifindex,\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));\n+ EXPECT_EQ(ntohl(received_pktinfo.ipi_spec_dst.s_addr), INADDR_LOOPBACK);\n+ EXPECT_EQ(ntohl(received_pktinfo.ipi_addr.s_addr), INADDR_LOOPBACK);\n+\n+ EXPECT_THAT(CMSG_NXTHDR(&recv_msg, cmsg), IsNull());\n+}\n+\n+TEST(RawSocketTest, ReceiveIPv6PacketInfo) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n+\n+ FileDescriptor raw =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET6, SOCK_RAW, IPPROTO_UDP));\n+\n+ const sockaddr_in6 addr_ = {\n+ .sin6_family = AF_INET6,\n+ .sin6_addr = in6addr_loopback,\n+ };\n+ ASSERT_THAT(\n+ bind(raw.get(), reinterpret_cast<const sockaddr*>(&addr_), sizeof(addr_)),\n+ SyscallSucceeds());\n+\n+ // Register to receive IPv6 packet info.\n+ constexpr int one = 1;\n+ ASSERT_THAT(\n+ setsockopt(raw.get(), IPPROTO_IPV6, IPV6_RECVPKTINFO, &one, sizeof(one)),\n+ SyscallSucceeds());\n+\n+ constexpr char send_buf[] = \"malformed UDP\";\n+ ASSERT_THAT(sendto(raw.get(), send_buf, sizeof(send_buf), 0 /* flags */,\n+ reinterpret_cast<const sockaddr*>(&addr_), sizeof(addr_)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ char recv_buf[sizeof(send_buf) + 1];\n+ iovec recv_iov = {\n+ .iov_base = recv_buf,\n+ .iov_len = sizeof(recv_buf),\n+ };\n+ in6_pktinfo received_pktinfo;\n+ char recv_cmsg_buf[CMSG_SPACE(sizeof(received_pktinfo))];\n+ msghdr recv_msg = {\n+ .msg_iov = &recv_iov,\n+ .msg_iovlen = 1,\n+ .msg_control = recv_cmsg_buf,\n+ .msg_controllen = CMSG_LEN(sizeof(received_pktinfo)),\n+ };\n+ ASSERT_THAT(RetryEINTR(recvmsg)(raw.get(), &recv_msg, 0),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+ EXPECT_EQ(memcmp(send_buf, recv_buf, sizeof(send_buf)), 0);\n+\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&recv_msg);\n+ ASSERT_THAT(cmsg, NotNull());\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(received_pktinfo)));\n+ EXPECT_EQ(cmsg->cmsg_level, IPPROTO_IPV6);\n+ EXPECT_EQ(cmsg->cmsg_type, IPV6_PKTINFO);\n+ memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(received_pktinfo));\n+ EXPECT_EQ(received_pktinfo.ipi6_ifindex,\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));\n+ ASSERT_EQ(memcmp(&received_pktinfo.ipi6_addr, &in6addr_loopback,\n+ sizeof(in6addr_loopback)),\n+ 0);\n+\n+ EXPECT_THAT(CMSG_NXTHDR(&recv_msg, cmsg), IsNull());\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support IP_PKTINFO and IPV6_RECVPKTINFO on raw sockets
Updates #1584, #3556.
PiperOrigin-RevId: 402354066 |
260,004 | 11.10.2021 12:33:44 | 25,200 | 125fae59beb2a054061fab4cc300994b753e127a | Add unit test for Redirect target
We already have integration tests `make iptables-tests` that tests
the REDIRECT target, but unit tests are a lot faster and easier
to run than the integration test. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1162,19 +1162,19 @@ func TestInputHookWithLocalForwarding(t *testing.T) {\n}\n}\n-func TestSNAT(t *testing.T) {\n- const listenPort = 8080\n+func TestNAT(t *testing.T) {\n+ const listenPort uint16 = 8080\ntype endpointAndAddresses struct {\nserverEP tcpip.Endpoint\n- serverAddr tcpip.Address\n+ serverAddr tcpip.FullAddress\nserverReadableCH chan struct{}\n+ serverConnectAddr tcpip.Address\nclientEP tcpip.Endpoint\nclientAddr tcpip.Address\nclientReadableCH chan struct{}\n-\n- nattedClientAddr tcpip.Address\n+ clientConnectAddr tcpip.FullAddress\n}\nnewEP := func(t *testing.T, s *stack.Stack, transProto tcpip.TransportProtocolNumber, netProto tcpip.NetworkProtocolNumber) (tcpip.Endpoint, chan struct{}) {\n@@ -1195,52 +1195,239 @@ func TestSNAT(t *testing.T) {\nreturn ep, ch\n}\n+ setupNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, hook stack.Hook, filter stack.IPHeaderFilter, target stack.Target) {\n+ t.Helper()\n+\n+ ipv6 := netProto == ipv6.ProtocolNumber\n+ ipt := s.IPTables()\n+ table := ipt.GetTable(stack.NATID, ipv6)\n+ ruleIdx := table.BuiltinChains[hook]\n+ table.Rules[ruleIdx].Filter = filter\n+ table.Rules[ruleIdx].Target = target\n+ // Make sure the packet is not dropped by the next rule.\n+ table.Rules[ruleIdx+1].Target = &stack.AcceptTarget{}\n+ if err := ipt.ReplaceTable(stack.NATID, table, ipv6); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n+ }\n+ }\n+\n+ setupDNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\n+ t.Helper()\n+\n+ setupNAT(\n+ t,\n+ s,\n+ netProto,\n+ stack.Prerouting,\n+ stack.IPHeaderFilter{\n+ Protocol: transProto,\n+ CheckProtocol: true,\n+ InputInterface: utils.RouterNIC2Name,\n+ },\n+ target)\n+ }\n+\n+ setupSNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\n+ t.Helper()\n+\n+ setupNAT(\n+ t,\n+ s,\n+ netProto,\n+ stack.Postrouting,\n+ stack.IPHeaderFilter{\n+ Protocol: transProto,\n+ CheckProtocol: true,\n+ OutputInterface: utils.RouterNIC1Name,\n+ },\n+ target)\n+ }\n+\n+ type natType struct {\n+ name string\n+ setupNAT func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber, tcpip.TransportProtocolNumber, tcpip.Address)\n+ }\n+\n+ snatTypes := []natType{\n+ {\n+ name: \"SNAT\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupSNAT(t, s, netProto, transProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: natToAddr})\n+ },\n+ },\n+ {\n+ name: \"Masquerade\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupSNAT(t, s, netProto, transProto, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n+ },\n+ },\n+ }\n+ dnatTypes := []natType{\n+ {\n+ name: \"Redirect\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupDNAT(t, s, netProto, transProto, &stack.RedirectTarget{NetworkProtocol: netProto, Port: listenPort})\n+ },\n+ },\n+ }\n+\ntests := []struct {\nname string\nnetProto tcpip.NetworkProtocolNumber\n+ // Setups up the stacks in such a way that:\n+ //\n+ // - Host2 is the client for all tests.\n+ // - Host1 is the server when performing SNAT\n+ // + NAT will transform client-originating packets' source addresses to\n+ // the router's NIC1's address before reaching Host1.\n+ // - Router is the server when performing DNAT (client will still attempt to\n+ // send packets to Host1).\n+ // + NAT will transform client-originating packets' destination addresses\n+ // to the router's NIC2's address.\nepAndAddrs func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses\n+ natTypes []natType\n}{\n{\n- name: \"IPv4 host1 server with host2 client\",\n+ name: \"IPv4 SNAT\",\nnetProto: ipv4.ProtocolNumber,\nepAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\nt.Helper()\n- ep1, ep1WECH := newEP(t, host1Stack, proto, ipv4.ProtocolNumber)\n+ listenerStack := host1Stack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address\n+ clientConnectPort := serverAddr.Port\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv4.ProtocolNumber)\nep2, ep2WECH := newEP(t, host2Stack, proto, ipv4.ProtocolNumber)\nreturn endpointAndAddresses{\nserverEP: ep1,\n- serverAddr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ serverAddr: serverAddr,\nserverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\nclientEP: ep2,\nclientAddr: utils.Host2IPv4Addr.AddressWithPrefix.Address,\nclientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n+ }\n+ },\n+ natTypes: snatTypes,\n+ },\n+ {\n+ name: \"IPv4 DNAT\",\n+ netProto: ipv4.ProtocolNumber,\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n- nattedClientAddr: utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address,\n+ // If we are performing DNAT, then the packet will be redirected\n+ // to the router.\n+ listenerStack := routerStack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.Host2IPv4Addr.AddressWithPrefix.Address\n+ // DNAT will update the destination port to what the server is\n+ // bound to.\n+ clientConnectPort := serverAddr.Port + 1\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv4.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv4.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: serverAddr,\n+ serverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n}\n},\n+ natTypes: dnatTypes,\n},\n{\n- name: \"IPv6 host1 server with host2 client\",\n+ name: \"IPv6 SNAT\",\nnetProto: ipv6.ProtocolNumber,\nepAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\nt.Helper()\n- ep1, ep1WECH := newEP(t, host1Stack, proto, ipv6.ProtocolNumber)\n+ listenerStack := host1Stack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address\n+ clientConnectPort := serverAddr.Port\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv6.ProtocolNumber)\nep2, ep2WECH := newEP(t, host2Stack, proto, ipv6.ProtocolNumber)\nreturn endpointAndAddresses{\nserverEP: ep1,\n- serverAddr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ serverAddr: serverAddr,\nserverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\nclientEP: ep2,\nclientAddr: utils.Host2IPv6Addr.AddressWithPrefix.Address,\nclientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n+ }\n+ },\n+ natTypes: snatTypes,\n+ },\n+ {\n+ name: \"IPv6 DNAT\",\n+ netProto: ipv6.ProtocolNumber,\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n- nattedClientAddr: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n+ // If we are performing DNAT, then the packet will be redirected\n+ // to the router.\n+ listenerStack := routerStack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.Host2IPv6Addr.AddressWithPrefix.Address\n+ // DNAT will update the destination port to what the server is\n+ // bound to.\n+ clientConnectPort := serverAddr.Port + 1\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv6.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv6.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: serverAddr,\n+ serverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n}\n},\n+ natTypes: dnatTypes,\n},\n}\n@@ -1305,49 +1492,11 @@ func TestSNAT(t *testing.T) {\n},\n}\n- setupNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, target stack.Target) {\n- t.Helper()\n-\n- ipv6 := netProto == ipv6.ProtocolNumber\n- ipt := s.IPTables()\n- filter := ipt.GetTable(stack.NATID, ipv6)\n- ruleIdx := filter.BuiltinChains[stack.Postrouting]\n- filter.Rules[ruleIdx].Filter = stack.IPHeaderFilter{OutputInterface: utils.RouterNIC1Name}\n- filter.Rules[ruleIdx].Target = target\n- // Make sure the packet is not dropped by the next rule.\n- filter.Rules[ruleIdx+1].Target = &stack.AcceptTarget{}\n- if err := ipt.ReplaceTable(stack.NATID, filter, ipv6); err != nil {\n- t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n- }\n- }\n-\n- natTypes := []struct {\n- name string\n- setupNAT func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber, tcpip.Address)\n- }{\n- {\n- name: \"SNAT\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, natToAddr tcpip.Address) {\n- t.Helper()\n-\n- setupNAT(t, s, netProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: natToAddr})\n- },\n- },\n- {\n- name: \"Masquerade\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, natToAddr tcpip.Address) {\n- t.Helper()\n-\n- setupNAT(t, s, netProto, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n- },\n- },\n- }\n-\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\nfor _, subTest := range subTests {\nt.Run(subTest.name, func(t *testing.T) {\n- for _, natType := range natTypes {\n+ for _, natType := range test.natTypes {\nt.Run(natType.name, func(t *testing.T) {\nstackOpts := stack.Options{\nNetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocol, ipv4.NewProtocol, ipv6.NewProtocol},\n@@ -1361,11 +1510,10 @@ func TestSNAT(t *testing.T) {\nepsAndAddrs := test.epAndAddrs(t, host1Stack, routerStack, host2Stack, subTest.proto)\n- natType.setupNAT(t, routerStack, test.netProto, epsAndAddrs.nattedClientAddr)\n+ natType.setupNAT(t, routerStack, test.netProto, subTest.proto, epsAndAddrs.serverConnectAddr)\n- serverAddr := tcpip.FullAddress{Addr: epsAndAddrs.serverAddr, Port: listenPort}\n- if err := epsAndAddrs.serverEP.Bind(serverAddr); err != nil {\n- t.Fatalf(\"epsAndAddrs.serverEP.Bind(%#v): %s\", serverAddr, err)\n+ if err := epsAndAddrs.serverEP.Bind(epsAndAddrs.serverAddr); err != nil {\n+ t.Fatalf(\"epsAndAddrs.serverEP.Bind(%#v): %s\", epsAndAddrs.serverAddr, err)\n}\nclientAddr := tcpip.FullAddress{Addr: epsAndAddrs.clientAddr}\nif err := epsAndAddrs.clientEP.Bind(clientAddr); err != nil {\n@@ -1376,21 +1524,21 @@ func TestSNAT(t *testing.T) {\nsubTest.setupServer(t, epsAndAddrs.serverEP)\n}\n{\n- err := epsAndAddrs.clientEP.Connect(serverAddr)\n+ err := epsAndAddrs.clientEP.Connect(epsAndAddrs.clientConnectAddr)\nif diff := cmp.Diff(subTest.expectedConnectErr, err); diff != \"\" {\n- t.Fatalf(\"unexpected error from epsAndAddrs.clientEP.Connect(%#v), (-want, +got):\\n%s\", serverAddr, diff)\n+ t.Fatalf(\"unexpected error from epsAndAddrs.clientEP.Connect(%#v), (-want, +got):\\n%s\", epsAndAddrs.clientConnectAddr, diff)\n}\n}\n- nattedClientAddr := tcpip.FullAddress{Addr: epsAndAddrs.nattedClientAddr}\n+ serverConnectAddr := tcpip.FullAddress{Addr: epsAndAddrs.serverConnectAddr}\nif addr, err := epsAndAddrs.clientEP.GetLocalAddress(); err != nil {\nt.Fatalf(\"epsAndAddrs.clientEP.GetLocalAddress(): %s\", err)\n} else {\n- nattedClientAddr.Port = addr.Port\n+ serverConnectAddr.Port = addr.Port\n}\nserverEP := epsAndAddrs.serverEP\nserverCH := epsAndAddrs.serverReadableCH\n- if ep, ch := subTest.setupServerConn(t, serverEP, serverCH, nattedClientAddr); ep != nil {\n+ if ep, ch := subTest.setupServerConn(t, serverEP, serverCH, serverConnectAddr); ep != nil {\ndefer ep.Close()\nserverEP = ep\nserverCH = ch\n@@ -1455,13 +1603,13 @@ func TestSNAT(t *testing.T) {\n{\ndata := []byte{1, 2, 3, 4}\nwrite(epsAndAddrs.clientEP, data)\n- read(serverCH, serverEP, data, nattedClientAddr)\n+ read(serverCH, serverEP, data, serverConnectAddr)\n}\n{\ndata := []byte{5, 6, 7, 8, 9, 10, 11, 12}\nwrite(serverEP, data)\n- read(epsAndAddrs.clientReadableCH, epsAndAddrs.clientEP, data, serverAddr)\n+ read(epsAndAddrs.clientReadableCH, epsAndAddrs.clientEP, data, epsAndAddrs.clientConnectAddr)\n}\n})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add unit test for Redirect target
We already have integration tests `make iptables-tests` that tests
the REDIRECT target, but unit tests are a lot faster and easier
to run than the integration test.
PiperOrigin-RevId: 402365412 |
260,004 | 11.10.2021 21:34:07 | 25,200 | ab1ef0baba1d15c4d4e7717d23cf8b32fd6b5feb | Support DNAT target | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -83,6 +83,45 @@ func (*ReturnTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (R\nreturn RuleReturn, 0\n}\n+// DNATTarget modifies the destination port/IP of packets.\n+type DNATTarget struct {\n+ // The new destination address for packets.\n+ //\n+ // Immutable.\n+ Addr tcpip.Address\n+\n+ // The new destination port for packets.\n+ //\n+ // Immutable.\n+ Port uint16\n+\n+ // NetworkProtocol is the network protocol the target is used with.\n+ //\n+ // Immutable.\n+ NetworkProtocol tcpip.NetworkProtocolNumber\n+}\n+\n+// Action implements Target.Action.\n+func (rt *DNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n+ // Sanity check.\n+ if rt.NetworkProtocol != pkt.NetworkProtocolNumber {\n+ panic(fmt.Sprintf(\n+ \"DNATTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n+ rt.NetworkProtocol, pkt.NetworkProtocolNumber))\n+ }\n+\n+ switch hook {\n+ case Prerouting, Output:\n+ case Input, Forward, Postrouting:\n+ panic(fmt.Sprintf(\"%s not supported for DNAT\", hook))\n+ default:\n+ panic(fmt.Sprintf(\"%s unrecognized\", hook))\n+ }\n+\n+ return natAction(pkt, hook, r, rt.Port, rt.Addr, true /* dnat */)\n+\n+}\n+\n// RedirectTarget redirects the packet to this machine by modifying the\n// destination port/IP. Outgoing packets are redirected to the loopback device,\n// and incoming packets are redirected to the incoming interface (rather than\n@@ -105,16 +144,6 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, address\nrt.NetworkProtocol, pkt.NetworkProtocolNumber))\n}\n- // Packet is already manipulated.\n- if pkt.NatDone {\n- return RuleAccept, 0\n- }\n-\n- // Drop the packet if network and transport header are not set.\n- if pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n- return RuleDrop, 0\n- }\n-\n// Change the address to loopback (127.0.0.1 or ::1) in Output and to\n// the primary address of the incoming interface in Prerouting.\nvar address tcpip.Address\n@@ -132,12 +161,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, address\npanic(\"redirect target is supported only on output and prerouting hooks\")\n}\n- if t := pkt.tuple; t != nil {\n- t.conn.performNAT(pkt, hook, r, rt.Port, address, true /* dnat */)\n- return RuleAccept, 0\n- }\n-\n- return RuleDrop, 0\n+ return natAction(pkt, hook, r, rt.Port, address, true /* dnat */)\n}\n// SNATTarget modifies the source port/IP in the outgoing packets.\n@@ -150,7 +174,7 @@ type SNATTarget struct {\nNetworkProtocol tcpip.NetworkProtocolNumber\n}\n-func snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address) (RuleVerdict, int) {\n+func natAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address, dnat bool) (RuleVerdict, int) {\n// Packet is already manipulated.\nif pkt.NatDone {\nreturn RuleAccept, 0\n@@ -161,6 +185,11 @@ func snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcp\nreturn RuleDrop, 0\n}\n+ t := pkt.tuple\n+ if t == nil {\n+ return RuleDrop, 0\n+ }\n+\n// TODO(https://gvisor.dev/issue/5773): If the port is in use, pick a\n// different port.\nif port == 0 {\n@@ -169,13 +198,12 @@ func snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcp\nport = header.UDP(pkt.TransportHeader().View()).SourcePort()\ncase header.TCPProtocolNumber:\nport = header.TCP(pkt.TransportHeader().View()).SourcePort()\n+ default:\n+ panic(fmt.Sprintf(\"unsupported transport protocol = %d\", pkt.TransportProtocolNumber))\n}\n}\n- if t := pkt.tuple; t != nil {\n- t.conn.performNAT(pkt, hook, r, port, address, false /* dnat */)\n- }\n-\n+ t.conn.performNAT(pkt, hook, r, port, address, dnat)\nreturn RuleAccept, 0\n}\n@@ -196,7 +224,7 @@ func (st *SNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, _ Addressab\npanic(fmt.Sprintf(\"%s unrecognized\", hook))\n}\n- return snatAction(pkt, hook, r, st.Port, st.Addr)\n+ return natAction(pkt, hook, r, st.Port, st.Addr, false /* dnat */)\n}\n// MasqueradeTarget modifies the source port/IP in the outgoing packets.\n@@ -232,7 +260,7 @@ func (mt *MasqueradeTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addre\naddress := ep.AddressWithPrefix().Address\nep.DecRef()\n- return snatAction(pkt, hook, r, 0 /* port */, address)\n+ return natAction(pkt, hook, r, 0 /* port */, address, false /* dnat */)\n}\nfunc rewritePacket(n header.Network, t header.ChecksummableTransport, updateSRCFields, fullChecksum, updatePseudoHeader bool, newPort uint16, newAddr tcpip.Address) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1245,21 +1245,21 @@ func TestNAT(t *testing.T) {\ntype natType struct {\nname string\n- setupNAT func(*testing.T, *stack.Stack, tcpip.NetworkProtocolNumber, tcpip.TransportProtocolNumber, tcpip.Address)\n+ setupNAT func(_ *testing.T, _ *stack.Stack, _ tcpip.NetworkProtocolNumber, _ tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address)\n}\nsnatTypes := []natType{\n{\nname: \"SNAT\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, _ tcpip.Address) {\nt.Helper()\n- setupSNAT(t, s, netProto, transProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: natToAddr})\n+ setupSNAT(t, s, netProto, transProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n},\n},\n{\nname: \"Masquerade\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address) {\nt.Helper()\nsetupSNAT(t, s, netProto, transProto, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n@@ -1269,12 +1269,20 @@ func TestNAT(t *testing.T) {\ndnatTypes := []natType{\n{\nname: \"Redirect\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, natToAddr tcpip.Address) {\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address) {\nt.Helper()\nsetupDNAT(t, s, netProto, transProto, &stack.RedirectTarget{NetworkProtocol: netProto, Port: listenPort})\n},\n},\n+ {\n+ name: \"DNAT\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, dnatAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupDNAT(t, s, netProto, transProto, &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: listenPort})\n+ },\n+ },\n}\ntests := []struct {\n@@ -1509,8 +1517,7 @@ func TestNAT(t *testing.T) {\nutils.SetupRoutedStacks(t, host1Stack, routerStack, host2Stack)\nepsAndAddrs := test.epAndAddrs(t, host1Stack, routerStack, host2Stack, subTest.proto)\n-\n- natType.setupNAT(t, routerStack, test.netProto, subTest.proto, epsAndAddrs.serverConnectAddr)\n+ natType.setupNAT(t, routerStack, test.netProto, subTest.proto, epsAndAddrs.serverConnectAddr, epsAndAddrs.serverAddr.Addr)\nif err := epsAndAddrs.serverEP.Bind(epsAndAddrs.serverAddr); err != nil {\nt.Fatalf(\"epsAndAddrs.serverEP.Bind(%#v): %s\", epsAndAddrs.serverAddr, err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support DNAT target
PiperOrigin-RevId: 402468096 |
259,992 | 12.10.2021 11:35:25 | 25,200 | 98a694eebc0b50e2e591da3af4a0ac280bf411d0 | Make cgroup creation/deletion more robust
Don't attempt to create directory is controller is not
present in the system
Ensure that all files being written exist in cgroupfs
Attempt to delete directories during Uninstall even if
other deletions have failed
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sync/BUILD",
"new_path": "pkg/sync/BUILD",
"diff": "@@ -26,6 +26,7 @@ go_library(\n\"rwmutex_unsafe.go\",\n\"seqcount.go\",\n\"sync.go\",\n+ \"wait.go\",\n],\nmarshal = False,\nstateify = False,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sync/wait.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 sync\n+\n+// WaitGroupErr is similar to WaitGroup but allows goroutines to report error.\n+// Only the first error is retained and reported back.\n+//\n+// Example usage:\n+// wg := WaitGroupErr{}\n+// wg.Add(1)\n+// go func() {\n+// defer wg.Done()\n+// if err := ...; err != nil {\n+// wg.ReportError(err)\n+// return\n+// }\n+// }()\n+// return wg.Error()\n+//\n+type WaitGroupErr struct {\n+ WaitGroup\n+\n+ // mu protects firstErr.\n+ mu Mutex\n+\n+ // firstErr holds the first error reported. nil is no error occurred.\n+ firstErr error\n+}\n+\n+// ReportError reports an error. Note it does not call Done().\n+func (w *WaitGroupErr) ReportError(err error) {\n+ w.mu.Lock()\n+ defer w.mu.Unlock()\n+ if w.firstErr == nil {\n+ w.firstErr = err\n+ }\n+}\n+\n+// Error waits for the counter to reach 0 and returns the first reported error\n+// if any.\n+func (w *WaitGroupErr) Error() error {\n+ w.Wait()\n+ w.mu.Lock()\n+ defer w.mu.Unlock()\n+ return w.firstErr\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/BUILD",
"new_path": "runsc/cgroup/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\ndeps = [\n\"//pkg/cleanup\",\n\"//pkg/log\",\n+ \"//pkg/sync\",\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"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -19,7 +19,6 @@ package cgroup\nimport (\n\"bufio\"\n\"context\"\n- \"errors\"\n\"fmt\"\n\"io\"\n\"io/ioutil\"\n@@ -34,6 +33,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n)\nconst (\n@@ -104,17 +104,21 @@ func setOptionalValueUint16(path, name string, val *uint16) error {\nfunc setValue(path, name, data string) error {\nfullpath := filepath.Join(path, name)\n+ log.Debugf(\"Setting %q to %q\", fullpath, data)\n+ return writeFile(fullpath, []byte(data), 0700)\n+}\n- // Retry writes on EINTR; see:\n- // https://github.com/golang/go/issues/38033\n- for {\n- err := ioutil.WriteFile(fullpath, []byte(data), 0700)\n- if err == nil {\n- return nil\n- } else if !errors.Is(err, unix.EINTR) {\n+// writeFile is similar to ioutil.WriteFile() but doesn't create the file if it\n+// doesn't exist.\n+func writeFile(path string, data []byte, perm os.FileMode) error {\n+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, perm)\n+ if err != nil {\nreturn err\n}\n- }\n+ defer f.Close()\n+\n+ _, err = f.Write(data)\n+ return err\n}\nfunc getValue(path, name string) (string, error) {\n@@ -155,15 +159,8 @@ func fillFromAncestor(path string) (string, error) {\nreturn \"\", err\n}\n- // Retry writes on EINTR; see:\n- // https://github.com/golang/go/issues/38033\n- for {\n- err := ioutil.WriteFile(path, []byte(val), 0700)\n- if err == nil {\n- break\n- } else if !errors.Is(err, unix.EINTR) {\n- return \"\", err\n- }\n+ if err := writeFile(path, []byte(val), 0700); err != nil {\n+ return \"\", nil\n}\nreturn val, nil\n}\n@@ -371,21 +368,20 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\n}\nfor _, key := range missing {\nctrlr := controllers[key]\n- path := c.MakePath(key)\n- log.Debugf(\"Creating cgroup %q: %q\", key, path)\n- if err := os.MkdirAll(path, 0755); err != nil {\n- if ctrlr.optional() && errors.Is(err, unix.EROFS) {\n+\n+ if skip, err := c.createController(key); skip && ctrlr.optional() {\nif err := ctrlr.skip(res); err != nil {\nreturn err\n}\n- log.Infof(\"Skipping cgroup %q\", key)\n+ log.Infof(\"Skipping cgroup %q, err: %v\", key, err)\ncontinue\n- }\n+ } else if err != nil {\nreturn err\n}\n// Only set controllers that were created by me.\nc.Own[key] = true\n+ path := c.MakePath(key)\nif err := ctrlr.set(res, path); err != nil {\nreturn err\n}\n@@ -394,10 +390,29 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\nreturn nil\n}\n+// createController creates the controller directory, checking that the\n+// controller is enabled in the system. It returns a boolean indicating whether\n+// the controller should be skipped (e.g. controller is disabled). In case it\n+// should be skipped, it also returns the error it got.\n+func (c *Cgroup) createController(name string) (bool, error) {\n+ ctrlrPath := filepath.Join(cgroupRoot, name)\n+ if _, err := os.Stat(ctrlrPath); err != nil {\n+ return os.IsNotExist(err), err\n+ }\n+\n+ path := c.MakePath(name)\n+ log.Debugf(\"Creating cgroup %q: %q\", name, path)\n+ if err := os.MkdirAll(path, 0755); err != nil {\n+ return false, err\n+ }\n+ return false, nil\n+}\n+\n// Uninstall removes the settings done in Install(). If cgroup path already\n// existed when Install() was called, Uninstall is a noop.\nfunc (c *Cgroup) Uninstall() error {\nlog.Debugf(\"Deleting cgroup %q\", c.Name)\n+ wait := sync.WaitGroupErr{}\nfor key := range controllers {\nif !c.Own[key] {\n// cgroup is managed by caller, don't touch it.\n@@ -406,9 +421,8 @@ func (c *Cgroup) Uninstall() error {\npath := c.MakePath(key)\nlog.Debugf(\"Removing cgroup controller for key=%q path=%q\", key, path)\n- // If we try to remove the cgroup too soon after killing the\n- // sandbox we might get EBUSY, so we retry for a few seconds\n- // until it succeeds.\n+ // If we try to remove the cgroup too soon after killing the sandbox we\n+ // might get EBUSY, so we retry for a few seconds until it succeeds.\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\ndefer cancel()\nb := backoff.WithContext(backoff.NewConstantBackOff(100*time.Millisecond), ctx)\n@@ -419,11 +433,18 @@ func (c *Cgroup) Uninstall() error {\n}\nreturn err\n}\n+ // Run deletions in parallel to remove all directories even if there are\n+ // failures/timeouts in other directories.\n+ wait.Add(1)\n+ go func() {\n+ defer wait.Done()\nif err := backoff.Retry(fn, b); err != nil {\n- return fmt.Errorf(\"removing cgroup path %q: %w\", path, err)\n+ wait.ReportError(fmt.Errorf(\"removing cgroup path %q: %w\", path, err))\n+ return\n}\n+ }()\n}\n- return nil\n+ return wait.Error()\n}\n// Join adds the current process to the all controllers. Returns function that\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup_test.go",
"new_path": "runsc/cgroup/cgroup_test.go",
"diff": "@@ -129,6 +129,18 @@ func boolPtr(v bool) *bool {\nreturn &v\n}\n+func createDir(dir string, contents map[string]string) error {\n+ for name := range contents {\n+ path := filepath.Join(dir, name)\n+ f, err := os.Create(path)\n+ if err != nil {\n+ return err\n+ }\n+ f.Close()\n+ }\n+ return nil\n+}\n+\nfunc checkDir(t *testing.T, dir string, contents map[string]string) {\nall, err := ioutil.ReadDir(dir)\nif err != nil {\n@@ -254,6 +266,9 @@ func TestBlockIO(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nBlockIO: tc.spec,\n@@ -304,6 +319,9 @@ func TestCPU(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nCPU: tc.spec,\n@@ -343,6 +361,9 @@ func TestCPUSet(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nCPU: tc.spec,\n@@ -481,6 +502,9 @@ func TestHugeTlb(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nHugepageLimits: tc.spec,\n@@ -542,6 +566,9 @@ func TestMemory(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nMemory: tc.spec,\n@@ -584,6 +611,9 @@ func TestNetworkClass(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nNetwork: tc.spec,\n@@ -631,6 +661,9 @@ func TestNetworkPriority(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nNetwork: tc.spec,\n@@ -671,6 +704,9 @@ func TestPids(t *testing.T) {\nt.Fatalf(\"error creating temporary directory: %v\", err)\n}\ndefer os.RemoveAll(dir)\n+ if err := createDir(dir, tc.wants); err != nil {\n+ t.Fatalf(\"createDir(): %v\", err)\n+ }\nspec := &specs.LinuxResources{\nPids: tc.spec,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make cgroup creation/deletion more robust
- Don't attempt to create directory is controller is not
present in the system
- Ensure that all files being written exist in cgroupfs
- Attempt to delete directories during Uninstall even if
other deletions have failed
Fixes #6446
PiperOrigin-RevId: 402614820 |
259,907 | 12.10.2021 12:44:53 | 25,200 | 035e44c7cb990d91e77b57b146b8dc78ad064b95 | Make DoubleLayerEpoll use non blocking pipes.
We don't want the read to block and want to test that epoll_wait returns only
when there is data available in rfd to be read. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/epoll.cc",
"new_path": "test/syscalls/linux/epoll.cc",
"diff": "@@ -499,7 +499,7 @@ TEST(EpollTest, PipeReaderHupAfterWriterClosed) {\nTEST(EpollTest, DoubleLayerEpoll) {\nint pipefds[2];\n- ASSERT_THAT(pipe(pipefds), SyscallSucceeds());\n+ ASSERT_THAT(pipe2(pipefds, O_NONBLOCK), SyscallSucceeds());\nFileDescriptor rfd(pipefds[0]);\nFileDescriptor wfd(pipefds[1]);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make DoubleLayerEpoll use non blocking pipes.
We don't want the read to block and want to test that epoll_wait returns only
when there is data available in rfd to be read.
PiperOrigin-RevId: 402631091 |
260,004 | 12.10.2021 15:29:57 | 25,200 | 08f1d96168ace77ff105da76f384aa0997a21e2f | Separate DNAT and SNAT manip states
This change also refactors the conntrack packet handling code
to not perform the actual rewriting of the packet while holding
the lock.
This change prepares for a followup CL that adds support for twice-NAT.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -45,17 +45,6 @@ const (\ndirReply\n)\n-// Manipulation type for the connection.\n-// TODO(gvisor.dev/issue/5696): Define this as a bit set and support SNAT and\n-// DNAT at the same time.\n-type manipType int\n-\n-const (\n- manipNone manipType = iota\n- manipSource\n- manipDestination\n-)\n-\n// tuple holds a connection's identifying and manipulating data in one\n// direction. It is immutable.\n//\n@@ -124,10 +113,14 @@ type conn struct {\n//\n// +checklocks:mu\nfinalized bool\n- // manip indicates if the packet should be manipulated.\n+ // sourceManip indicates the packet's source is manipulated.\n+ //\n+ // +checklocks:mu\n+ sourceManip bool\n+ // destinationManip indicates the packet's destination is manipulated.\n//\n// +checklocks:mu\n- manip manipType\n+ destinationManip bool\n// tcb is TCB control block. It is used to keep track of states\n// of tcp connection.\n//\n@@ -286,7 +279,6 @@ func (ct *ConnTrack) getConnOrMaybeInsertNoop(pkt *PacketBuffer) *tuple {\nct: ct,\noriginal: tuple{tupleID: tid, direction: dirOriginal},\nreply: tuple{tupleID: tid.reply(), direction: dirReply},\n- manip: manipNone,\nlastUsed: now,\n}\nconn.original.conn = conn\n@@ -393,9 +385,17 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\nreturn\n}\n- if cn.manip != manipNone {\n+ if dnat {\n+ if cn.destinationManip {\n+ return\n+ }\n+ cn.destinationManip = true\n+ } else {\n+ if cn.sourceManip {\nreturn\n}\n+ cn.sourceManip = true\n+ }\ncn.reply.mu.Lock()\ndefer cn.reply.mu.Unlock()\n@@ -403,11 +403,9 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\nif dnat {\ncn.reply.tupleID.srcAddr = address\ncn.reply.tupleID.srcPort = port\n- cn.manip = manipDestination\n} else {\ncn.reply.tupleID.dstAddr = address\ncn.reply.tupleID.dstPort = port\n- cn.manip = manipSource\n}\n}\n@@ -421,92 +419,98 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\nreturn\n}\n- netHeader := pkt.Network()\n+ fullChecksum := false\n+ updatePseudoHeader := false\n+ dnat := false\n+ switch hook {\n+ case Prerouting:\n+ // Packet came from outside the stack so it must have a checksum set\n+ // already.\n+ fullChecksum = true\n+ updatePseudoHeader = true\n+\n+ dnat = true\n+ case Input:\n+ case Forward:\n+ panic(\"should not handle packet in the forwarding hook\")\n+ case Output:\n+ dnat = true\n+ fallthrough\n+ case Postrouting:\n+ if pkt.TransportProtocolNumber == header.TCPProtocolNumber && pkt.GSOOptions.Type != GSONone && pkt.GSOOptions.NeedsCsum {\n+ updatePseudoHeader = true\n+ } else if r.RequiresTXTransportChecksum() {\n+ fullChecksum = true\n+ updatePseudoHeader = true\n+ }\n+ default:\n+ panic(fmt.Sprintf(\"unrecognized hook = %d\", hook))\n+ }\n// TODO(gvisor.dev/issue/5748): TCP checksums on inbound packets should be\n// validated if checksum offloading is off. It may require IP defrag if the\n// packets are fragmented.\n- var newAddr tcpip.Address\n- var newPort uint16\n-\n- updateSRCFields := false\n-\ndir := pkt.tuple.direction\n-\n+ tid, performManip := func() (tupleID, bool) {\ncn.mu.Lock()\ndefer cn.mu.Unlock()\n- switch hook {\n- case Prerouting, Output:\n- if cn.manip == manipDestination && dir == dirOriginal {\n- id := cn.reply.id()\n- newPort = id.srcPort\n- newAddr = id.srcAddr\n- pkt.NatDone = true\n- } else if cn.manip == manipSource && dir == dirReply {\n- id := cn.original.id()\n- newPort = id.srcPort\n- newAddr = id.srcAddr\n- pkt.NatDone = true\n+ var tuple *tuple\n+ switch dir {\n+ case dirOriginal:\n+ if dnat {\n+ if !cn.destinationManip {\n+ return tupleID{}, false\n}\n- case Input, Postrouting:\n- if cn.manip == manipSource && dir == dirOriginal {\n- id := cn.reply.id()\n- newPort = id.dstPort\n- newAddr = id.dstAddr\n- updateSRCFields = true\n- pkt.NatDone = true\n- } else if cn.manip == manipDestination && dir == dirReply {\n- id := cn.original.id()\n- newPort = id.dstPort\n- newAddr = id.dstAddr\n- updateSRCFields = true\n- pkt.NatDone = true\n+ } else if !cn.sourceManip {\n+ return tupleID{}, false\n+ }\n+\n+ tuple = &cn.reply\n+ case dirReply:\n+ if dnat {\n+ if !cn.sourceManip {\n+ return tupleID{}, false\n+ }\n+ } else if !cn.destinationManip {\n+ return tupleID{}, false\n}\n+\n+ tuple = &cn.original\ndefault:\n- panic(fmt.Sprintf(\"unrecognized hook = %s\", hook))\n+ panic(fmt.Sprintf(\"unhandled dir = %d\", dir))\n}\n- if !pkt.NatDone {\n+ // Mark the connection as having been used recently so it isn't reaped.\n+ cn.lastUsed = time.Now()\n+ // Update connection state.\n+ cn.updateLocked(pkt, dir)\n+\n+ return tuple.id(), true\n+ }()\n+ if !performManip {\nreturn\n}\n- fullChecksum := false\n- updatePseudoHeader := false\n- switch hook {\n- case Prerouting:\n- // Packet came from outside the stack so it must have a checksum set\n- // already.\n- fullChecksum = true\n- updatePseudoHeader = true\n- case Input:\n- case Output, Postrouting:\n- // Calculate the TCP checksum and set it.\n- if pkt.TransportProtocolNumber == header.TCPProtocolNumber && pkt.GSOOptions.Type != GSONone && pkt.GSOOptions.NeedsCsum {\n- updatePseudoHeader = true\n- } else if r.RequiresTXTransportChecksum() {\n- fullChecksum = true\n- updatePseudoHeader = true\n- }\n- default:\n- panic(fmt.Sprintf(\"unrecognized hook = %s\", hook))\n+ newPort := tid.dstPort\n+ newAddr := tid.dstAddr\n+ if dnat {\n+ newPort = tid.srcPort\n+ newAddr = tid.srcAddr\n}\nrewritePacket(\n- netHeader,\n+ pkt.Network(),\ntransportHeader,\n- updateSRCFields,\n+ !dnat,\nfullChecksum,\nupdatePseudoHeader,\nnewPort,\nnewAddr,\n)\n- // Mark the connection as having been used recently so it isn't reaped.\n- cn.lastUsed = time.Now()\n- // Update connection state.\n- cn.updateLocked(pkt, dir)\n+ pkt.NatDone = true\n}\n// bucket gets the conntrack bucket for a tupleID.\n@@ -651,7 +655,7 @@ func (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.Networ\nt.conn.mu.RLock()\ndefer t.conn.mu.RUnlock()\n- if t.conn.manip != manipDestination {\n+ if !t.conn.destinationManip {\n// Unmanipulated destination.\nreturn \"\", 0, &tcpip.ErrInvalidOptionValue{}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Separate DNAT and SNAT manip states
This change also refactors the conntrack packet handling code
to not perform the actual rewriting of the packet while holding
the lock.
This change prepares for a followup CL that adds support for twice-NAT.
Updates #5696.
PiperOrigin-RevId: 402671685 |
259,962 | 12.10.2021 16:24:34 | 25,200 | e54ee7a990753ba0616b9dc6010323f5a411cb5f | Create constants for Keepalive defaults.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -813,10 +813,9 @@ func newEndpoint(s *stack.Stack, protocol *protocol, netProto tcpip.NetworkProto\nwaiterQueue: waiterQueue,\nstate: uint32(StateInitial),\nkeepalive: keepalive{\n- // Linux defaults.\n- idle: 2 * time.Hour,\n- interval: 75 * time.Second,\n- count: 9,\n+ idle: DefaultKeepaliveIdle,\n+ interval: DefaultKeepaliveInterval,\n+ count: DefaultKeepaliveCount,\n},\nuniqueID: s.UniqueID(),\ntxHash: s.Rand().Uint32(),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -66,6 +66,18 @@ const (\n// DefaultSynRetries is the default value for the number of SYN retransmits\n// before a connect is aborted.\nDefaultSynRetries = 6\n+\n+ // DefaultKeepaliveIdle is the idle time for a connection before keep-alive\n+ // probes are sent.\n+ DefaultKeepaliveIdle = 2 * time.Hour\n+\n+ // DefaultKeepaliveInterval is the time between two successive keep-alive\n+ // probes.\n+ DefaultKeepaliveInterval = 75 * time.Second\n+\n+ // DefaultKeepaliveCount is the number of keep-alive probes that are sent\n+ // before declaring the connection dead.\n+ DefaultKeepaliveCount = 9\n)\nconst (\n"
}
] | Go | Apache License 2.0 | google/gvisor | Create constants for Keepalive defaults.
Fixes #6725
PiperOrigin-RevId: 402683244 |
260,004 | 12.10.2021 19:36:55 | 25,200 | 747cb92460bc30983263fcd85562a8586842d824 | Support Twice NAT
This CL allows both SNAT and DNAT targets to be performed on the same
packet.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -439,7 +439,7 @@ func (e *endpoint) WritePacket(r *stack.Route, params stack.NetworkHeaderParams,\n// We should do this for every packet, rather than only NATted packets, but\n// removing this check short circuits broadcasts before they are sent out to\n// other hosts.\n- if pkt.NatDone {\n+ if pkt.DNATDone {\nnetHeader := header.IPv4(pkt.NetworkHeader().View())\nif ep := e.protocol.findEndpointWithAddress(netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -761,7 +761,7 @@ func (e *endpoint) WritePacket(r *stack.Route, params stack.NetworkHeaderParams,\n// We should do this for every packet, rather than only NATted packets, but\n// removing this check short circuits broadcasts before they are sent out to\n// other hosts.\n- if pkt.NatDone {\n+ if pkt.DNATDone {\nnetHeader := header.IPv6(pkt.NetworkHeader().View())\nif ep := e.protocol.findEndpointWithAddress(netHeader.DestinationAddress()); ep != nil {\n// Since we rewrote the packet but it is being routed back to us, we\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -409,18 +409,19 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\n}\n}\n-func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\n- if pkt.NatDone {\n- return\n- }\n-\n+// handlePacket attempts to handle a packet and perform NAT if the connection\n+// has had NAT performed on it.\n+//\n+// Returns true if the packet can skip the NAT table.\n+func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\ntransportHeader, ok := getTransportHeader(pkt)\nif !ok {\n- return\n+ return false\n}\nfullChecksum := false\nupdatePseudoHeader := false\n+ natDone := &pkt.SNATDone\ndnat := false\nswitch hook {\ncase Prerouting:\n@@ -429,11 +430,13 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\nfullChecksum = true\nupdatePseudoHeader = true\n+ natDone = &pkt.DNATDone\ndnat = true\ncase Input:\ncase Forward:\npanic(\"should not handle packet in the forwarding hook\")\ncase Output:\n+ natDone = &pkt.DNATDone\ndnat = true\nfallthrough\ncase Postrouting:\n@@ -447,6 +450,10 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\npanic(fmt.Sprintf(\"unrecognized hook = %d\", hook))\n}\n+ if *natDone {\n+ panic(fmt.Sprintf(\"packet already had NAT(dnat=%t) performed at hook=%s; pkt=%#v\", dnat, hook, pkt))\n+ }\n+\n// TODO(gvisor.dev/issue/5748): TCP checksums on inbound packets should be\n// validated if checksum offloading is off. It may require IP defrag if the\n// packets are fragmented.\n@@ -490,7 +497,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\nreturn tuple.id(), true\n}()\nif !performManip {\n- return\n+ return false\n}\nnewPort := tid.dstPort\n@@ -510,7 +517,8 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) {\nnewAddr,\n)\n- pkt.NatDone = true\n+ *natDone = true\n+ return true\n}\n// bucket gets the conntrack bucket for a tupleID.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -277,10 +277,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\nreturn true\n}\n- if t := it.connections.getConnOrMaybeInsertNoop(pkt); t != nil {\n- pkt.tuple = t\n- t.conn.handlePacket(pkt, hook, nil /* route */)\n- }\n+ pkt.tuple = it.connections.getConnOrMaybeInsertNoop(pkt)\nreturn it.check(hook, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */)\n}\n@@ -298,10 +295,6 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\nreturn true\n}\n- if t := pkt.tuple; t != nil {\n- t.conn.handlePacket(pkt, hook, nil /* route */)\n- }\n-\nret := it.check(hook, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */)\nif t := pkt.tuple; t != nil {\nt.conn.finalize()\n@@ -336,10 +329,7 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\nreturn true\n}\n- if t := it.connections.getConnOrMaybeInsertNoop(pkt); t != nil {\n- pkt.tuple = t\n- t.conn.handlePacket(pkt, hook, r)\n- }\n+ pkt.tuple = it.connections.getConnOrMaybeInsertNoop(pkt)\nreturn it.check(hook, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName)\n}\n@@ -357,10 +347,6 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP Addr\nreturn true\n}\n- if t := pkt.tuple; t != nil {\n- t.conn.handlePacket(pkt, hook, r)\n- }\n-\nret := it.check(hook, pkt, r, addressEP, \"\" /* inNicName */, outNicName)\nif t := pkt.tuple; t != nil {\nt.conn.finalize()\n@@ -396,9 +382,7 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP Addr\n// Go through each table containing the hook.\npriorities := it.priorities[hook]\nfor _, tableID := range priorities {\n- // If handlePacket already NATed the packet, we don't need to\n- // check the NAT table.\n- if tableID == NATID && pkt.NatDone {\n+ if t := pkt.tuple; t != nil && tableID == NATID && t.conn.handlePacket(pkt, hook, r) {\ncontinue\n}\nvar table Table\n@@ -476,7 +460,7 @@ func (it *IPTables) startReaper(interval time.Duration) {\nfunc (it *IPTables) CheckOutputPackets(pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nreturn checkPackets(pkts, func(pkt *PacketBuffer) bool {\nreturn it.CheckOutput(pkt, r, outNicName)\n- })\n+ }, true /* dnat */)\n}\n// CheckPostroutingPackets performs the postrouting hook on the packets.\n@@ -487,26 +471,29 @@ func (it *IPTables) CheckOutputPackets(pkts PacketBufferList, r *Route, outNicNa\nfunc (it *IPTables) CheckPostroutingPackets(pkts PacketBufferList, r *Route, addressEP AddressableEndpoint, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nreturn checkPackets(pkts, func(pkt *PacketBuffer) bool {\nreturn it.CheckPostrouting(pkt, r, addressEP, outNicName)\n- })\n+ }, false /* dnat */)\n}\n-func checkPackets(pkts PacketBufferList, f func(*PacketBuffer) bool) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n+func checkPackets(pkts PacketBufferList, f func(*PacketBuffer) bool, dnat bool) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n- if !pkt.NatDone {\n+ natDone := &pkt.SNATDone\n+ if dnat {\n+ natDone = &pkt.DNATDone\n+ }\n+\nif ok := f(pkt); !ok {\nif drop == nil {\ndrop = make(map[*PacketBuffer]struct{})\n}\ndrop[pkt] = struct{}{}\n}\n- if pkt.NatDone {\n+ if *natDone {\nif natPkts == nil {\nnatPkts = make(map[*PacketBuffer]struct{})\n}\nnatPkts[pkt] = struct{}{}\n}\n}\n- }\nreturn drop, natPkts\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -175,11 +175,6 @@ type SNATTarget struct {\n}\nfunc natAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address, dnat bool) (RuleVerdict, int) {\n- // Packet is already manipulated.\n- if pkt.NatDone {\n- return RuleAccept, 0\n- }\n-\n// Drop the packet if network and transport header are not set.\nif pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\nreturn RuleDrop, 0\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -126,9 +126,13 @@ type PacketBuffer struct {\nEgressRoute RouteInfo\nGSOOptions GSO\n- // NatDone indicates if the packet has been manipulated as per NAT\n- // iptables rule.\n- NatDone bool\n+ // SNATDone indicates if the packet's source has been manipulated as per\n+ // iptables NAT table.\n+ SNATDone bool\n+\n+ // DNATDone indicates if the packet's destination has been manipulated as per\n+ // iptables NAT table.\n+ DNATDone bool\n// PktType indicates the SockAddrLink.PacketType of the packet as defined in\n// https://www.man7.org/linux/man-pages/man7/packet.7.html.\n@@ -298,7 +302,8 @@ func (pk *PacketBuffer) Clone() *PacketBuffer {\nOwner: pk.Owner,\nGSOOptions: pk.GSOOptions,\nNetworkProtocolNumber: pk.NetworkProtocolNumber,\n- NatDone: pk.NatDone,\n+ DNATDone: pk.DNATDone,\n+ SNATDone: pk.SNATDone,\nTransportProtocolNumber: pk.TransportProtocolNumber,\nPktType: pk.PktType,\nNICID: pk.NICID,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1285,19 +1285,109 @@ func TestNAT(t *testing.T) {\n},\n}\n+ setupTwiceNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, dnatAddr tcpip.Address, snatTarget stack.Target) {\n+ t.Helper()\n+\n+ ipv6 := netProto == ipv6.ProtocolNumber\n+ ipt := s.IPTables()\n+\n+ table := stack.Table{\n+ Rules: []stack.Rule{\n+ // Prerouting\n+ {\n+ Filter: stack.IPHeaderFilter{\n+ Protocol: transProto,\n+ CheckProtocol: true,\n+ InputInterface: utils.RouterNIC2Name,\n+ },\n+ Target: &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: listenPort},\n+ },\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Input\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Forward\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Output\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Postrouting\n+ {\n+ Filter: stack.IPHeaderFilter{\n+ Protocol: transProto,\n+ CheckProtocol: true,\n+ OutputInterface: utils.RouterNIC1Name,\n+ },\n+ Target: snatTarget,\n+ },\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+ },\n+ BuiltinChains: [stack.NumHooks]int{\n+ stack.Prerouting: 0,\n+ stack.Input: 2,\n+ stack.Forward: 3,\n+ stack.Output: 4,\n+ stack.Postrouting: 5,\n+ },\n+ }\n+\n+ if err := ipt.ReplaceTable(stack.NATID, table, ipv6); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n+ }\n+ }\n+ twiceNATTypes := []natType{\n+ {\n+ name: \"DNAT-Masquerade\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n+ },\n+ },\n+ {\n+ name: \"DNAT-SNAT\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address) {\n+ t.Helper()\n+\n+ setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n+ },\n+ },\n+ }\n+\ntests := []struct {\nname string\nnetProto tcpip.NetworkProtocolNumber\n// Setups up the stacks in such a way that:\n//\n// - Host2 is the client for all tests.\n- // - Host1 is the server when performing SNAT\n+ // - When performing SNAT only:\n+ // + Host1 is the server.\n// + NAT will transform client-originating packets' source addresses to\n// the router's NIC1's address before reaching Host1.\n- // - Router is the server when performing DNAT (client will still attempt to\n- // send packets to Host1).\n+ // - When performing DNAT only:\n+ // + Router is the server.\n+ // + Client will send packets directed to Host1.\n// + NAT will transform client-originating packets' destination addresses\n// to the router's NIC2's address.\n+ // - When performing Twice-NAT:\n+ // + Host1 is the server.\n+ // + Client will send packets directed to router's NIC2.\n+ // + NAT will transform client originating packets' destination addresses\n+ // to Host1's address.\n+ // + NAT will transform client-originating packets' source addresses to\n+ // the router's NIC1's address before reaching Host1.\nepAndAddrs func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses\nnatTypes []natType\n}{\n@@ -1369,6 +1459,38 @@ func TestNAT(t *testing.T) {\n},\nnatTypes: dnatTypes,\n},\n+ {\n+ name: \"IPv4 Twice-NAT\",\n+ netProto: ipv4.ProtocolNumber,\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n+\n+ listenerStack := host1Stack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address\n+ clientConnectPort := serverAddr.Port\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv4.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv4.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: serverAddr,\n+ serverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n+ }\n+ },\n+ natTypes: twiceNATTypes,\n+ },\n{\nname: \"IPv6 SNAT\",\nnetProto: ipv6.ProtocolNumber,\n@@ -1437,6 +1559,38 @@ func TestNAT(t *testing.T) {\n},\nnatTypes: dnatTypes,\n},\n+ {\n+ name: \"IPv6 Twice-NAT\",\n+ netProto: ipv6.ProtocolNumber,\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n+\n+ listenerStack := host1Stack\n+ serverAddr := tcpip.FullAddress{\n+ Addr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ Port: listenPort,\n+ }\n+ serverConnectAddr := utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address\n+ clientConnectPort := serverAddr.Port\n+ ep1, ep1WECH := newEP(t, listenerStack, proto, ipv6.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv6.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: serverAddr,\n+ serverReadableCH: ep1WECH,\n+ serverConnectAddr: serverConnectAddr,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+ clientConnectAddr: tcpip.FullAddress{\n+ Addr: utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ Port: clientConnectPort,\n+ },\n+ }\n+ },\n+ natTypes: twiceNATTypes,\n+ },\n}\nsubTests := []struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support Twice NAT
This CL allows both SNAT and DNAT targets to be performed on the same
packet.
Fixes #5696.
PiperOrigin-RevId: 402714738 |
260,004 | 13.10.2021 09:48:35 | 25,200 | b74bbe11e6da5f3ec00bafe4a93ab383bea78af1 | Represent direction with boolean
...since direction can only hold one of two possible values. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -37,14 +37,6 @@ import (\n// Our hash table has 16K buckets.\nconst numBuckets = 1 << 14\n-// Direction of the tuple.\n-type direction int\n-\n-const (\n- dirOriginal direction = iota\n- dirReply\n-)\n-\n// tuple holds a connection's identifying and manipulating data in one\n// direction. It is immutable.\n//\n@@ -56,8 +48,9 @@ type tuple struct {\n// conn is the connection tracking entry this tuple belongs to.\nconn *conn\n- // direction is the direction of the tuple.\n- direction direction\n+ // reply is true iff the tuple's direction is opposite that of the first\n+ // packet seen on the connection.\n+ reply bool\nmu sync.RWMutex `state:\"nosave\"`\n// +checklocks:mu\n@@ -155,7 +148,7 @@ func (cn *conn) timedOut(now time.Time) bool {\n//\n// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n// +checklocks:cn.mu\n-func (cn *conn) updateLocked(pkt *PacketBuffer, dir direction) {\n+func (cn *conn) updateLocked(pkt *PacketBuffer, reply bool) {\nif pkt.TransportProtocolNumber != header.TCPProtocolNumber {\nreturn\n}\n@@ -170,13 +163,10 @@ func (cn *conn) updateLocked(pkt *PacketBuffer, dir direction) {\nreturn\n}\n- switch dir {\n- case dirOriginal:\n- cn.tcb.UpdateStateOutbound(tcpHeader)\n- case dirReply:\n+ if reply {\ncn.tcb.UpdateStateInbound(tcpHeader)\n- default:\n- panic(fmt.Sprintf(\"unhandled dir = %d\", dir))\n+ } else {\n+ cn.tcb.UpdateStateOutbound(tcpHeader)\n}\n}\n@@ -277,8 +267,8 @@ func (ct *ConnTrack) getConnOrMaybeInsertNoop(pkt *PacketBuffer) *tuple {\n// for this new connection.\nconn := &conn{\nct: ct,\n- original: tuple{tupleID: tid, direction: dirOriginal},\n- reply: tuple{tupleID: tid.reply(), direction: dirReply},\n+ original: tuple{tupleID: tid},\n+ reply: tuple{tupleID: tid.reply(), reply: true},\nlastUsed: now,\n}\nconn.original.conn = conn\n@@ -458,41 +448,38 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n// validated if checksum offloading is off. It may require IP defrag if the\n// packets are fragmented.\n- dir := pkt.tuple.direction\n+ reply := pkt.tuple.reply\ntid, performManip := func() (tupleID, bool) {\ncn.mu.Lock()\ndefer cn.mu.Unlock()\nvar tuple *tuple\n- switch dir {\n- case dirOriginal:\n+ if reply {\nif dnat {\n- if !cn.destinationManip {\n+ if !cn.sourceManip {\nreturn tupleID{}, false\n}\n- } else if !cn.sourceManip {\n+ } else if !cn.destinationManip {\nreturn tupleID{}, false\n}\n- tuple = &cn.reply\n- case dirReply:\n+ tuple = &cn.original\n+ } else {\nif dnat {\n- if !cn.sourceManip {\n+ if !cn.destinationManip {\nreturn tupleID{}, false\n}\n- } else if !cn.destinationManip {\n+ } else if !cn.sourceManip {\nreturn tupleID{}, false\n}\n- tuple = &cn.original\n- default:\n- panic(fmt.Sprintf(\"unhandled dir = %d\", dir))\n+ tuple = &cn.reply\n}\n// Mark the connection as having been used recently so it isn't reaped.\ncn.lastUsed = time.Now()\n// Update connection state.\n- cn.updateLocked(pkt, dir)\n+ cn.updateLocked(pkt, reply)\nreturn tuple.id(), true\n}()\n@@ -637,10 +624,10 @@ func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now t\n// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n// +checklocks:b.mu\nfunc removeConnFromBucket(b *bucket, tuple *tuple) {\n- if tuple.direction == dirOriginal {\n- b.tuples.Remove(&tuple.conn.reply)\n- } else {\n+ if tuple.reply {\nb.tuples.Remove(&tuple.conn.original)\n+ } else {\n+ b.tuples.Remove(&tuple.conn.reply)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Represent direction with boolean
...since direction can only hold one of two possible values.
PiperOrigin-RevId: 402855698 |
259,853 | 13.10.2021 13:48:43 | 25,200 | 82218937948bd59f8d20e44575405874d56f0ae7 | runsc: allow to run rootless containers on cgroupV2
Before cl/402392291 and cl/402614820, it worked without any problem.
In this case, we just ignore a cgroup configuration. We do the same thing,
when we don't have permissions to create new cgroups on cgroupV1. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -1278,7 +1278,10 @@ func (c *Container) setupCgroupForSubcontainer(conf *config.Config, spec *specs.\n// no cgroups was configured.\nfunc cgroupInstall(conf *config.Config, cg *cgroup.Cgroup, res *specs.LinuxResources) (*cgroup.Cgroup, error) {\n// TODO(gvisor.dev/issue/3481): Remove when cgroups v2 is supported.\n- if !conf.Rootless && cgroup.IsOnlyV2() {\n+ if cgroup.IsOnlyV2() {\n+ if conf.Rootless {\n+ return nil, nil\n+ }\nreturn nil, fmt.Errorf(\"cgroups V2 is not yet supported. Enable cgroups V1 and retry\")\n}\nif err := cg.Install(res); err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: allow to run rootless containers on cgroupV2
Before cl/402392291 and cl/402614820, it worked without any problem.
In this case, we just ignore a cgroup configuration. We do the same thing,
when we don't have permissions to create new cgroups on cgroupV1.
PiperOrigin-RevId: 402913129 |
259,891 | 13.10.2021 14:36:53 | 25,200 | 1796cd89d516033800f9c887250481c26bab0ae0 | add create-only raw sockets
These can be used by applications to manipulate iptables rules without enabling
arbitrary reads from and writes to the underlying packet socket. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/internal/noop/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"noop\",\n+ srcs = [\"endpoint.go\"],\n+ visibility = [\"//pkg/tcpip/transport/raw:__pkg__\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/stack\",\n+ \"//pkg/waiter\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/transport/internal/noop/endpoint.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 noop contains an endpoint that implements all tcpip.Endpoint\n+// functions as noops.\n+package noop\n+\n+import (\n+ \"fmt\"\n+ \"io\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n+)\n+\n+// endpoint can be created, but all interactions have no effect or\n+// return errors.\n+//\n+// +stateify savable\n+type endpoint struct {\n+ tcpip.DefaultSocketOptionsHandler\n+ ops tcpip.SocketOptions\n+}\n+\n+// New returns an initialized noop endpoint.\n+func New(stk *stack.Stack) tcpip.Endpoint {\n+ // ep.ops must be in a valid, initialized state for callers of\n+ // ep.SocketOptions.\n+ var ep endpoint\n+ ep.ops.InitHandler(&ep, stk, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n+ return &ep\n+}\n+\n+// Abort implements stack.TransportEndpoint.Abort.\n+func (*endpoint) Abort() {\n+ // No-op.\n+}\n+\n+// Close implements tcpip.Endpoint.Close.\n+func (*endpoint) Close() {\n+ // No-op.\n+}\n+\n+// ModerateRecvBuf implements tcpip.Endpoint.ModerateRecvBuf.\n+func (*endpoint) ModerateRecvBuf(int) {\n+ // No-op.\n+}\n+\n+func (*endpoint) SetOwner(tcpip.PacketOwner) {\n+ // No-op.\n+}\n+\n+// Read implements tcpip.Endpoint.Read.\n+func (*endpoint) Read(io.Writer, tcpip.ReadOptions) (tcpip.ReadResult, tcpip.Error) {\n+ return tcpip.ReadResult{}, &tcpip.ErrNotPermitted{}\n+}\n+\n+// Write implements tcpip.Endpoint.Write.\n+func (*endpoint) Write(tcpip.Payloader, tcpip.WriteOptions) (int64, tcpip.Error) {\n+ return 0, &tcpip.ErrNotPermitted{}\n+}\n+\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (*endpoint) Disconnect() tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n+// Connect implements tcpip.Endpoint.Connect.\n+func (*endpoint) Connect(tcpip.FullAddress) tcpip.Error {\n+ return &tcpip.ErrNotPermitted{}\n+}\n+\n+// Shutdown implements tcpip.Endpoint.Shutdown.\n+func (*endpoint) Shutdown(tcpip.ShutdownFlags) tcpip.Error {\n+ return &tcpip.ErrNotPermitted{}\n+}\n+\n+// Listen implements tcpip.Endpoint.Listen.\n+func (*endpoint) Listen(int) tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n+// Accept implements tcpip.Endpoint.Accept.\n+func (*endpoint) Accept(*tcpip.FullAddress) (tcpip.Endpoint, *waiter.Queue, tcpip.Error) {\n+ return nil, nil, &tcpip.ErrNotSupported{}\n+}\n+\n+// Bind implements tcpip.Endpoint.Bind.\n+func (*endpoint) Bind(tcpip.FullAddress) tcpip.Error {\n+ return &tcpip.ErrNotPermitted{}\n+}\n+\n+// GetLocalAddress implements tcpip.Endpoint.GetLocalAddress.\n+func (*endpoint) GetLocalAddress() (tcpip.FullAddress, tcpip.Error) {\n+ return tcpip.FullAddress{}, &tcpip.ErrNotSupported{}\n+}\n+\n+// GetRemoteAddress implements tcpip.Endpoint.GetRemoteAddress.\n+func (*endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\n+ return tcpip.FullAddress{}, &tcpip.ErrNotConnected{}\n+}\n+\n+// Readiness implements tcpip.Endpoint.Readiness.\n+func (*endpoint) Readiness(waiter.EventMask) waiter.EventMask {\n+ return 0\n+}\n+\n+// SetSockOpt implements tcpip.Endpoint.SetSockOpt.\n+func (*endpoint) SetSockOpt(tcpip.SettableSocketOption) tcpip.Error {\n+ return &tcpip.ErrUnknownProtocolOption{}\n+}\n+\n+func (*endpoint) SetSockOptInt(tcpip.SockOptInt, int) tcpip.Error {\n+ return &tcpip.ErrUnknownProtocolOption{}\n+}\n+\n+// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n+func (*endpoint) GetSockOpt(tcpip.GettableSocketOption) tcpip.Error {\n+ return &tcpip.ErrUnknownProtocolOption{}\n+}\n+\n+// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+func (*endpoint) GetSockOptInt(tcpip.SockOptInt) (int, tcpip.Error) {\n+ return 0, &tcpip.ErrUnknownProtocolOption{}\n+}\n+\n+// HandlePacket implements stack.RawTransportEndpoint.HandlePacket.\n+func (*endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n+ panic(fmt.Sprintf(\"unreachable: noop.endpoint should never be registered, but got packet: %+v\", pkt))\n+}\n+\n+// State implements socket.Socket.State.\n+func (*endpoint) State() uint32 {\n+ return 0\n+}\n+\n+// Wait implements stack.TransportEndpoint.Wait.\n+func (*endpoint) Wait() {\n+ // No-op.\n+}\n+\n+// LastError implements tcpip.Endpoint.LastError.\n+func (*endpoint) LastError() tcpip.Error {\n+ return nil\n+}\n+\n+// SocketOptions implements tcpip.Endpoint.SocketOptions.\n+func (ep *endpoint) SocketOptions() *tcpip.SocketOptions {\n+ return &ep.ops\n+}\n+\n+// Info implements tcpip.Endpoint.Info.\n+func (*endpoint) Info() tcpip.EndpointInfo {\n+ return &stack.TransportEndpointInfo{}\n+}\n+\n+// Stats returns a pointer to the endpoint stats.\n+func (*endpoint) Stats() tcpip.EndpointStats {\n+ return &tcpip.TransportEndpointStats{}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/BUILD",
"new_path": "pkg/tcpip/transport/raw/BUILD",
"diff": "@@ -35,6 +35,7 @@ go_library(\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/transport\",\n\"//pkg/tcpip/transport/internal/network\",\n+ \"//pkg/tcpip/transport/internal/noop\",\n\"//pkg/tcpip/transport/packet\",\n\"//pkg/waiter\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/protocol.go",
"new_path": "pkg/tcpip/transport/raw/protocol.go",
"diff": "@@ -17,6 +17,7 @@ package raw\nimport (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/internal/noop\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/packet\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -33,3 +34,18 @@ func (EndpointFactory) NewUnassociatedEndpoint(stack *stack.Stack, netProto tcpi\nfunc (EndpointFactory) NewPacketEndpoint(stack *stack.Stack, cooked bool, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, tcpip.Error) {\nreturn packet.NewEndpoint(stack, cooked, netProto, waiterQueue)\n}\n+\n+// CreateOnlyFactory implements stack.RawFactory. It allows creation of raw\n+// endpoints that do not support reading, writing, binding, etc.\n+type CreateOnlyFactory struct{}\n+\n+// NewUnassociatedEndpoint implements stack.RawFactory.NewUnassociatedEndpoint.\n+func (CreateOnlyFactory) NewUnassociatedEndpoint(stk *stack.Stack, _ tcpip.NetworkProtocolNumber, _ tcpip.TransportProtocolNumber, _ *waiter.Queue) (tcpip.Endpoint, tcpip.Error) {\n+ return noop.New(stk), nil\n+}\n+\n+// NewPacketEndpoint implements stack.RawFactory.NewPacketEndpoint.\n+func (CreateOnlyFactory) NewPacketEndpoint(*stack.Stack, bool, tcpip.NetworkProtocolNumber, *waiter.Queue) (tcpip.Endpoint, tcpip.Error) {\n+ // This isn't needed by anything, so it isn't implemented.\n+ return nil, &tcpip.ErrNotPermitted{}\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | add create-only raw sockets
These can be used by applications to manipulate iptables rules without enabling
arbitrary reads from and writes to the underlying packet socket.
PiperOrigin-RevId: 402924733 |
259,962 | 13.10.2021 15:17:23 | 25,200 | 4e2cc2bef3220bb77a60b4a33fb02f491d5acf98 | Minor fixes to sharedmem.
Use route/protocol from packetbuffer.
Sharedmem implementation should use the EgressRoute/NetworkProtocolNumber
embedded in the packetbuffer rather than what is passed as parameters to
Write(Raw)Packet(s). | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/BUILD",
"new_path": "pkg/tcpip/link/sharedmem/BUILD",
"diff": "@@ -19,6 +19,7 @@ go_library(\n\"//pkg/cleanup\",\n\"//pkg/eventfd\",\n\"//pkg/log\",\n+ \"//pkg/memutil\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"diff": "@@ -343,10 +343,10 @@ func (e *endpoint) writePacketLocked(r stack.RouteInfo, protocol tcpip.NetworkPr\n// WritePacket writes outbound packets to the file descriptor. If it is not\n// currently writable, the packet is dropped.\n-func (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n+func (e *endpoint) WritePacket(_ stack.RouteInfo, _ tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- if err := e.writePacketLocked(r, protocol, pkt); err != nil {\n+ if err := e.writePacketLocked(pkt.EgressRoute, pkt.NetworkProtocolNumber, pkt); err != nil {\nreturn err\n}\ne.tx.notify()\n@@ -354,13 +354,13 @@ func (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocol\n}\n// WritePackets implements stack.LinkEndpoint.WritePackets.\n-func (e *endpoint) WritePackets(r stack.RouteInfo, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\n+func (e *endpoint) WritePackets(_ stack.RouteInfo, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\nn := 0\nvar err tcpip.Error\ne.mu.Lock()\ndefer e.mu.Unlock()\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n- if err = e.writePacketLocked(r, pkt.NetworkProtocolNumber, pkt); err != nil {\n+ if err = e.writePacketLocked(pkt.EgressRoute, pkt.NetworkProtocolNumber, pkt); err != nil {\nbreak\n}\nn++\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem_server.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem_server.go",
"diff": "@@ -218,14 +218,24 @@ func (e *serverEndpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcp\neth.Encode(ethHdr)\n}\n-// WriteRawPacket implements stack.LinkEndpoint.\n-func (*serverEndpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error {\n- return &tcpip.ErrNotSupported{}\n+// WriteRawPacket implements stack.LinkEndpoint.WriteRawPacket\n+func (e *serverEndpoint) WriteRawPacket(pkt *stack.PacketBuffer) tcpip.Error {\n+ views := pkt.Views()\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+ ok := e.tx.transmit(views)\n+ if !ok {\n+ return &tcpip.ErrWouldBlock{}\n+ }\n+ e.tx.notify()\n+ return nil\n}\n// +checklocks:e.mu\nfunc (e *serverEndpoint) writePacketLocked(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n+ if e.addr != \"\" {\ne.AddHeader(r.LocalLinkAddress, r.RemoteLinkAddress, protocol, pkt)\n+ }\nviews := pkt.Views()\nok := e.tx.transmit(views)\n@@ -238,11 +248,12 @@ func (e *serverEndpoint) writePacketLocked(r stack.RouteInfo, protocol tcpip.Net\n// WritePacket writes outbound packets to the file descriptor. If it is not\n// currently writable, the packet is dropped.\n-func (e *serverEndpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n+// WritePacket implements stack.LinkEndpoint.WritePacket.\n+func (e *serverEndpoint) WritePacket(_ stack.RouteInfo, _ tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n// Transmit the packet.\ne.mu.Lock()\ndefer e.mu.Unlock()\n- if err := e.writePacketLocked(r, protocol, pkt); err != nil {\n+ if err := e.writePacketLocked(pkt.EgressRoute, pkt.NetworkProtocolNumber, pkt); err != nil {\nreturn err\n}\ne.tx.notify()\n@@ -250,13 +261,13 @@ func (e *serverEndpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkPr\n}\n// WritePackets implements stack.LinkEndpoint.WritePackets.\n-func (e *serverEndpoint) WritePackets(r stack.RouteInfo, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\n+func (e *serverEndpoint) WritePackets(_ stack.RouteInfo, pkts stack.PacketBufferList, protocol tcpip.NetworkProtocolNumber) (int, tcpip.Error) {\nn := 0\nvar err tcpip.Error\ne.mu.Lock()\ndefer e.mu.Unlock()\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\n- if err = e.writePacketLocked(r, pkt.NetworkProtocolNumber, pkt); err != nil {\n+ if err = e.writePacketLocked(pkt.EgressRoute, pkt.NetworkProtocolNumber, pkt); err != nil {\nbreak\n}\nn++\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem_test.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem_test.go",
"diff": "@@ -210,6 +210,7 @@ func TestSimpleSend(t *testing.T) {\n// Prepare route.\nvar r stack.RouteInfo\nr.RemoteLinkAddress = remoteLinkAddr\n+ r.LocalLinkAddress = localLinkAddr\nfor iters := 1000; iters > 0; iters-- {\nfunc() {\n@@ -227,8 +228,11 @@ func TestSimpleSend(t *testing.T) {\nData: data.ToVectorisedView(),\n})\ncopy(pkt.NetworkHeader().Push(hdrLen), hdrBuf)\n-\nproto := tcpip.NetworkProtocolNumber(rand.Intn(0x10000))\n+ // Every PacketBuffer must have these set:\n+ // See nic.writePacket.\n+ pkt.EgressRoute = r\n+ pkt.NetworkProtocolNumber = proto\nif err := c.ep.WritePacket(r, proto, pkt); err != nil {\nt.Fatalf(\"WritePacket failed: %v\", err)\n}\n@@ -297,8 +301,11 @@ func TestPreserveSrcAddressInSend(t *testing.T) {\n// the minimum size of the ethernet header.\nReserveHeaderBytes: header.EthernetMinimumSize,\n})\n-\nproto := tcpip.NetworkProtocolNumber(rand.Intn(0x10000))\n+ // Every PacketBuffer must have these set:\n+ // See nic.writePacket.\n+ pkt.EgressRoute = r\n+ pkt.NetworkProtocolNumber = proto\nif err := c.ep.WritePacket(r, proto, pkt); err != nil {\nt.Fatalf(\"WritePacket failed: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem_unsafe.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem_unsafe.go",
"diff": "package sharedmem\nimport (\n+ \"fmt\"\n+ \"reflect\"\n\"unsafe\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/memutil\"\n)\n// sharedDataPointer converts the shared data slice into a pointer so that it\n@@ -23,3 +28,31 @@ import (\nfunc sharedDataPointer(sharedData []byte) *uint32 {\nreturn (*uint32)(unsafe.Pointer(&sharedData[0:4][0]))\n}\n+\n+// getBuffer returns a memory region mapped to the full contents of the given\n+// file descriptor.\n+func getBuffer(fd int) ([]byte, error) {\n+ var s unix.Stat_t\n+ if err := unix.Fstat(fd, &s); err != nil {\n+ return nil, err\n+ }\n+\n+ // Check that size doesn't overflow an int.\n+ if s.Size > int64(^uint(0)>>1) {\n+ return nil, unix.EDOM\n+ }\n+\n+ addr, err := memutil.MapFile(0 /* addr */, uintptr(s.Size), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_FILE, uintptr(fd), 0 /*offset*/)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"failed to map memory for buffer fd: %d, error: %s\", fd, err)\n+ }\n+\n+ // Use unsafe to conver addr into a []byte.\n+ var b []byte\n+ hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n+ hdr.Data = addr\n+ hdr.Len = int(s.Size)\n+ hdr.Cap = int(s.Size)\n+\n+ return b, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/tx.go",
"new_path": "pkg/tcpip/link/sharedmem/tx.go",
"diff": "@@ -152,22 +152,6 @@ func (t *tx) notify() {\nt.eventFD.Notify()\n}\n-// getBuffer returns a memory region mapped to the full contents of the given\n-// file descriptor.\n-func getBuffer(fd int) ([]byte, error) {\n- var s unix.Stat_t\n- if err := unix.Fstat(fd, &s); err != nil {\n- return nil, err\n- }\n-\n- // Check that size doesn't overflow an int.\n- if s.Size > int64(^uint(0)>>1) {\n- return nil, unix.EDOM\n- }\n-\n- return unix.Mmap(fd, 0, int(s.Size), unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED|unix.MAP_FILE)\n-}\n-\n// idDescriptor is used by idManager to either point to a tx buffer (in case\n// the ID is assigned) or to the next free element (if the id is not assigned).\ntype idDescriptor struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor fixes to sharedmem.
Use route/protocol from packetbuffer.
Sharedmem implementation should use the EgressRoute/NetworkProtocolNumber
embedded in the packetbuffer rather than what is passed as parameters to
Write(Raw)Packet(s).
PiperOrigin-RevId: 402934171 |
260,001 | 14.10.2021 16:24:35 | 25,200 | 6f4fcc4bac81f0fc73712b0216e3ed50b056a925 | Add a size parameter | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/ioctl.go",
"new_path": "pkg/abi/linux/ioctl.go",
"diff": "@@ -180,8 +180,12 @@ var (\n// to get quote.\nconst SizeOfQuoteInputData = 64\n-// SignReport is a struct that gets signed quote from input data.\n+// SignReport is a struct that gets signed quote from input data. The\n+// serialized quote is copied to buf.\n+// size is an input that specifies the size of buf. When returned, it's updated\n+// to the size of quote.\ntype SignReport struct {\ndata [64]byte\n- quote []byte\n+ size uint32\n+ buf []byte\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a size parameter
PiperOrigin-RevId: 403214414 |
259,881 | 15.10.2021 13:49:48 | 25,200 | 04dc27899bbdeb9bbce2b2647856d160e8ccd78d | Fix incorrect printf verb
tcpip.Error does not implement error and thus cannot be used with %w.
This was flagged by nogo. | [
{
"change_type": "MODIFY",
"old_path": "test/benchmarks/tcp/tcp_proxy.go",
"new_path": "test/benchmarks/tcp/tcp_proxy.go",
"diff": "@@ -213,7 +213,7 @@ func newNetstackImpl(mode string) (impl, error) {\nAddressWithPrefix: parsedAddr.WithPrefix(),\n}\nif err := s.AddProtocolAddress(nicID, protocolAddr, stack.AddressProperties{}); err != nil {\n- return nil, fmt.Errorf(\"error adding IP address %+v to %q: %w\", protocolAddr, *iface, err)\n+ return nil, fmt.Errorf(\"error adding IP address %+v to %q: %s\", protocolAddr, *iface, err)\n}\nsubnet, err := tcpip.NewSubnet(parsedDest, parsedMask)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix incorrect printf verb
tcpip.Error does not implement error and thus cannot be used with %w.
This was flagged by nogo.
PiperOrigin-RevId: 403458480 |
259,978 | 15.10.2021 14:01:39 | 25,200 | e4fc15bd88f0b62fb8923f1417175f015482c0bd | Implement WriteRawPacket for pipe
Implement WriteRawPacket for pipe by calling `DeliverNetworkPacket`
on the other end with empty values for the route and protocol number,
and relies on the `NetworkDispatcher` to decapsulate the link layer
header from the raw packet itself. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/pipe/pipe.go",
"new_path": "pkg/tcpip/link/pipe/pipe.go",
"diff": "@@ -123,4 +123,6 @@ func (*Endpoint) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber\n}\n// WriteRawPacket implements stack.LinkEndpoint.\n-func (*Endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n+func (e *Endpoint) WriteRawPacket(pkt *stack.PacketBuffer) tcpip.Error {\n+ return e.WritePacket(stack.RouteInfo{}, 0, pkt)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement WriteRawPacket for pipe
Implement WriteRawPacket for pipe by calling `DeliverNetworkPacket`
on the other end with empty values for the route and protocol number,
and relies on the `NetworkDispatcher` to decapsulate the link layer
header from the raw packet itself.
PiperOrigin-RevId: 403461448 |
260,004 | 15.10.2021 15:16:14 | 25,200 | 706f6f35f468c63cfaf385fb099af09b835bcfe1 | Satisfy nogo | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet_test.go",
"diff": "@@ -630,7 +630,7 @@ func makePipe() (c1, c2 net.Conn, stop func(), err error) {\nAddressWithPrefix: ip.WithPrefix(),\n}\nif err := s.AddProtocolAddress(NICID, protocolAddr, stack.AddressProperties{}); err != nil {\n- return nil, nil, nil, fmt.Errorf(\"AddProtocolAddress(%d, %+v, {}): %w\", NICID, protocolAddr, err)\n+ return nil, nil, nil, fmt.Errorf(\"AddProtocolAddress(%d, %+v, {}): %s\", NICID, protocolAddr, err)\n}\nl, err := ListenTCP(s, addr, ipv4.ProtocolNumber)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Satisfy nogo
PiperOrigin-RevId: 403479257 |
259,992 | 18.10.2021 11:44:11 | 25,200 | eafa3f19e4d2c0a490af78dbe77289c7b5edbb76 | Mount namespace can be nil after task exits
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -950,7 +950,7 @@ func (l *Loader) executeAsync(args *control.ExecArgs) (kernel.ThreadID, error) {\nif kernel.VFS2Enabled {\n// task.MountNamespaceVFS2() does not take a ref, so we must do so ourselves.\nargs.MountNamespaceVFS2 = tg.Leader().MountNamespaceVFS2()\n- if !args.MountNamespaceVFS2.TryIncRef() {\n+ if args.MountNamespaceVFS2 == nil || !args.MountNamespaceVFS2.TryIncRef() {\nreturn 0, fmt.Errorf(\"container %q has stopped\", args.ContainerID)\n}\n} else {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -1624,6 +1624,7 @@ func TestMultiContainerGoferKilled(t *testing.T) {\ndefer cleanup()\nconf := testutil.TestConfig(t)\n+ conf.VFS2 = true\nconf.RootDir = rootDir\nsleep := []string{\"sleep\", \"100\"}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mount namespace can be nil after task exits
Updates #1035
PiperOrigin-RevId: 404017795 |
259,881 | 18.10.2021 12:14:22 | 25,200 | c7e5b4bd67e0a80c07bf051654e7d28fb592cc39 | Add hook to add addition build tags | [
{
"change_type": "MODIFY",
"old_path": "tools/nogo/build.go",
"new_path": "tools/nogo/build.go",
"diff": "@@ -31,3 +31,8 @@ func findStdPkg(GOOS, GOARCH, path string) (io.ReadCloser, error) {\n}\nreturn os.Open(fmt.Sprintf(\"external/go_sdk/pkg/%s_%s/%s.a\", GOOS, GOARCH, path))\n}\n+\n+// ReleaseTags returns nil, indicating that the defaults should be used.\n+func ReleaseTags() ([]string, error) {\n+ return nil, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/check/main.go",
"new_path": "tools/nogo/check/main.go",
"diff": "@@ -66,14 +66,22 @@ func run([]string) int {\nreturn 1\n}\n+ releaseTags, err := nogo.ReleaseTags()\n+ if err != nil {\n+ fmt.Fprintf(os.Stderr, \"error determining release tags: %v\", err)\n+ return 1\n+ }\n+\n// Run the configuration.\nif *stdlibFile != \"\" {\n// Perform stdlib analysis.\nc := loadConfig(*stdlibFile, new(nogo.StdlibConfig)).(*nogo.StdlibConfig)\n+ c.ReleaseTags = releaseTags\nfindings, factData, err = nogo.CheckStdlib(c, nogo.AllAnalyzers)\n} else if *packageFile != \"\" {\n// Perform standard analysis.\nc := loadConfig(*packageFile, new(nogo.PackageConfig)).(*nogo.PackageConfig)\n+ c.ReleaseTags = releaseTags\nfindings, factData, err = nogo.CheckPackage(c, nogo.AllAnalyzers, nil)\n} else {\nfmt.Fprintf(os.Stderr, \"please provide at least one of package or stdlib!\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/defs.bzl",
"new_path": "tools/nogo/defs.bzl",
"diff": "@@ -126,7 +126,7 @@ def _nogo_stdlib_impl(ctx):\nSrcs = [f.path for f in go_ctx.stdlib_srcs],\nGOOS = go_ctx.goos,\nGOARCH = go_ctx.goarch,\n- Tags = go_ctx.gotags,\n+ BuildTags = go_ctx.gotags,\n)\nconfig_file = ctx.actions.declare_file(ctx.label.name + \".cfg\")\nctx.actions.write(config_file, config.to_json())\n@@ -321,7 +321,7 @@ def _nogo_aspect_impl(target, ctx):\nNonGoFiles = [src.path for src in srcs if not src.path.endswith(\".go\")],\nGOOS = go_ctx.goos,\nGOARCH = go_ctx.goarch,\n- Tags = go_ctx.gotags,\n+ BuildTags = go_ctx.gotags,\nFactMap = fact_map,\nImportMap = import_map,\nStdlibFacts = stdlib_facts.path,\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/nogo/nogo.go",
"new_path": "tools/nogo/nogo.go",
"diff": "@@ -55,7 +55,8 @@ type StdlibConfig struct {\nSrcs []string\nGOOS string\nGOARCH string\n- Tags []string\n+ BuildTags []string\n+ ReleaseTags []string // Use build.Default if nil.\n}\n// PackageConfig is serialized as the configuration.\n@@ -65,7 +66,8 @@ type PackageConfig struct {\nImportPath string\nGoFiles []string\nNonGoFiles []string\n- Tags []string\n+ BuildTags []string\n+ ReleaseTags []string // Use build.Default if nil.\nGOOS string\nGOARCH string\nImportMap map[string]string\n@@ -182,7 +184,10 @@ func (c *PackageConfig) shouldInclude(path string) (bool, error) {\nctx := build.Default\nctx.GOOS = c.GOOS\nctx.GOARCH = c.GOARCH\n- ctx.BuildTags = c.Tags\n+ ctx.BuildTags = c.BuildTags\n+ if c.ReleaseTags != nil {\n+ ctx.ReleaseTags = c.ReleaseTags\n+ }\nreturn ctx.MatchFile(filepath.Dir(path), filepath.Base(path))\n}\n@@ -336,7 +341,8 @@ func CheckStdlib(config *StdlibConfig, analyzers []*analysis.Analyzer) (allFindi\nImportPath: pkg,\nGOOS: config.GOOS,\nGOARCH: config.GOARCH,\n- Tags: config.Tags,\n+ BuildTags: config.BuildTags,\n+ ReleaseTags: config.ReleaseTags,\n}\npackages[pkg] = c\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add hook to add addition build tags
PiperOrigin-RevId: 404025736 |
259,881 | 18.10.2021 13:13:04 | 25,200 | fb053829f9cad92527e7df93b17e211f5885a783 | Update testDeps definition for
The in-progress Go 1.18's testing.corpusEntry changed definition slightly in
Update our definition to the new version. | [
{
"change_type": "MODIFY",
"old_path": "test/runtimes/runner/lib/lib.go",
"new_path": "test/runtimes/runner/lib/lib.go",
"diff": "@@ -209,7 +209,7 @@ func (f testDeps) SnapshotCoverage() {}\n// Copied from testing/fuzz.go.\ntype corpusEntry = struct {\nParent string\n- Name string\n+ Path string\nData []byte\nValues []interface{}\nGeneration int\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update testDeps definition for https://golang.org/cl/354632
The in-progress Go 1.18's testing.corpusEntry changed definition slightly in
https://golang.org/cl/354632. Update our definition to the new version.
PiperOrigin-RevId: 404040853 |
259,992 | 18.10.2021 13:22:38 | 25,200 | 832c309ce95b5b68bdb4e98ac85dc64c6762646e | Change test to use VFS2
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -984,7 +984,7 @@ func (c *containerMounter) createRestoreEnvironment(conf *config.Config) (*fs.Re\n// Add root mount.\nfd := c.fds.remove()\n- opts := goferMountData(fd, conf.FileAccess, \"/\", false /* vfs2 */, false /* lisafs */)\n+ opts := goferMountData(fd, conf.FileAccess, \"/\", conf.VFS2, false /* lisafs */)\nmf := fs.MountSourceFlags{}\nif c.root.Readonly || conf.Overlay {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader_test.go",
"new_path": "runsc/boot/loader_test.go",
"diff": "@@ -552,7 +552,7 @@ func TestRestoreEnvironment(t *testing.T) {\n{\nDev: \"9pfs-/\",\nFlags: fs.MountSourceFlags{ReadOnly: true},\n- DataString: \"trans=fd,rfdno=0,wfdno=0,privateunixsocket=true\",\n+ DataString: \"trans=fd,rfdno=0,wfdno=0\",\n},\n},\n\"tmpfs\": {\n@@ -606,11 +606,11 @@ func TestRestoreEnvironment(t *testing.T) {\n{\nDev: \"9pfs-/\",\nFlags: fs.MountSourceFlags{ReadOnly: true},\n- DataString: \"trans=fd,rfdno=0,wfdno=0,privateunixsocket=true\",\n+ DataString: \"trans=fd,rfdno=0,wfdno=0\",\n},\n{\nDev: \"9pfs-/dev/fd-foo\",\n- DataString: \"trans=fd,rfdno=1,wfdno=1,privateunixsocket=true,cache=remote_revalidating\",\n+ DataString: \"trans=fd,rfdno=1,wfdno=1,cache=remote_revalidating\",\n},\n},\n\"tmpfs\": {\n@@ -664,7 +664,7 @@ func TestRestoreEnvironment(t *testing.T) {\n{\nDev: \"9pfs-/\",\nFlags: fs.MountSourceFlags{ReadOnly: true},\n- DataString: \"trans=fd,rfdno=0,wfdno=0,privateunixsocket=true\",\n+ DataString: \"trans=fd,rfdno=0,wfdno=0\",\n},\n},\n\"tmpfs\": {\n@@ -704,6 +704,7 @@ func TestRestoreEnvironment(t *testing.T) {\nfor _, tc := range testCases {\nt.Run(tc.name, func(t *testing.T) {\nconf := testConfig()\n+ conf.VFS2 = true\nvar ioFDs []*fd.FD\nfor _, ioFD := range tc.ioFDs {\nioFDs = append(ioFDs, fd.New(ioFD))\n@@ -713,7 +714,7 @@ func TestRestoreEnvironment(t *testing.T) {\nspec: tc.spec,\ngoferFDs: ioFDs,\n}\n- mntr := newContainerMounter(&info, nil, &podMountHints{}, false /* vfs2Enabled */)\n+ mntr := newContainerMounter(&info, nil, &podMountHints{}, conf.VFS2)\nactualRenv, err := mntr.createRestoreEnvironment(conf)\nif !tc.errorExpected && err != nil {\nt.Fatalf(\"could not create restore environment for test:%s\", tc.name)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change test to use VFS2
Updates #1035
PiperOrigin-RevId: 404043283 |
259,992 | 18.10.2021 15:06:45 | 25,200 | fa56fbf44e440bbbca710ef1b7cc1d54f862c20e | Report ramdiskfs usage correctly
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go",
"diff": "@@ -95,7 +95,7 @@ type regularFile struct {\nfunc (fs *filesystem) newRegularFile(kuid auth.KUID, kgid auth.KGID, mode linux.FileMode, parentDir *directory) *inode {\nfile := ®ularFile{\nmemFile: fs.mfp.MemoryFile(),\n- memoryUsageKind: usage.Tmpfs,\n+ memoryUsageKind: fs.usage,\nseals: linux.F_SEAL_SEAL,\n}\nfile.inode.init(file, fs, kuid, kgid, linux.S_IFREG|mode, parentDir)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -41,6 +41,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usage\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs/memxattr\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -74,6 +75,10 @@ type filesystem struct {\n// filesystem. Immutable.\nmopts string\n+ // usage is the memory accounting category under which pages backing\n+ // files in this filesystem are accounted.\n+ usage usage.MemoryKind\n+\n// mu serializes changes to the Dentry tree.\nmu sync.RWMutex `state:\"nosave\"`\n@@ -106,6 +111,10 @@ type FilesystemOpts struct {\n// tmpfs filesystem. This allows tmpfs to \"impersonate\" other\n// filesystems, like ramdiskfs and cgroupfs.\nFilesystemType vfs.FilesystemType\n+\n+ // Usage is the memory accounting category under which pages backing files in\n+ // the filesystem are accounted.\n+ Usage *usage.MemoryKind\n}\n// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\n@@ -184,11 +193,16 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, err\n}\nclock := time.RealtimeClockFromContext(ctx)\n+ memUsage := usage.Tmpfs\n+ if tmpfsOpts.Usage != nil {\n+ memUsage = *tmpfsOpts.Usage\n+ }\nfs := filesystem{\nmfp: mfp,\nclock: clock,\ndevMinor: devMinor,\nmopts: opts.Data,\n+ usage: memUsage,\n}\nfs.vfsfs.Init(vfsObj, newFSType, &fs)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Report ramdiskfs usage correctly
Updates #1035
PiperOrigin-RevId: 404072231 |
259,891 | 18.10.2021 15:07:06 | 25,200 | 211bbf82ad2f490ed7215568c2065d76dfa682ca | conntrack: use tcpip.Clock instead of time.Time
We should be using a monotonic clock
This will make future testing easier
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -58,8 +58,8 @@ var nameToID = map[string]stack.TableID{\n// DefaultLinuxTables returns the rules of stack.DefaultTables() wrapped for\n// compatibility with netfilter extensions.\n-func DefaultLinuxTables(seed uint32) *stack.IPTables {\n- tables := stack.DefaultTables(seed)\n+func DefaultLinuxTables(seed uint32, clock tcpip.Clock) *stack.IPTables {\n+ tables := stack.DefaultTables(seed, clock)\ntables.VisitTargets(func(oldTarget stack.Target) stack.Target {\nswitch val := oldTarget.(type) {\ncase *stack.AcceptTarget:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -48,7 +48,6 @@ go_library(\n\"hook_string.go\",\n\"icmp_rate_limit.go\",\n\"iptables.go\",\n- \"iptables_state.go\",\n\"iptables_targets.go\",\n\"iptables_types.go\",\n\"neighbor_cache.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -122,14 +122,12 @@ type conn struct {\n// lastUsed is the last time the connection saw a relevant packet, and\n// is updated by each packet on the connection.\n//\n- // TODO(gvisor.dev/issue/5939): do not use the ambient clock.\n- //\n// +checklocks:mu\n- lastUsed time.Time `state:\".(unixTime)\"`\n+ lastUsed tcpip.MonotonicTime\n}\n// timedOut returns whether the connection timed out based on its state.\n-func (cn *conn) timedOut(now time.Time) bool {\n+func (cn *conn) timedOut(now tcpip.MonotonicTime) bool {\nconst establishedTimeout = 5 * 24 * time.Hour\nconst defaultTimeout = 120 * time.Second\ncn.mu.RLock()\n@@ -190,6 +188,9 @@ type ConnTrack struct {\n// It is immutable.\nseed uint32\n+ // clock provides timing used to determine conntrack reapings.\n+ clock tcpip.Clock\n+\nmu sync.RWMutex `state:\"nosave\"`\n// mu protects the buckets slice, but not buckets' contents. Only take\n// the write lock if you are modifying the slice or saving for S/R.\n@@ -248,7 +249,7 @@ func (ct *ConnTrack) getConnOrMaybeInsertNoop(pkt *PacketBuffer) *tuple {\nbkt := &ct.buckets[bktID]\nct.mu.RUnlock()\n- now := time.Now()\n+ now := ct.clock.NowMonotonic()\nif t := bkt.connForTID(tid, now); t != nil {\nreturn t\n}\n@@ -294,17 +295,17 @@ func (ct *ConnTrack) connForTID(tid tupleID) *tuple {\nbkt := &ct.buckets[bktID]\nct.mu.RUnlock()\n- return bkt.connForTID(tid, time.Now())\n+ return bkt.connForTID(tid, ct.clock.NowMonotonic())\n}\n-func (bkt *bucket) connForTID(tid tupleID, now time.Time) *tuple {\n+func (bkt *bucket) connForTID(tid tupleID, now tcpip.MonotonicTime) *tuple {\nbkt.mu.RLock()\ndefer bkt.mu.RUnlock()\nreturn bkt.connForTIDRLocked(tid, now)\n}\n// +checklocksread:bkt.mu\n-func (bkt *bucket) connForTIDRLocked(tid tupleID, now time.Time) *tuple {\n+func (bkt *bucket) connForTIDRLocked(tid tupleID, now tcpip.MonotonicTime) *tuple {\nfor other := bkt.tuples.Front(); other != nil; other = other.Next() {\nif tid == other.id() && !other.conn.timedOut(now) {\nreturn other\n@@ -324,7 +325,7 @@ func (ct *ConnTrack) finalize(cn *conn) {\nbkt.mu.Lock()\ndefer bkt.mu.Unlock()\n- if t := bkt.connForTIDRLocked(tid, time.Now()); t != nil {\n+ if t := bkt.connForTIDRLocked(tid, ct.clock.NowMonotonic()); t != nil {\n// Another connection for the reply already exists. We can't do much about\n// this so we leave the connection cn represents in a state where it can\n// send packets but its responses will be mapped to some other connection.\n@@ -476,7 +477,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n}\n// Mark the connection as having been used recently so it isn't reaped.\n- cn.lastUsed = time.Now()\n+ cn.lastUsed = cn.ct.clock.NowMonotonic()\n// Update connection state.\ncn.updateLocked(pkt, reply)\n@@ -548,7 +549,7 @@ func (ct *ConnTrack) reapUnused(start int, prevInterval time.Duration) (int, tim\nconst minInterval = 10 * time.Millisecond\nconst maxInterval = maxFullTraversal / fractionPerReaping\n- now := time.Now()\n+ now := ct.clock.NowMonotonic()\nchecked := 0\nexpired := 0\nvar idx int\n@@ -592,7 +593,7 @@ func (ct *ConnTrack) reapUnused(start int, prevInterval time.Duration) (int, tim\n// Precondition: ct.mu is read locked and bkt.mu is write locked.\n// +checklocksread:ct.mu\n// +checklocks:bkt.mu\n-func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now time.Time) bool {\n+func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now tcpip.MonotonicTime) bool {\nif !tuple.conn.timedOut(now) {\nreturn false\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -42,7 +42,7 @@ const reaperDelay = 5 * time.Second\n// DefaultTables returns a default set of tables. Each chain is set to accept\n// all packets.\n-func DefaultTables(seed uint32) *IPTables {\n+func DefaultTables(seed uint32, clock tcpip.Clock) *IPTables {\nreturn &IPTables{\nv4Tables: [NumTables]Table{\nNATID: {\n@@ -183,6 +183,7 @@ func DefaultTables(seed uint32) *IPTables {\n},\nconnections: ConnTrack{\nseed: seed,\n+ clock: clock,\n},\nreaperDone: make(chan struct{}, 1),\n}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/tcpip/stack/iptables_state.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 stack\n-\n-import (\n- \"time\"\n-)\n-\n-// +stateify savable\n-type unixTime struct {\n- second int64\n- nano int64\n-}\n-\n-// saveLastUsed is invoked by stateify.\n-func (cn *conn) saveLastUsed() unixTime {\n- cn.mu.Lock()\n- defer cn.mu.Unlock()\n- return unixTime{cn.lastUsed.Unix(), cn.lastUsed.UnixNano()}\n-}\n-\n-// loadLastUsed is invoked by stateify.\n-func (cn *conn) loadLastUsed(unix unixTime) {\n- cn.mu.Lock()\n- defer cn.mu.Unlock()\n- cn.lastUsed = time.Unix(unix.second, unix.nano)\n-}\n-\n-// beforeSave is invoked by stateify.\n-func (ct *ConnTrack) beforeSave() {\n- ct.mu.Lock()\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -238,7 +238,7 @@ type Options struct {\n// DefaultIPTables is an optional iptables rules constructor that is called\n// if IPTables is nil. If both fields are nil, iptables will allow all\n// traffic.\n- DefaultIPTables func(uint32) *IPTables\n+ DefaultIPTables func(seed uint32, clock tcpip.Clock) *IPTables\n// SecureRNG is a cryptographically secure random number generator.\nSecureRNG io.Reader\n@@ -358,7 +358,7 @@ func New(opts Options) *Stack {\nif opts.DefaultIPTables == nil {\nopts.DefaultIPTables = DefaultTables\n}\n- opts.IPTables = opts.DefaultIPTables(seed)\n+ opts.IPTables = opts.DefaultIPTables(seed, clock)\n}\nopts.NUDConfigs.resetInvalidFields()\n"
}
] | Go | Apache License 2.0 | google/gvisor | conntrack: use tcpip.Clock instead of time.Time
- We should be using a monotonic clock
- This will make future testing easier
Updates #6748.
PiperOrigin-RevId: 404072318 |
259,891 | 18.10.2021 20:41:37 | 25,200 | 03bc93d2b82045fc44102d0f40a208f97db16479 | conntrack: update state of un-NATted connections
This prevents reaping connections unnecessarily early. This change both moves
the state update to the beginning of handlePacket and fixes a bug where
un-finalized connections could become un-reapable.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -132,6 +132,7 @@ go_test(\nname = \"stack_test\",\nsize = \"small\",\nsrcs = [\n+ \"conntrack_test.go\",\n\"forwarding_test.go\",\n\"neighbor_cache_test.go\",\n\"neighbor_entry_test.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -37,6 +37,11 @@ import (\n// Our hash table has 16K buckets.\nconst numBuckets = 1 << 14\n+const (\n+ establishedTimeout time.Duration = 5 * 24 * time.Hour\n+ unestablishedTimeout time.Duration = 120 * time.Second\n+)\n+\n// tuple holds a connection's identifying and manipulating data in one\n// direction. It is immutable.\n//\n@@ -128,8 +133,6 @@ type conn struct {\n// timedOut returns whether the connection timed out based on its state.\nfunc (cn *conn) timedOut(now tcpip.MonotonicTime) bool {\n- const establishedTimeout = 5 * 24 * time.Hour\n- const defaultTimeout = 120 * time.Second\ncn.mu.RLock()\ndefer cn.mu.RUnlock()\nif cn.tcb.State() == tcpconntrack.ResultAlive {\n@@ -139,7 +142,7 @@ func (cn *conn) timedOut(now tcpip.MonotonicTime) bool {\n}\n// Use the same default as Linux, which lets connections in most states\n// other than established remain for <= 120 seconds.\n- return now.Sub(cn.lastUsed) > defaultTimeout\n+ return now.Sub(cn.lastUsed) > unestablishedTimeout\n}\n// update the connection tracking state.\n@@ -403,7 +406,7 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\n// has had NAT performed on it.\n//\n// Returns true if the packet can skip the NAT table.\n-func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n+func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\ntransportHeader, ok := getTransportHeader(pkt)\nif !ok {\nreturn false\n@@ -432,7 +435,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\ncase Postrouting:\nif pkt.TransportProtocolNumber == header.TCPProtocolNumber && pkt.GSOOptions.Type != GSONone && pkt.GSOOptions.NeedsCsum {\nupdatePseudoHeader = true\n- } else if r.RequiresTXTransportChecksum() {\n+ } else if rt.RequiresTXTransportChecksum() {\nfullChecksum = true\nupdatePseudoHeader = true\n}\n@@ -453,6 +456,11 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\ncn.mu.Lock()\ndefer cn.mu.Unlock()\n+ // Mark the connection as having been used recently so it isn't reaped.\n+ cn.lastUsed = cn.ct.clock.NowMonotonic()\n+ // Update connection state.\n+ cn.updateLocked(pkt, reply)\n+\nvar tuple *tuple\nif reply {\nif dnat {\n@@ -476,11 +484,6 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\ntuple = &cn.reply\n}\n- // Mark the connection as having been used recently so it isn't reaped.\n- cn.lastUsed = cn.ct.clock.NowMonotonic()\n- // Update connection state.\n- cn.updateLocked(pkt, reply)\n-\nreturn tuple.id(), true\n}()\nif !performManip {\n@@ -598,13 +601,18 @@ func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now t\nreturn false\n}\n- // To maintain lock order, we can only reap these tuples if the reply\n- // appears later in the table.\n+ // To maintain lock order, we can only reap both tuples if the reply appears\n+ // later in the table.\nreplyBktID := ct.bucket(tuple.id().reply())\n- if bktID > replyBktID {\n+ tuple.conn.mu.RLock()\n+ replyTupleInserted := tuple.conn.finalized\n+ tuple.conn.mu.RUnlock()\n+ if bktID > replyBktID && replyTupleInserted {\nreturn true\n}\n+ // Reap the reply.\n+ if replyTupleInserted {\n// Don't re-lock if both tuples are in the same bucket.\nif bktID != replyBktID {\nreplyBkt := &ct.buckets[replyBktID]\n@@ -614,8 +622,8 @@ func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now t\n} else {\nremoveConnFromBucket(bkt, tuple)\n}\n+ }\n- // We have the buckets locked and can remove both tuples.\nbkt.tuples.Remove(tuple)\nreturn true\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/stack/conntrack_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 stack\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n+)\n+\n+func TestReap(t *testing.T) {\n+ // Initialize conntrack.\n+ clock := faketime.NewManualClock()\n+ ct := ConnTrack{\n+ clock: clock,\n+ }\n+ ct.init()\n+ ct.checkNumTuples(t, 0)\n+\n+ // Simulate sending a SYN. This will get the connection into conntrack, but\n+ // the connection won't be considered established. Thus the timeout for\n+ // reaping is unestablishedTimeout.\n+ pkt1 := genTCPPacket()\n+ pkt1.tuple = ct.getConnOrMaybeInsertNoop(pkt1)\n+ // We set rt.routeInfo.Loop to avoid a panic when handlePacket calls\n+ // rt.RequiresTXTransportChecksum.\n+ var rt Route\n+ rt.routeInfo.Loop = PacketLoop\n+ if pkt1.tuple.conn.handlePacket(pkt1, Output, &rt) {\n+ t.Fatal(\"handlePacket() shouldn't perform any NAT\")\n+ }\n+ ct.checkNumTuples(t, 1)\n+\n+ // Travel a little into the future and send the same SYN. This should update\n+ // lastUsed, but per #6748 didn't.\n+ clock.Advance(unestablishedTimeout / 2)\n+ pkt2 := genTCPPacket()\n+ pkt2.tuple = ct.getConnOrMaybeInsertNoop(pkt2)\n+ if pkt2.tuple.conn.handlePacket(pkt2, Output, &rt) {\n+ t.Fatal(\"handlePacket() shouldn't perform any NAT\")\n+ }\n+ ct.checkNumTuples(t, 1)\n+\n+ // Travel farther into the future - enough that failing to update lastUsed\n+ // would cause a reaping - and reap the whole table. Make sure the connection\n+ // hasn't been reaped.\n+ clock.Advance(unestablishedTimeout * 3 / 4)\n+ ct.reapEverything()\n+ ct.checkNumTuples(t, 1)\n+\n+ // Travel past unestablishedTimeout to confirm the tuple is gone.\n+ clock.Advance(unestablishedTimeout / 2)\n+ ct.reapEverything()\n+ ct.checkNumTuples(t, 0)\n+}\n+\n+// genTCPPacket returns an initialized IPv4 TCP packet.\n+func genTCPPacket() *PacketBuffer {\n+ const packetLen = header.IPv4MinimumSize + header.TCPMinimumSize\n+ pkt := NewPacketBuffer(PacketBufferOptions{\n+ ReserveHeaderBytes: packetLen,\n+ })\n+ pkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\n+ pkt.TransportProtocolNumber = header.TCPProtocolNumber\n+ tcpHdr := header.TCP(pkt.TransportHeader().Push(header.TCPMinimumSize))\n+ tcpHdr.Encode(&header.TCPFields{\n+ SrcPort: 5555,\n+ DstPort: 6666,\n+ SeqNum: 7777,\n+ AckNum: 8888,\n+ DataOffset: header.TCPMinimumSize,\n+ Flags: header.TCPFlagSyn,\n+ WindowSize: 50000,\n+ Checksum: 0, // Conntrack doesn't verify the checksum.\n+ })\n+ ipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))\n+ ipHdr.Encode(&header.IPv4Fields{\n+ TotalLength: packetLen,\n+ Protocol: uint8(header.TCPProtocolNumber),\n+ SrcAddr: testutil.MustParse4(\"1.0.0.1\"),\n+ DstAddr: testutil.MustParse4(\"1.0.0.2\"),\n+ Checksum: 0, // Conntrack doesn't verify the checksum.\n+ })\n+\n+ return pkt\n+}\n+\n+// checkNumTuples checks that there are exactly want tuples tracked by\n+// conntrack.\n+func (ct *ConnTrack) checkNumTuples(t *testing.T, want int) {\n+ t.Helper()\n+ ct.mu.RLock()\n+ defer ct.mu.RUnlock()\n+\n+ var total int\n+ for idx := range ct.buckets {\n+ ct.buckets[idx].mu.RLock()\n+ total += ct.buckets[idx].tuples.Len()\n+ ct.buckets[idx].mu.RUnlock()\n+ }\n+\n+ if total != want {\n+ t.Fatalf(\"checkNumTuples: got %d, wanted %d\", total, want)\n+ }\n+}\n+\n+func (ct *ConnTrack) reapEverything() {\n+ var bucket int\n+ for {\n+ newBucket, _ := ct.reapUnused(bucket, 0 /* ignored */)\n+ // We started reaping at bucket 0. If the next bucket isn't after our\n+ // current bucket, we've gone through them all.\n+ if newBucket <= bucket {\n+ break\n+ }\n+ bucket = newBucket\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | conntrack: update state of un-NATted connections
This prevents reaping connections unnecessarily early. This change both moves
the state update to the beginning of handlePacket and fixes a bug where
un-finalized connections could become un-reapable.
Fixes #6748
PiperOrigin-RevId: 404141012 |
259,881 | 19.10.2021 08:15:48 | 25,200 | 83840125e0bd050129fc3c8983a5bcef7afefe4e | Drop accept from sentryctl socket filters
Now that we use x/sys/unix beyond we always use
accept4 in place of accept. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -651,11 +651,6 @@ func controlServerFilters(fd int) seccomp.SyscallRules {\nseccomp.EqualTo(fd),\n},\n},\n- unix.SYS_ACCEPT: []seccomp.Rule{\n- {\n- seccomp.EqualTo(fd),\n- },\n- },\nunix.SYS_LISTEN: []seccomp.Rule{\n{\nseccomp.EqualTo(fd),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop accept from sentryctl socket filters
Now that we use x/sys/unix beyond https://golang.org/cl/313690 we always use
accept4 in place of accept.
PiperOrigin-RevId: 404265340 |
259,985 | 19.10.2021 15:36:02 | 25,200 | 80d655d842755c93d7d6bf0288732cd5d3552c50 | Stub cpuset cgroup control files. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"new_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\nload(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nlicenses([\"notice\"])\n@@ -18,6 +18,7 @@ go_library(\nname = \"cgroupfs\",\nsrcs = [\n\"base.go\",\n+ \"bitmap.go\",\n\"cgroupfs.go\",\n\"cpu.go\",\n\"cpuacct.go\",\n@@ -29,10 +30,12 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/bitmap\",\n\"//pkg/context\",\n\"//pkg/coverage\",\n\"//pkg/errors/linuxerr\",\n\"//pkg/fspath\",\n+ \"//pkg/hostarch\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n@@ -47,3 +50,11 @@ go_library(\n\"//pkg/usermem\",\n],\n)\n+\n+go_test(\n+ name = \"cgroupfs_test\",\n+ size = \"small\",\n+ srcs = [\"bitmap_test.go\"],\n+ library = \":cgroupfs\",\n+ deps = [\"//pkg/bitmap\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/cgroupfs/bitmap.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 cgroupfs\n+\n+import (\n+ \"fmt\"\n+ \"strconv\"\n+ \"strings\"\n+\n+ \"gvisor.dev/gvisor/pkg/bitmap\"\n+)\n+\n+// formatBitmap produces a string representation of b, which lists the indicies\n+// of set bits in the bitmap. Indicies are separated by commas and ranges of\n+// set bits are abbreviated. Example outputs: \"0,2,4\", \"0,3-7,10\", \"0-10\".\n+//\n+// Inverse of parseBitmap.\n+func formatBitmap(b *bitmap.Bitmap) string {\n+ ones := b.ToSlice()\n+ if len(ones) == 0 {\n+ return \"\"\n+ }\n+\n+ elems := make([]string, 0, len(ones))\n+ runStart := ones[0]\n+ lastVal := ones[0]\n+ inRun := false\n+\n+ for _, v := range ones[1:] {\n+ last := lastVal\n+ lastVal = v\n+\n+ if last+1 == v {\n+ // In a contiguous block of ones.\n+ if !inRun {\n+ runStart = last\n+ inRun = true\n+ }\n+\n+ continue\n+ }\n+\n+ // Non-contiguous bit.\n+ if inRun {\n+ // Render a run\n+ elems = append(elems, fmt.Sprintf(\"%d-%d\", runStart, last))\n+ inRun = false\n+ continue\n+ }\n+\n+ // Lone non-contiguous bit.\n+ elems = append(elems, fmt.Sprintf(\"%d\", last))\n+\n+ }\n+\n+ // Process potential final run\n+ if inRun {\n+ elems = append(elems, fmt.Sprintf(\"%d-%d\", runStart, lastVal))\n+ } else {\n+ elems = append(elems, fmt.Sprintf(\"%d\", lastVal))\n+ }\n+\n+ return strings.Join(elems, \",\")\n+}\n+\n+func parseToken(token string) (start, end uint32, err error) {\n+ ts := strings.SplitN(token, \"-\", 2)\n+ switch len(ts) {\n+ case 0:\n+ return 0, 0, fmt.Errorf(\"invalid token %q\", token)\n+ case 1:\n+ val, err := strconv.ParseUint(ts[0], 10, 32)\n+ if err != nil {\n+ return 0, 0, err\n+ }\n+ return uint32(val), uint32(val), nil\n+ case 2:\n+ val1, err := strconv.ParseUint(ts[0], 10, 32)\n+ if err != nil {\n+ return 0, 0, err\n+ }\n+ val2, err := strconv.ParseUint(ts[1], 10, 32)\n+ if err != nil {\n+ return 0, 0, err\n+ }\n+ if val1 >= val2 {\n+ return 0, 0, fmt.Errorf(\"start (%v) must be less than end (%v)\", val1, val2)\n+ }\n+ return uint32(val1), uint32(val2), nil\n+ default:\n+ panic(fmt.Sprintf(\"Unreachable: got %d substrs\", len(ts)))\n+ }\n+}\n+\n+// parseBitmap parses input as a bitmap. input should be a comma separated list\n+// of indices, and ranges of set bits may be abbreviated. Examples: \"0,2,4\",\n+// \"0,3-7,10\", \"0-10\". Input after the first newline or null byte is discarded.\n+//\n+// sizeHint sets the initial size of the bitmap, which may prevent reallocation\n+// when growing the bitmap during parsing. Ideally sizeHint should be at least\n+// as large as the bitmap represented by input, but this is not required.\n+//\n+// Inverse of formatBitmap.\n+func parseBitmap(input string, sizeHint uint32) (*bitmap.Bitmap, error) {\n+ b := bitmap.New(sizeHint)\n+\n+ if termIdx := strings.IndexAny(input, \"\\n\\000\"); termIdx != -1 {\n+ input = input[:termIdx]\n+ }\n+ input = strings.TrimSpace(input)\n+\n+ if len(input) == 0 {\n+ return &b, nil\n+ }\n+ tokens := strings.Split(input, \",\")\n+\n+ for _, t := range tokens {\n+ start, end, err := parseToken(strings.TrimSpace(t))\n+ if err != nil {\n+ return nil, err\n+ }\n+ for i := start; i <= end; i++ {\n+ b.Add(i)\n+ }\n+ }\n+ return &b, nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/cgroupfs/bitmap_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 cgroupfs\n+\n+import (\n+ \"fmt\"\n+ \"reflect\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/bitmap\"\n+)\n+\n+func TestFormat(t *testing.T) {\n+ tests := []struct {\n+ input []uint32\n+ output string\n+ }{\n+ {[]uint32{1, 2, 3, 4, 7}, \"1-4,7\"},\n+ {[]uint32{2}, \"2\"},\n+ {[]uint32{0, 1, 2}, \"0-2\"},\n+ {[]uint32{}, \"\"},\n+ {[]uint32{1, 3, 4, 5, 6, 9, 11, 13, 14, 15, 16, 17}, \"1,3-6,9,11,13-17\"},\n+ {[]uint32{2, 3, 10, 12, 13, 14, 15, 16, 20, 21, 33, 34, 47}, \"2-3,10,12-16,20-21,33-34,47\"},\n+ }\n+ for i, tt := range tests {\n+ t.Run(fmt.Sprintf(\"case-%d\", i), func(t *testing.T) {\n+ b := bitmap.New(64)\n+ for _, v := range tt.input {\n+ b.Add(v)\n+ }\n+ s := formatBitmap(&b)\n+ if s != tt.output {\n+ t.Errorf(\"Expected %q, got %q\", tt.output, s)\n+ }\n+ b1, err := parseBitmap(s, 64)\n+ if err != nil {\n+ t.Fatalf(\"Failed to parse formatted bitmap: %v\", err)\n+ }\n+ if got, want := b1.ToSlice(), b.ToSlice(); !reflect.DeepEqual(got, want) {\n+ t.Errorf(\"Parsing formatted output doesn't result in the original bitmap. Got %v, want %v\", got, want)\n+ }\n+ })\n+ }\n+}\n+\n+func TestParse(t *testing.T) {\n+ tests := []struct {\n+ input string\n+ output []uint32\n+ shouldFail bool\n+ }{\n+ {\"1\", []uint32{1}, false},\n+ {\"\", []uint32{}, false},\n+ {\"1,2,3,4\", []uint32{1, 2, 3, 4}, false},\n+ {\"1-4\", []uint32{1, 2, 3, 4}, false},\n+ {\"1,2-4\", []uint32{1, 2, 3, 4}, false},\n+ {\"1,2-3,4\", []uint32{1, 2, 3, 4}, false},\n+ {\"1-2,3,4,10,11\", []uint32{1, 2, 3, 4, 10, 11}, false},\n+ {\"1,2-4,5,16\", []uint32{1, 2, 3, 4, 5, 16}, false},\n+ {\"abc\", []uint32{}, true},\n+ {\"1,3-2,4\", []uint32{}, true},\n+ {\"1,3-3,4\", []uint32{}, true},\n+ {\"1,2,3\\000,4\", []uint32{1, 2, 3}, false},\n+ {\"1,2,3\\n,4\", []uint32{1, 2, 3}, false},\n+ }\n+ for i, tt := range tests {\n+ t.Run(fmt.Sprintf(\"case-%d\", i), func(t *testing.T) {\n+ b, err := parseBitmap(tt.input, 64)\n+ if tt.shouldFail {\n+ if err == nil {\n+ t.Fatalf(\"Expected parsing of %q to fail, but it didn't\", tt.input)\n+ }\n+ return\n+ }\n+ if err != nil {\n+ t.Fatalf(\"Failed to parse bitmap: %v\", err)\n+ return\n+ }\n+\n+ got := b.ToSlice()\n+ if !reflect.DeepEqual(got, tt.output) {\n+ t.Errorf(\"Parsed bitmap doesn't match what we expected. Got %v, want %v\", got, tt.output)\n+ }\n+\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "@@ -269,7 +269,7 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ncase controllerCPUAcct:\nc = newCPUAcctController(fs)\ncase controllerCPUSet:\n- c = newCPUSetController(fs)\n+ c = newCPUSetController(k, fs)\ncase controllerJob:\nc = newJobController(fs)\ncase controllerMemory:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"diff": "package cgroupfs\nimport (\n+ \"bytes\"\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/bitmap\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n+ \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\n// +stateify savable\ntype cpusetController struct {\ncontrollerCommon\n+\n+ maxCpus uint32\n+ maxMems uint32\n+\n+ cpus *bitmap.Bitmap\n+ mems *bitmap.Bitmap\n}\nvar _ controller = (*cpusetController)(nil)\n-func newCPUSetController(fs *filesystem) *cpusetController {\n- c := &cpusetController{}\n+func newCPUSetController(k *kernel.Kernel, fs *filesystem) *cpusetController {\n+ cores := uint32(k.ApplicationCores())\n+ cpus := bitmap.New(cores)\n+ cpus.FlipRange(0, cores)\n+ mems := bitmap.New(1)\n+ mems.FlipRange(0, 1)\n+ c := &cpusetController{\n+ cpus: &cpus,\n+ mems: &mems,\n+ maxCpus: uint32(k.ApplicationCores()),\n+ maxMems: 1, // We always report a single NUMA node.\n+ }\nc.controllerCommon.init(controllerCPUSet, fs)\nreturn c\n}\n// AddControlFiles implements controller.AddControlFiles.\nfunc (c *cpusetController) AddControlFiles(ctx context.Context, creds *auth.Credentials, _ *cgroupInode, contents map[string]kernfs.Inode) {\n- // This controller is currently intentionally empty.\n+ contents[\"cpuset.cpus\"] = c.fs.newControllerWritableFile(ctx, creds, &cpusData{c: c})\n+ contents[\"cpuset.mems\"] = c.fs.newControllerWritableFile(ctx, creds, &memsData{c: c})\n+}\n+\n+// +stateify savable\n+type cpusData struct {\n+ c *cpusetController\n+}\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (d *cpusData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"%s\\n\", formatBitmap(d.c.cpus))\n+ return nil\n+}\n+\n+// Write implements vfs.WritableDynamicBytesSource.Write.\n+func (d *cpusData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ src = src.DropFirst64(offset)\n+ if src.NumBytes() > hostarch.PageSize {\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ t := kernel.TaskFromContext(ctx)\n+ buf := t.CopyScratchBuffer(hostarch.PageSize)\n+ n, err := src.CopyIn(ctx, buf)\n+ if err != nil {\n+ return 0, err\n+ }\n+ buf = buf[:n]\n+\n+ b, err := parseBitmap(string(buf), d.c.maxCpus)\n+ if err != nil {\n+ log.Warningf(\"cgroupfs cpuset controller: Failed to parse bitmap: %v\", err)\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ if got, want := b.Maximum(), d.c.maxCpus; got > want {\n+ log.Warningf(\"cgroupfs cpuset controller: Attempted to specify cpuset.cpus beyond highest available cpu: got %d, want %d\", got, want)\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ d.c.cpus = b\n+ return int64(n), nil\n+}\n+\n+// +stateify savable\n+type memsData struct {\n+ c *cpusetController\n+}\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (d *memsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"%s\\n\", formatBitmap(d.c.mems))\n+ return nil\n+}\n+\n+// Write implements vfs.WritableDynamicBytesSource.Write.\n+func (d *memsData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ src = src.DropFirst64(offset)\n+ if src.NumBytes() > hostarch.PageSize {\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ t := kernel.TaskFromContext(ctx)\n+ buf := t.CopyScratchBuffer(hostarch.PageSize)\n+ n, err := src.CopyIn(ctx, buf)\n+ if err != nil {\n+ return 0, err\n+ }\n+ buf = buf[:n]\n+\n+ b, err := parseBitmap(string(buf), d.c.maxMems)\n+ if err != nil {\n+ log.Warningf(\"cgroupfs cpuset controller: Failed to parse bitmap: %v\", err)\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ if got, want := b.Maximum(), d.c.maxMems; got > want {\n+ log.Warningf(\"cgroupfs cpuset controller: Attempted to specify cpuset.mems beyond highest available node: got %d, want %d\", got, want)\n+ return 0, linuxerr.EINVAL\n+ }\n+\n+ d.c.mems = b\n+ return int64(n), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -37,6 +37,8 @@ namespace {\nusing ::testing::_;\nusing ::testing::Contains;\n+using ::testing::Each;\n+using ::testing::Eq;\nusing ::testing::Ge;\nusing ::testing::Gt;\nusing ::testing::Key;\n@@ -383,6 +385,32 @@ PosixError WriteAndVerifyControlValue(const Cgroup& c, std::string_view path,\nreturn NoError();\n}\n+PosixErrorOr<std::vector<bool>> ParseBitmap(std::string s) {\n+ std::vector<bool> bitmap;\n+ bitmap.reserve(64);\n+ for (const std::string_view& t : absl::StrSplit(s, ',')) {\n+ std::vector<std::string> parts = absl::StrSplit(t, absl::MaxSplits('-', 2));\n+ if (parts.size() == 2) {\n+ ASSIGN_OR_RETURN_ERRNO(int64_t start, Atoi<int64_t>(parts[0]));\n+ ASSIGN_OR_RETURN_ERRNO(int64_t end, Atoi<int64_t>(parts[1]));\n+ // Note: start and end are indices into bitmap.\n+ if (end >= bitmap.size()) {\n+ bitmap.resize(end + 1, false);\n+ }\n+ for (int i = start; i <= end; ++i) {\n+ bitmap[i] = true;\n+ }\n+ } else { // parts.size() == 1, 0 not possible.\n+ ASSIGN_OR_RETURN_ERRNO(int64_t i, Atoi<int64_t>(parts[0]));\n+ if (i >= bitmap.size()) {\n+ bitmap.resize(i + 1, false);\n+ }\n+ bitmap[i] = true;\n+ }\n+ }\n+ return bitmap;\n+}\n+\nTEST(JobCgroup, ReadWriteRead) {\nSKIP_IF(!CgroupsAvailable());\n@@ -396,6 +424,59 @@ TEST(JobCgroup, ReadWriteRead) {\nEXPECT_NO_ERRNO(WriteAndVerifyControlValue(c, \"job.id\", LLONG_MAX));\n}\n+TEST(CpusetCgroup, Defaults) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"cpuset\"));\n+\n+ std::string cpus =\n+ ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.cpus\"));\n+ std::vector<bool> cpus_bitmap = ASSERT_NO_ERRNO_AND_VALUE(ParseBitmap(cpus));\n+ EXPECT_GT(cpus_bitmap.size(), 0);\n+ EXPECT_THAT(cpus_bitmap, Each(Eq(true)));\n+\n+ std::string mems =\n+ ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.mems\"));\n+ std::vector<bool> mems_bitmap = ASSERT_NO_ERRNO_AND_VALUE(ParseBitmap(mems));\n+ EXPECT_GT(mems_bitmap.size(), 0);\n+ EXPECT_THAT(mems_bitmap, Each(Eq(true)));\n+}\n+\n+TEST(CpusetCgroup, SetMask) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"cpuset\"));\n+\n+ std::string cpus =\n+ ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.cpus\"));\n+ std::vector<bool> cpus_bitmap = ASSERT_NO_ERRNO_AND_VALUE(ParseBitmap(cpus));\n+\n+ SKIP_IF(cpus_bitmap.size() <= 1); // \"Not enough CPUs\"\n+\n+ int max_cpu = cpus_bitmap.size() - 1;\n+ ASSERT_NO_ERRNO(\n+ c.WriteControlFile(\"cpuset.cpus\", absl::StrCat(\"1-\", max_cpu)));\n+ cpus_bitmap[0] = false;\n+ cpus = ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.cpus\"));\n+ std::vector<bool> cpus_bitmap_after =\n+ ASSERT_NO_ERRNO_AND_VALUE(ParseBitmap(cpus));\n+ EXPECT_EQ(cpus_bitmap_after, cpus_bitmap);\n+}\n+\n+TEST(CpusetCgroup, SetEmptyMask) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"cpuset\"));\n+ ASSERT_NO_ERRNO(c.WriteControlFile(\"cpuset.cpus\", \"\"));\n+ std::string_view cpus = absl::StripAsciiWhitespace(\n+ ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.cpus\")));\n+ EXPECT_EQ(cpus, \"\");\n+ ASSERT_NO_ERRNO(c.WriteControlFile(\"cpuset.mems\", \"\"));\n+ std::string_view mems = absl::StripAsciiWhitespace(\n+ ASSERT_NO_ERRNO_AND_VALUE(c.ReadControlFile(\"cpuset.mems\")));\n+ EXPECT_EQ(mems, \"\");\n+}\n+\nTEST(ProcCgroups, Empty) {\nSKIP_IF(!CgroupsAvailable());\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/cgroup_util.cc",
"new_path": "test/util/cgroup_util.cc",
"diff": "@@ -69,6 +69,9 @@ PosixError Cgroup::WriteControlFile(absl::string_view name,\nconst std::string& value) const {\nASSIGN_OR_RETURN_ERRNO(FileDescriptor fd, Open(Relpath(name), O_WRONLY));\nRETURN_ERROR_IF_SYSCALL_FAIL(WriteFd(fd.get(), value.c_str(), value.size()));\n+ const std::string alias_path = absl::StrFormat(\"[cg#%d]/%s\", id_, name);\n+ std::cerr << absl::StreamFormat(\"echo '%s' > %s\", value, alias_path)\n+ << std::endl;\nreturn NoError();\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub cpuset cgroup control files.
PiperOrigin-RevId: 404382475 |
259,992 | 19.10.2021 17:03:06 | 25,200 | 6dde3d5ae51030fceb0798d671d19ec1df3ae7a3 | Fix typo in FIXME | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/kvm_safecopy_test.go",
"new_path": "pkg/sentry/platform/kvm/kvm_safecopy_test.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// FIXME(gvisor.dev/issue//6629): These tests don't pass on ARM64.\n+// FIXME(gvisor.dev/issue/6629): These tests don't pass on ARM64.\n//\n//go:build amd64\n// +build amd64\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix typo in FIXME
PiperOrigin-RevId: 404400399 |
260,004 | 19.10.2021 17:22:45 | 25,200 | bdf4e41c863ce025c67bfd30b5c52d15bdc54ced | Always parse Transport headers
..including ICMP headers before delivering them to the
TransportDispatcher.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/parse/parse.go",
"new_path": "pkg/tcpip/header/parse/parse.go",
"diff": "@@ -110,6 +110,16 @@ traverseExtensions:\nswitch extHdr := extHdr.(type) {\ncase header.IPv6FragmentExtHdr:\n+ if extHdr.IsAtomic() {\n+ // This fragment extension header indicates that this packet is an\n+ // atomic fragment. An atomic fragment is a fragment that contains\n+ // all the data required to reassemble a full packet. As per RFC 6946,\n+ // atomic fragments must not interfere with \"normal\" fragmented traffic\n+ // so we skip processing the fragment instead of feeding it through the\n+ // reassembly process below.\n+ continue\n+ }\n+\nif fragID == 0 && fragOffset == 0 && !fragMore {\nfragID = extHdr.ID()\nfragOffset = extHdr.FragmentOffset()\n@@ -175,3 +185,61 @@ func TCP(pkt *stack.PacketBuffer) bool {\npkt.TransportProtocolNumber = header.TCPProtocolNumber\nreturn ok\n}\n+\n+// ICMPv4 populates the packet buffer's transport header with an ICMPv4 header,\n+// if present.\n+//\n+// Returns true if an ICMPv4 header was successfully parsed.\n+func ICMPv4(pkt *stack.PacketBuffer) bool {\n+ if _, ok := pkt.TransportHeader().Consume(header.ICMPv4MinimumSize); ok {\n+ pkt.TransportProtocolNumber = header.ICMPv4ProtocolNumber\n+ return true\n+ }\n+ return false\n+}\n+\n+// ICMPv6 populates the packet buffer's transport header with an ICMPv4 header,\n+// if present.\n+//\n+// Returns true if an ICMPv6 header was successfully parsed.\n+func ICMPv6(pkt *stack.PacketBuffer) bool {\n+ hdr, ok := pkt.Data().PullUp(header.ICMPv6MinimumSize)\n+ if !ok {\n+ return false\n+ }\n+\n+ h := header.ICMPv6(hdr)\n+ switch h.Type() {\n+ case header.ICMPv6RouterSolicit,\n+ header.ICMPv6RouterAdvert,\n+ header.ICMPv6NeighborSolicit,\n+ header.ICMPv6NeighborAdvert,\n+ header.ICMPv6RedirectMsg:\n+ size := pkt.Data().Size()\n+ if _, ok := pkt.TransportHeader().Consume(size); !ok {\n+ panic(fmt.Sprintf(\"expected to consume the full data of size = %d bytes into transport header\", size))\n+ }\n+ case header.ICMPv6MulticastListenerQuery,\n+ header.ICMPv6MulticastListenerReport,\n+ header.ICMPv6MulticastListenerDone:\n+ size := header.ICMPv6HeaderSize + header.MLDMinimumSize\n+ if _, ok := pkt.TransportHeader().Consume(size); !ok {\n+ return false\n+ }\n+ case header.ICMPv6DstUnreachable,\n+ header.ICMPv6PacketTooBig,\n+ header.ICMPv6TimeExceeded,\n+ header.ICMPv6ParamProblem,\n+ header.ICMPv6EchoRequest,\n+ header.ICMPv6EchoReply:\n+ fallthrough\n+ default:\n+ if _, ok := pkt.TransportHeader().Consume(header.ICMPv6MinimumSize); !ok {\n+ // Checked above if the packet buffer holds at least the minimum size for\n+ // an ICMPv6 packet.\n+ panic(fmt.Sprintf(\"expected to consume %d bytes\", header.ICMPv6MinimumSize))\n+ }\n+ }\n+ pkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber\n+ return true\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -175,18 +175,14 @@ func (e *endpoint) handleControl(errInfo stack.TransportError, pkt *stack.Packet\nfunc (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\nreceived := e.stats.icmp.packetsReceived\n- // ICMP packets don't have their TransportHeader fields set. See\n- // icmp/protocol.go:protocol.Parse for a full explanation. Not all ICMP types\n- // require consuming the header, so we only call PullUp.\n- v, ok := pkt.Data().PullUp(header.ICMPv4MinimumSize)\n- if !ok {\n+ h := header.ICMPv4(pkt.TransportHeader().View())\n+ if len(h) < header.ICMPv4MinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n- h := header.ICMPv4(v)\n// Only do in-stack processing if the checksum is correct.\n- if pkt.Data().AsRange().Checksum() != 0xffff {\n+ if header.Checksum(h, pkt.Data().AsRange().Checksum()) != 0xffff {\nreceived.invalid.Increment()\n// It's possible that a raw socket expects to receive this regardless\n// of checksum errors. If it's an echo request we know it's safe because\n@@ -251,7 +247,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\n// TODO(gvisor.dev/issue/4399): The copy may not be needed if there are no\n// waiting endpoints. Consider moving responsibility for doing the copy to\n// DeliverTransportPacket so that is is only done when needed.\n- replyData := pkt.Data().AsRange().ToOwnedView()\n+ replyData := stack.PayloadSince(pkt.TransportHeader())\nipHdr := header.IPv4(pkt.NetworkHeader().View())\nlocalAddressBroadcast := pkt.NetworkPacketInfo.LocalAddressBroadcast\n@@ -344,9 +340,6 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer) {\nmtu := h.MTU()\ncode := h.Code()\n- if _, ok := pkt.Data().Consume(header.ICMPv4MinimumSize); !ok {\n- panic(\"could not consume ICMPv4MinimumSize bytes\")\n- }\nswitch code {\ncase header.ICMPv4HostUnreachable:\ne.handleControl(&icmpv4DestinationHostUnreachableSockError{}, pkt)\n@@ -574,20 +567,6 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) tcpip\n// Don't respond to icmp error packets.\nif origIPHdr.Protocol() == uint8(header.ICMPv4ProtocolNumber) {\n- // TODO(gvisor.dev/issue/3810):\n- // Unfortunately the current stack pretty much always has ICMPv4 headers\n- // in the Data section of the packet but there is no guarantee that is the\n- // case. If this is the case grab the header to make it like all other\n- // packet types. When this is cleaned up the Consume should be removed.\n- if transportHeader.IsEmpty() {\n- var ok bool\n- transportHeader, ok = pkt.TransportHeader().Consume(header.ICMPv4MinimumSize)\n- if !ok {\n- return nil\n- }\n- } else if transportHeader.Size() < header.ICMPv4MinimumSize {\n- return nil\n- }\n// We need to decide to explicitly name the packets we can respond to or\n// the ones we can not respond to. The decision is somewhat arbitrary and\n// if problems arise this could be reversed. It was judged less of a breach\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -984,7 +984,7 @@ func (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer,\n}\nproto := h.Protocol()\n- resPkt, _, ready, err := e.protocol.fragmentation.Process(\n+ resPkt, transProtoNum, ready, err := e.protocol.fragmentation.Process(\n// As per RFC 791 section 2.3, the identification value is unique\n// for a source-destination pair and protocol.\nfragmentation.FragmentID{\n@@ -1015,6 +1015,8 @@ func (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer,\nh.SetTotalLength(uint16(pkt.Data().Size() + len(h)))\nh.SetFlagsFragmentOffset(0, 0)\n+ e.protocol.parseTransport(pkt, tcpip.TransportProtocolNumber(transProtoNum))\n+\n// Now that the packet is reassembled, it can be sent to raw sockets.\ne.dispatcher.DeliverRawPacket(h.TransportProtocol(), pkt)\n}\n@@ -1310,6 +1312,19 @@ func (p *protocol) parseAndValidate(pkt *stack.PacketBuffer) (header.IPv4, bool)\n}\nif hasTransportHdr {\n+ p.parseTransport(pkt, transProtoNum)\n+ }\n+\n+ return h, true\n+}\n+\n+func (p *protocol) parseTransport(pkt *stack.PacketBuffer, transProtoNum tcpip.TransportProtocolNumber) {\n+ if transProtoNum == header.ICMPv4ProtocolNumber {\n+ // The transport layer will handle transport layer parsing errors.\n+ _ = parse.ICMPv4(pkt)\n+ return\n+ }\n+\nswitch err := p.stack.ParsePacketBufferTransport(transProtoNum, pkt); err {\ncase stack.ParsedOK:\ncase stack.UnknownTransportProtocol, stack.TransportLayerParseError:\n@@ -1320,9 +1335,6 @@ func (p *protocol) parseAndValidate(pkt *stack.PacketBuffer) (header.IPv4, bool)\n}\n}\n- return h, true\n-}\n-\n// Parse implements stack.NetworkProtocol.\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.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "@@ -274,7 +274,7 @@ func isMLDValid(pkt *stack.PacketBuffer, iph header.IPv6, routerAlert *header.IP\nif routerAlert == nil || routerAlert.Value != header.IPv6RouterAlertMLD {\nreturn false\n}\n- if pkt.Data().Size() < header.ICMPv6HeaderSize+header.MLDMinimumSize {\n+ if pkt.TransportHeader().View().Size() < header.ICMPv6HeaderSize+header.MLDMinimumSize {\nreturn false\n}\nif iph.HopLimit() != header.MLDHopLimit {\n@@ -289,20 +289,17 @@ func isMLDValid(pkt *stack.PacketBuffer, iph header.IPv6, routerAlert *header.IP\nfunc (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, routerAlert *header.IPv6RouterAlertOption) {\nsent := e.stats.icmp.packetsSent\nreceived := e.stats.icmp.packetsReceived\n- // ICMP packets don't have their TransportHeader fields set. See\n- // icmp/protocol.go:protocol.Parse for a full explanation.\n- v, ok := pkt.Data().PullUp(header.ICMPv6HeaderSize)\n- if !ok {\n+ h := header.ICMPv6(pkt.TransportHeader().View())\n+ if len(h) < header.ICMPv6MinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n- h := header.ICMPv6(v)\niph := header.IPv6(pkt.NetworkHeader().View())\nsrcAddr := iph.SourceAddress()\ndstAddr := iph.DestinationAddress()\n// Validate ICMPv6 checksum before processing the packet.\n- payload := pkt.Data().AsRange().SubRange(len(h))\n+ payload := pkt.Data().AsRange()\nif got, want := h.Checksum(), header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\nHeader: h,\nSrc: srcAddr,\n@@ -329,12 +326,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nswitch icmpType := h.Type(); icmpType {\ncase header.ICMPv6PacketTooBig:\nreceived.packetTooBig.Increment()\n- hdr, ok := pkt.Data().Consume(header.ICMPv6PacketTooBigMinimumSize)\n- if !ok {\n- received.invalid.Increment()\n- return\n- }\n- networkMTU, err := calculateNetworkMTU(header.ICMPv6(hdr).MTU(), header.IPv6MinimumSize)\n+ networkMTU, err := calculateNetworkMTU(h.MTU(), header.IPv6MinimumSize)\nif err != nil {\nnetworkMTU = 0\n}\n@@ -342,13 +334,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\ncase header.ICMPv6DstUnreachable:\nreceived.dstUnreachable.Increment()\n- hdr, ok := pkt.Data().Consume(header.ICMPv6DstUnreachableMinimumSize)\n- if !ok {\n- received.invalid.Increment()\n- return\n- }\n- code := header.ICMPv6(hdr).Code()\n- switch code {\n+ switch h.Code() {\ncase header.ICMPv6NetworkUnreachable:\ne.handleControl(&icmpv6DestinationNetworkUnreachableSockError{}, pkt)\ncase header.ICMPv6PortUnreachable:\n@@ -356,16 +342,12 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\n}\ncase header.ICMPv6NeighborSolicit:\nreceived.neighborSolicit.Increment()\n- if !isNDPValid() || pkt.Data().Size() < header.ICMPv6NeighborSolicitMinimumSize {\n+ if !isNDPValid() || len(h) < header.ICMPv6NeighborSolicitMinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n- // The remainder of payload must be only the neighbor solicitation, so\n- // payload.AsView() always returns the solicitation. Per RFC 6980 section 5,\n- // NDP messages cannot be fragmented. Also note that in the common case NDP\n- // datagrams are very small and AsView() will not incur allocations.\n- ns := header.NDPNeighborSolicit(payload.AsView())\n+ ns := header.NDPNeighborSolicit(h.MessageBody())\ntargetAddr := ns.TargetAddress()\n// As per RFC 4861 section 4.3, the Target Address MUST NOT be a multicast\n@@ -578,16 +560,12 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\ncase header.ICMPv6NeighborAdvert:\nreceived.neighborAdvert.Increment()\n- if !isNDPValid() || pkt.Data().Size() < header.ICMPv6NeighborAdvertMinimumSize {\n+ if !isNDPValid() || len(h) < header.ICMPv6NeighborAdvertMinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n- // The remainder of payload must be only the neighbor advertisement, so\n- // payload.AsView() always returns the advertisement. Per RFC 6980 section\n- // 5, NDP messages cannot be fragmented. Also note that in the common case\n- // NDP datagrams are very small and AsView() will not incur allocations.\n- na := header.NDPNeighborAdvert(payload.AsView())\n+ na := header.NDPNeighborAdvert(h.MessageBody())\nit, err := na.Options().Iter(false /* check */)\nif err != nil {\n@@ -674,12 +652,6 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\ncase header.ICMPv6EchoRequest:\nreceived.echoRequest.Increment()\n- icmpHdr, ok := pkt.TransportHeader().Consume(header.ICMPv6EchoMinimumSize)\n- if !ok {\n- received.invalid.Increment()\n- return\n- }\n-\n// As per RFC 4291 section 2.7, multicast addresses must not be used as\n// source addresses in IPv6 packets.\nlocalAddr := dstAddr\n@@ -705,7 +677,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\n})\nicmp := header.ICMPv6(replyPkt.TransportHeader().Push(header.ICMPv6EchoMinimumSize))\npkt.TransportProtocolNumber = header.ICMPv6ProtocolNumber\n- copy(icmp, icmpHdr)\n+ copy(icmp, h)\nicmp.SetType(header.ICMPv6EchoReply)\ndataRange := replyPkt.Data().AsRange()\nicmp.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\n@@ -727,7 +699,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\ncase header.ICMPv6EchoReply:\nreceived.echoReply.Increment()\n- if pkt.Data().Size() < header.ICMPv6EchoMinimumSize {\n+ if len(h) < header.ICMPv6EchoMinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n@@ -747,7 +719,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\n//\n// Is the NDP payload of sufficient size to hold a Router Solictation?\n- if !isNDPValid() || pkt.Data().Size()-header.ICMPv6HeaderSize < header.NDPRSMinimumSize {\n+ if !isNDPValid() || len(h)-header.ICMPv6HeaderSize < header.NDPRSMinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n@@ -757,9 +729,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nreturn\n}\n- // Note that in the common case NDP datagrams are very small and AsView()\n- // will not incur allocations.\n- rs := header.NDPRouterSolicit(payload.AsView())\n+ rs := header.NDPRouterSolicit(h.MessageBody())\nit, err := rs.Options().Iter(false /* check */)\nif err != nil {\n// Options are not valid as per the wire format, silently drop the packet.\n@@ -803,7 +773,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\n//\n// Is the NDP payload of sufficient size to hold a Router Advertisement?\n- if !isNDPValid() || pkt.Data().Size()-header.ICMPv6HeaderSize < header.NDPRAMinimumSize {\n+ if !isNDPValid() || len(h)-header.ICMPv6HeaderSize < header.NDPRAMinimumSize {\nreceived.invalid.Increment()\nreturn\n}\n@@ -817,9 +787,7 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nreturn\n}\n- // Note that in the common case NDP datagrams are very small and AsView()\n- // will not incur allocations.\n- ra := header.NDPRouterAdvert(payload.AsView())\n+ ra := header.NDPRouterAdvert(h.MessageBody())\nit, err := ra.Options().Iter(false /* check */)\nif err != nil {\n// Options are not valid as per the wire format, silently drop the packet.\n@@ -897,11 +865,11 @@ func (e *endpoint) handleICMP(pkt *stack.PacketBuffer, hasFragmentHeader bool, r\nswitch icmpType {\ncase header.ICMPv6MulticastListenerQuery:\ne.mu.Lock()\n- e.mu.mld.handleMulticastListenerQuery(header.MLD(payload.AsView()))\n+ e.mu.mld.handleMulticastListenerQuery(header.MLD(h.MessageBody()))\ne.mu.Unlock()\ncase header.ICMPv6MulticastListenerReport:\ne.mu.Lock()\n- e.mu.mld.handleMulticastListenerReport(header.MLD(payload.AsView()))\n+ e.mu.mld.handleMulticastListenerReport(header.MLD(h.MessageBody()))\ne.mu.Unlock()\ncase header.ICMPv6MulticastListenerDone:\ndefault:\n@@ -1182,18 +1150,7 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) tcpip\n}\nif pkt.TransportProtocolNumber == header.ICMPv6ProtocolNumber {\n- // TODO(gvisor.dev/issues/3810): Sort this out when ICMP headers are stored.\n- // Unfortunately at this time ICMP Packets do not have a transport\n- // header separated out. It is in the Data part so we need to\n- // separate it out now. We will just pretend it is a minimal length\n- // ICMP packet as we don't really care if any later bits of a\n- // larger ICMP packet are in the header view or in the Data view.\n- transport, ok := pkt.TransportHeader().Consume(header.ICMPv6MinimumSize)\n- if !ok {\n- return nil\n- }\n- typ := header.ICMPv6(transport).Type()\n- if typ.IsErrorType() || typ == header.ICMPv6RedirectMsg {\n+ if typ := header.ICMPv6(pkt.TransportHeader().View()).Type(); typ.IsErrorType() || typ == header.ICMPv6RedirectMsg {\nreturn nil\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -1554,13 +1554,19 @@ func (e *endpoint) processExtensionHeaders(h header.IPv6, pkt *stack.PacketBuffe\nreturn fmt.Errorf(\"could not consume %d bytes\", trim)\n}\n+ proto := tcpip.TransportProtocolNumber(extHdr.Identifier)\n+ // If the packet was reassembled from a fragment, it will not have a\n+ // transport header set yet.\n+ if pkt.TransportHeader().View().IsEmpty() {\n+ e.protocol.parseTransport(pkt, proto)\n+ }\n+\nstats.PacketsDelivered.Increment()\n- if p := tcpip.TransportProtocolNumber(extHdr.Identifier); p == header.ICMPv6ProtocolNumber {\n- pkt.TransportProtocolNumber = p\n+ if proto == header.ICMPv6ProtocolNumber {\ne.handleICMP(pkt, hasFragmentHeader, routerAlert)\n} else {\nstats.PacketsDelivered.Increment()\n- switch res := e.dispatcher.DeliverTransportPacket(p, pkt); res {\n+ switch res := e.dispatcher.DeliverTransportPacket(proto, pkt); res {\ncase stack.TransportPacketHandled:\ncase stack.TransportPacketDestinationPortUnreachable:\n// As per RFC 4443 section 3.1:\n@@ -2161,6 +2167,19 @@ func (p *protocol) parseAndValidate(pkt *stack.PacketBuffer) (header.IPv6, bool)\n}\nif hasTransportHdr {\n+ p.parseTransport(pkt, transProtoNum)\n+ }\n+\n+ return h, true\n+}\n+\n+func (p *protocol) parseTransport(pkt *stack.PacketBuffer, transProtoNum tcpip.TransportProtocolNumber) {\n+ if transProtoNum == header.ICMPv6ProtocolNumber {\n+ // The transport layer will handle transport layer parsing errors.\n+ _ = parse.ICMPv6(pkt)\n+ return\n+ }\n+\nswitch err := p.stack.ParsePacketBufferTransport(transProtoNum, pkt); err {\ncase stack.ParsedOK:\ncase stack.UnknownTransportProtocol, stack.TransportLayerParseError:\n@@ -2171,9 +2190,6 @@ func (p *protocol) parseAndValidate(pkt *stack.PacketBuffer) (header.IPv6, bool)\n}\n}\n- return h, true\n-}\n-\n// Parse implements stack.NetworkProtocol.\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/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -833,25 +833,10 @@ func (n *nic) DeliverTransportPacket(protocol tcpip.TransportProtocolNumber, pkt\ntransProto := state.proto\n- // TransportHeader is empty only when pkt is an ICMP packet or was reassembled\n- // from fragments.\nif pkt.TransportHeader().View().IsEmpty() {\n- // ICMP packets don't have their TransportHeader fields set yet, parse it\n- // here. See icmp/protocol.go:protocol.Parse for a full explanation.\n- if protocol == header.ICMPv4ProtocolNumber || protocol == header.ICMPv6ProtocolNumber {\n- // ICMP packets may be longer, but until icmp.Parse is implemented, here\n- // we parse it using the minimum size.\n- if _, ok := pkt.TransportHeader().Consume(transProto.MinimumPacketSize()); !ok {\nn.stats.malformedL4RcvdPackets.Increment()\n- // We consider a malformed transport packet handled because there is\n- // nothing the caller can do.\nreturn TransportPacketHandled\n}\n- } else if !transProto.Parse(pkt) {\n- n.stats.malformedL4RcvdPackets.Increment()\n- return TransportPacketHandled\n- }\n- }\nsrcPort, dstPort, err := transProto.ParsePorts(pkt.TransportHeader().View())\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1865,12 +1865,6 @@ const (\n// ParsePacketBufferTransport parses the provided packet buffer's transport\n// header.\nfunc (s *Stack) ParsePacketBufferTransport(protocol tcpip.TransportProtocolNumber, pkt *PacketBuffer) ParseResult {\n- // ICMP packets don't have their TransportHeader fields set yet, parse it\n- // here. See icmp/protocol.go:protocol.Parse for a full explanation.\n- if protocol == header.ICMPv4ProtocolNumber || protocol == header.ICMPv6ProtocolNumber {\n- return ParsedOK\n- }\n-\npkt.TransportProtocolNumber = protocol\n// Parse the transport header if present.\nstate, ok := s.transportProtocols[protocol]\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -155,8 +155,18 @@ func (f *fakeNetworkEndpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n+ transProtoNum := tcpip.TransportProtocolNumber(netHdr[protocolNumberOffset])\n+ switch err := f.proto.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// Dispatch the packet to the transport protocol.\n- f.dispatcher.DeliverTransportPacket(tcpip.TransportProtocolNumber(pkt.NetworkHeader().View()[protocolNumberOffset]), pkt)\n+ f.dispatcher.DeliverTransportPacket(transProtoNum, pkt)\n}\nfunc (f *fakeNetworkEndpoint) MaxHeaderLength() uint16 {\n@@ -218,6 +228,8 @@ func (*fakeNetworkEndpointStats) IsNetworkEndpointStats() {}\n// number of packets sent and received via endpoints of this protocol. The index\n// where packets are added is given by the packet's destination address MOD 10.\ntype fakeNetworkProtocol struct {\n+ stack *stack.Stack\n+\npacketCount [10]int\nsendPacketCount [10]int\ndefaultTTL uint8\n@@ -299,8 +311,8 @@ func (f *fakeNetworkEndpoint) SetForwarding(v bool) {\nf.mu.forwarding = v\n}\n-func fakeNetFactory(*stack.Stack) stack.NetworkProtocol {\n- return &fakeNetworkProtocol{}\n+func fakeNetFactory(s *stack.Stack) stack.NetworkProtocol {\n+ return &fakeNetworkProtocol{stack: s}\n}\n// linkEPWithMockedAttach is a stack.LinkEndpoint that tests can use to verify\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_test.go",
"new_path": "pkg/tcpip/stack/transport_test.go",
"diff": "@@ -331,8 +331,11 @@ func (*fakeTransportProtocol) Wait() {}\n// Parse implements TransportProtocol.Parse.\nfunc (*fakeTransportProtocol) Parse(pkt *stack.PacketBuffer) bool {\n- _, ok := pkt.TransportHeader().Consume(fakeTransHeaderLen)\n- return ok\n+ if _, ok := pkt.TransportHeader().Consume(fakeTransHeaderLen); ok {\n+ pkt.TransportProtocolNumber = fakeTransNumber\n+ return true\n+ }\n+ return false\n}\nfunc fakeTransFactory(s *stack.Stack) stack.TransportProtocol {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Always parse Transport headers
..including ICMP headers before delivering them to the
TransportDispatcher.
Updates #3810.
PiperOrigin-RevId: 404404002 |
259,992 | 20.10.2021 10:42:29 | 25,200 | c23d67f3c092176d0d5313f186d571d4067c1d57 | Report correct error when restore fails
When file corruption is detected, report vfs.ErrCorruption to
distinguish corruption error from other restore errors.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"new_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"diff": "@@ -277,18 +277,18 @@ func (d *dentry) restoreFile(ctx context.Context, file p9file, qid p9.QID, attrM\nif d.isRegularFile() {\nif opts.ValidateFileSizes {\nif !attrMask.Size {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: file size not available\", genericDebugPathname(d))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: file size not available\", genericDebugPathname(d))}\n}\nif d.size != attr.Size {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: size changed from %d to %d\", genericDebugPathname(d), d.size, attr.Size)\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: size changed from %d to %d\", genericDebugPathname(d), d.size, attr.Size)}\n}\n}\nif opts.ValidateFileModificationTimestamps {\nif !attrMask.MTime {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime not available\", genericDebugPathname(d))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime not available\", genericDebugPathname(d))}\n}\nif want := dentryTimestampFromP9(attr.MTimeSeconds, attr.MTimeNanoSeconds); d.mtime != want {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime changed from %+v to %+v\", genericDebugPathname(d), linux.NsecToStatxTimestamp(d.mtime), linux.NsecToStatxTimestamp(want))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime changed from %+v to %+v\", genericDebugPathname(d), linux.NsecToStatxTimestamp(d.mtime), linux.NsecToStatxTimestamp(want))}\n}\n}\n}\n@@ -326,18 +326,18 @@ func (d *dentry) restoreFileLisa(ctx context.Context, inode *lisafs.Inode, opts\nif d.isRegularFile() {\nif opts.ValidateFileSizes {\nif inode.Stat.Mask&linux.STATX_SIZE != 0 {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: file size not available\", genericDebugPathname(d))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: file size not available\", genericDebugPathname(d))}\n}\nif d.size != inode.Stat.Size {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: size changed from %d to %d\", genericDebugPathname(d), d.size, inode.Stat.Size)\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: file size validation failed: size changed from %d to %d\", genericDebugPathname(d), d.size, inode.Stat.Size)}\n}\n}\nif opts.ValidateFileModificationTimestamps {\nif inode.Stat.Mask&linux.STATX_MTIME != 0 {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime not available\", genericDebugPathname(d))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime not available\", genericDebugPathname(d))}\n}\nif want := dentryTimestampFromLisa(inode.Stat.Mtime); d.mtime != want {\n- return fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime changed from %+v to %+v\", genericDebugPathname(d), linux.NsecToStatxTimestamp(d.mtime), linux.NsecToStatxTimestamp(want))\n+ return vfs.ErrCorruption{fmt.Errorf(\"gofer.dentry(%q).restoreFile: mtime validation failed: mtime changed from %+v to %+v\", genericDebugPathname(d), linux.NsecToStatxTimestamp(d.mtime), linux.NsecToStatxTimestamp(want))}\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/save_restore.go",
"new_path": "pkg/sentry/vfs/save_restore.go",
"diff": "package vfs\nimport (\n- \"fmt\"\n\"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -24,6 +23,18 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+// ErrCorruption indicates a failed restore due to external file system state in\n+// corruption.\n+type ErrCorruption struct {\n+ // Err is the wrapped error.\n+ Err error\n+}\n+\n+// Error returns a sensible description of the restore error.\n+func (e ErrCorruption) Error() string {\n+ return \"restore failed due to external file system state in corruption: \" + e.Err.Error()\n+}\n+\n// FilesystemImplSaveRestoreExtension is an optional extension to\n// FilesystemImpl.\ntype FilesystemImplSaveRestoreExtension interface {\n@@ -37,38 +48,30 @@ type FilesystemImplSaveRestoreExtension interface {\n// PrepareSave prepares all filesystems for serialization.\nfunc (vfs *VirtualFilesystem) PrepareSave(ctx context.Context) error {\n- failures := 0\nfor fs := range vfs.getFilesystems() {\nif ext, ok := fs.impl.(FilesystemImplSaveRestoreExtension); ok {\nif err := ext.PrepareSave(ctx); err != nil {\n- ctx.Warningf(\"%T.PrepareSave failed: %v\", fs.impl, err)\n- failures++\n+ fs.DecRef(ctx)\n+ return err\n}\n}\nfs.DecRef(ctx)\n}\n- if failures != 0 {\n- return fmt.Errorf(\"%d filesystems failed to prepare for serialization\", failures)\n- }\nreturn nil\n}\n// CompleteRestore completes restoration from checkpoint for all filesystems\n// after deserialization.\nfunc (vfs *VirtualFilesystem) CompleteRestore(ctx context.Context, opts *CompleteRestoreOptions) error {\n- failures := 0\nfor fs := range vfs.getFilesystems() {\nif ext, ok := fs.impl.(FilesystemImplSaveRestoreExtension); ok {\nif err := ext.CompleteRestore(ctx, *opts); err != nil {\n- ctx.Warningf(\"%T.CompleteRestore failed: %v\", fs.impl, err)\n- failures++\n+ fs.DecRef(ctx)\n+ return err\n}\n}\nfs.DecRef(ctx)\n}\n- if failures != 0 {\n- return fmt.Errorf(\"%d filesystems failed to complete restore after deserialization\", failures)\n- }\nreturn nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Report correct error when restore fails
When file corruption is detected, report vfs.ErrCorruption to
distinguish corruption error from other restore errors.
Updates #1035
PiperOrigin-RevId: 404588445 |
259,992 | 20.10.2021 14:12:55 | 25,200 | cfcd3eba9f011b73be1f359f6da7af7f2584a089 | Add Debug to log file header | [
{
"change_type": "MODIFY",
"old_path": "runsc/cli/main.go",
"new_path": "runsc/cli/main.go",
"diff": "@@ -229,6 +229,7 @@ func Main(version string) {\nlog.Infof(\"\\t\\tNetwork: %v, logging: %t\", conf.Network, conf.LogPackets)\nlog.Infof(\"\\t\\tStrace: %t, max size: %d, syscalls: %s\", conf.Strace, conf.StraceLogSize, conf.StraceSyscalls)\nlog.Infof(\"\\t\\tVFS2 enabled: %t, LISAFS: %t\", conf.VFS2, conf.Lisafs)\n+ log.Infof(\"\\t\\tDebug: %v\", conf.Debug)\nlog.Infof(\"***************************\")\nif conf.TestOnlyAllowRunAsCurrentUserWithoutChroot {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Debug to log file header
PiperOrigin-RevId: 404635832 |
259,962 | 21.10.2021 13:50:08 | 25,200 | 207221ffb27f2010c46468d827f1817432df3960 | Add an integration test for istio like redirect.
Updates #6441,#6317 | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/adapters/gonet/gonet.go",
"new_path": "pkg/tcpip/adapters/gonet/gonet.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"bytes\"\n\"context\"\n\"errors\"\n+ \"fmt\"\n\"io\"\n\"net\"\n\"time\"\n@@ -471,9 +472,9 @@ func DialTCP(s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtoc\nreturn DialContextTCP(context.Background(), s, addr, network)\n}\n-// DialContextTCP creates a new TCPConn connected to the specified address\n-// with the option of adding cancellation and timeouts.\n-func DialContextTCP(ctx context.Context, s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*TCPConn, error) {\n+// DialTCPWithBind creates a new TCPConn connected to the specified\n+// remoteAddress with its local address bound to localAddr.\n+func DialTCPWithBind(ctx context.Context, s *stack.Stack, localAddr, remoteAddr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*TCPConn, error) {\n// Create TCP endpoint, then connect.\nvar wq waiter.Queue\nep, err := s.NewEndpoint(tcp.ProtocolNumber, network, &wq)\n@@ -494,7 +495,14 @@ func DialContextTCP(ctx context.Context, s *stack.Stack, addr tcpip.FullAddress,\ndefault:\n}\n- err = ep.Connect(addr)\n+ // Bind before connect if requested.\n+ if localAddr != (tcpip.FullAddress{}) {\n+ if err = ep.Bind(localAddr); err != nil {\n+ return nil, fmt.Errorf(\"ep.Bind(%+v) = %s\", localAddr, err)\n+ }\n+ }\n+\n+ err = ep.Connect(remoteAddr)\nif _, ok := err.(*tcpip.ErrConnectStarted); ok {\nselect {\ncase <-ctx.Done():\n@@ -510,7 +518,7 @@ func DialContextTCP(ctx context.Context, s *stack.Stack, addr tcpip.FullAddress,\nreturn nil, &net.OpError{\nOp: \"connect\",\nNet: \"tcp\",\n- Addr: fullToTCPAddr(addr),\n+ Addr: fullToTCPAddr(remoteAddr),\nErr: errors.New(err.String()),\n}\n}\n@@ -518,6 +526,12 @@ func DialContextTCP(ctx context.Context, s *stack.Stack, addr tcpip.FullAddress,\nreturn NewTCPConn(&wq, ep), nil\n}\n+// DialContextTCP creates a new TCPConn connected to the specified address\n+// with the option of adding cancellation and timeouts.\n+func DialContextTCP(ctx context.Context, s *stack.Stack, addr tcpip.FullAddress, network tcpip.NetworkProtocolNumber) (*TCPConn, error) {\n+ return DialTCPWithBind(ctx, s, tcpip.FullAddress{} /* localAddr */, addr /* remoteAddr */, network)\n+}\n+\n// A UDPConn is a wrapper around a UDP tcpip.Endpoint that implements\n// net.Conn and net.PacketConn.\ntype UDPConn struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv4.go",
"new_path": "pkg/tcpip/header/ipv4.go",
"diff": "@@ -208,6 +208,15 @@ var IPv4EmptySubnet = func() tcpip.Subnet {\nreturn subnet\n}()\n+// IPv4LoopbackSubnet is the loopback subnet for IPv4.\n+var IPv4LoopbackSubnet = func() tcpip.Subnet {\n+ subnet, err := tcpip.NewSubnet(tcpip.Address(\"\\x7f\\x00\\x00\\x00\"), tcpip.AddressMask(\"\\xff\\x00\\x00\\x00\"))\n+ if err != nil {\n+ panic(err)\n+ }\n+ return subnet\n+}()\n+\n// IPVersion returns the version of IP used in the given packet. It returns -1\n// if the packet is not large enough to contain the version field.\nfunc IPVersion(b []byte) int {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/BUILD",
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "@@ -143,3 +143,25 @@ go_test(\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n],\n)\n+\n+go_test(\n+ name = \"istio_test\",\n+ size = \"small\",\n+ srcs = [\"istio_test.go\"],\n+ deps = [\n+ \"//pkg/context\",\n+ \"//pkg/rand\",\n+ \"//pkg/sync\",\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/adapters/gonet\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/link/loopback\",\n+ \"//pkg/tcpip/link/pipe\",\n+ \"//pkg/tcpip/link/sniffer\",\n+ \"//pkg/tcpip/network/ipv4\",\n+ \"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/testutil\",\n+ \"//pkg/tcpip/transport/tcp\",\n+ \"@com_github_google_go_cmp//cmp:go_default_library\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/tests/integration/istio_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 istio_test\n+\n+import (\n+ \"fmt\"\n+ \"io\"\n+ \"net\"\n+ \"net/http\"\n+ \"strconv\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/rand\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/pipe\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/sniffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n+)\n+\n+// testContext encapsulates the state required to run tests that simulate\n+// an istio like environment.\n+//\n+// A diagram depicting the setup is shown below.\n+// +-----------------------------------------------------------------------+\n+// | +-------------------------------------------------+ |\n+// | + ----------+ | + -----------------+ PROXY +----------+ | |\n+// | | clientEP | | | serverListeningEP|--accepted-> | serverEP |-+ | |\n+// | + ----------+ | + -----------------+ +----------+ | | |\n+// | | -------|-------------+ +----------+ | | |\n+// | | | | | proxyEP |-+ | |\n+// | +-----redirect | +----------+ | |\n+// | + ------------+---|------+---+ |\n+// | | |\n+// | Local Stack. | |\n+// +-------------------------------------------------------|---------------+\n+// |\n+// +-----------------------------------------------------------------------+\n+// | remoteStack | |\n+// | +-------------SYN ---------------| |\n+// | | | |\n+// | +-------------------|--------------------------------|-_---+ |\n+// | | + -----------------+ + ----------+ | | |\n+// | | | remoteListeningEP|--accepted--->| remoteEP |<++ | |\n+// | | + -----------------+ + ----------+ | |\n+// | | Remote HTTP Server | |\n+// | +----------------------------------------------------------+ |\n+// +-----------------------------------------------------------------------+\n+//\n+type testContext struct {\n+ // localServerListener is the listening port for the server which will proxy\n+ // all traffic to the remote EP.\n+ localServerListener *gonet.TCPListener\n+\n+ // remoteListenListener is the remote listening endpoint that will receive\n+ // connections from server.\n+ remoteServerListener *gonet.TCPListener\n+\n+ // localStack is the stack used to create client/server endpoints and\n+ // also the stack on which we install NAT redirect rules.\n+ localStack *stack.Stack\n+\n+ // remoteStack is the stack that represents a *remote* server.\n+ remoteStack *stack.Stack\n+\n+ // defaultResponse is the response served by the HTTP server for all GET\n+ defaultResponse []byte\n+\n+ // requests. wg is used to wait for HTTP server and Proxy to terminate before\n+ // returning from cleanup.\n+ wg sync.WaitGroup\n+}\n+\n+func (ctx *testContext) cleanup() {\n+ ctx.localServerListener.Close()\n+ ctx.localStack.Close()\n+ ctx.remoteServerListener.Close()\n+ ctx.remoteStack.Close()\n+ ctx.wg.Wait()\n+}\n+\n+const (\n+ localServerPort = 8080\n+ remoteServerPort = 9090\n+)\n+\n+var (\n+ localIPv4Addr1 = testutil.MustParse4(\"10.0.0.1\")\n+ localIPv4Addr2 = testutil.MustParse4(\"10.0.0.2\")\n+ loopbackIPv4Addr = testutil.MustParse4(\"127.0.0.1\")\n+ remoteIPv4Addr1 = testutil.MustParse4(\"10.0.0.3\")\n+)\n+\n+func newTestContext(t *testing.T) *testContext {\n+ t.Helper()\n+ localNIC, remoteNIC := pipe.New(\"\" /* linkAddr1 */, \"\" /* linkAddr2 */)\n+\n+ localStack := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ HandleLocal: true,\n+ })\n+\n+ remoteStack := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ HandleLocal: true,\n+ })\n+\n+ // Add loopback NIC. We need a loopback NIC as NAT redirect rule redirect to\n+ // loopback address + specified port.\n+ loopbackNIC := loopback.New()\n+ const loopbackNICID = tcpip.NICID(1)\n+ if err := localStack.CreateNIC(loopbackNICID, sniffer.New(loopbackNIC)); err != nil {\n+ t.Fatalf(\"localStack.CreateNIC(%d, _): %s\", loopbackNICID, err)\n+ }\n+ loopbackAddr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: loopbackIPv4Addr.WithPrefix(),\n+ }\n+ if err := localStack.AddProtocolAddress(loopbackNICID, loopbackAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"localStack.AddProtocolAddress(%d, %+v, {}): %s\", loopbackNICID, loopbackAddr, err)\n+ }\n+\n+ // Create linked NICs that connects the local and remote stack.\n+ const localNICID = tcpip.NICID(2)\n+ const remoteNICID = tcpip.NICID(3)\n+ if err := localStack.CreateNIC(localNICID, sniffer.New(localNIC)); err != nil {\n+ t.Fatalf(\"localStack.CreateNIC(%d, _): %s\", localNICID, err)\n+ }\n+ if err := remoteStack.CreateNIC(remoteNICID, sniffer.New(remoteNIC)); err != nil {\n+ t.Fatalf(\"remoteStack.CreateNIC(%d, _): %s\", remoteNICID, err)\n+ }\n+\n+ for _, addr := range []tcpip.Address{localIPv4Addr1, localIPv4Addr2} {\n+ localProtocolAddr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: addr.WithPrefix(),\n+ }\n+ if err := localStack.AddProtocolAddress(localNICID, localProtocolAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"localStack.AddProtocolAddress(%d, %+v, {}): %s\", localNICID, localProtocolAddr, err)\n+ }\n+ }\n+\n+ remoteProtocolAddr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv4ProtocolNumber,\n+ AddressWithPrefix: remoteIPv4Addr1.WithPrefix(),\n+ }\n+ if err := remoteStack.AddProtocolAddress(remoteNICID, remoteProtocolAddr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"remoteStack.AddProtocolAddress(%d, %+v, {}): %s\", remoteNICID, remoteProtocolAddr, err)\n+ }\n+\n+ // Setup route table for local and remote stacks.\n+ localStack.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4LoopbackSubnet,\n+ NIC: loopbackNICID,\n+ },\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: localNICID,\n+ },\n+ })\n+ remoteStack.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: header.IPv4EmptySubnet,\n+ NIC: remoteNICID,\n+ },\n+ })\n+\n+ const netProto = ipv4.ProtocolNumber\n+ localServerAddress := tcpip.FullAddress{\n+ Port: localServerPort,\n+ }\n+\n+ localServerListener, err := gonet.ListenTCP(localStack, localServerAddress, netProto)\n+ if err != nil {\n+ t.Fatalf(\"gonet.ListenTCP(_, %+v, %d) = %s\", localServerAddress, netProto, err)\n+ }\n+\n+ remoteServerAddress := tcpip.FullAddress{\n+ Port: remoteServerPort,\n+ }\n+ remoteServerListener, err := gonet.ListenTCP(remoteStack, remoteServerAddress, netProto)\n+ if err != nil {\n+ t.Fatalf(\"gonet.ListenTCP(_, %+v, %d) = %s\", remoteServerAddress, netProto, err)\n+ }\n+\n+ // Initialize a random default response served by the HTTP server.\n+ defaultResponse := make([]byte, 512<<10)\n+ if _, err := rand.Read(defaultResponse); err != nil {\n+ t.Fatalf(\"rand.Read(buf) failed: %s\", err)\n+ }\n+\n+ tc := &testContext{\n+ localServerListener: localServerListener,\n+ remoteServerListener: remoteServerListener,\n+ localStack: localStack,\n+ remoteStack: remoteStack,\n+ defaultResponse: defaultResponse,\n+ }\n+\n+ tc.startServers(t)\n+ return tc\n+}\n+\n+func (ctx *testContext) startServers(t *testing.T) {\n+ ctx.wg.Add(1)\n+ go func() {\n+ defer ctx.wg.Done()\n+ ctx.startHTTPServer()\n+ }()\n+ ctx.wg.Add(1)\n+ go func() {\n+ defer ctx.wg.Done()\n+ ctx.startTCPProxyServer(t)\n+ }()\n+}\n+\n+func (ctx *testContext) startTCPProxyServer(t *testing.T) {\n+ t.Helper()\n+ for {\n+ conn, err := ctx.localServerListener.Accept()\n+ if err != nil {\n+ t.Logf(\"terminating local proxy server: %s\", err)\n+ return\n+ }\n+ // Start a goroutine to handle this inbound connection.\n+ go func() {\n+ remoteServerAddr := tcpip.FullAddress{\n+ Addr: remoteIPv4Addr1,\n+ Port: remoteServerPort,\n+ }\n+ localServerAddr := tcpip.FullAddress{\n+ Addr: localIPv4Addr2,\n+ }\n+ serverConn, err := gonet.DialTCPWithBind(context.Background(), ctx.localStack, localServerAddr, remoteServerAddr, ipv4.ProtocolNumber)\n+ if err != nil {\n+ t.Logf(\"gonet.DialTCP(_, %+v, %d) = %s\", remoteServerAddr, ipv4.ProtocolNumber, err)\n+ return\n+ }\n+ proxy(conn, serverConn)\n+ t.Logf(\"proxying completed\")\n+ }()\n+ }\n+}\n+\n+// proxy transparently proxies the TCP payload from conn1 to conn2\n+// and vice versa.\n+func proxy(conn1, conn2 net.Conn) {\n+ var wg sync.WaitGroup\n+ wg.Add(1)\n+ go func() {\n+ io.Copy(conn2, conn1)\n+ conn1.Close()\n+ conn2.Close()\n+ }()\n+ wg.Add(1)\n+ go func() {\n+ io.Copy(conn1, conn2)\n+ conn1.Close()\n+ conn2.Close()\n+ }()\n+ wg.Wait()\n+}\n+\n+func (ctx *testContext) startHTTPServer() {\n+ handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n+ w.Write([]byte(ctx.defaultResponse))\n+ })\n+ s := &http.Server{\n+ Handler: handlerFunc,\n+ }\n+ s.Serve(ctx.remoteServerListener)\n+}\n+\n+func TestOutboundNATRedirect(t *testing.T) {\n+ ctx := newTestContext(t)\n+ defer ctx.cleanup()\n+\n+ // Install an IPTable rule to redirect all TCP traffic with the sourceIP of\n+ // localIPv4Addr1 to the tcp proxy port.\n+ ipt := ctx.localStack.IPTables()\n+ tbl := ipt.GetTable(stack.NATID, false /* ipv6 */)\n+ ruleIdx := tbl.BuiltinChains[stack.Output]\n+ tbl.Rules[ruleIdx].Filter = stack.IPHeaderFilter{\n+ Protocol: tcp.ProtocolNumber,\n+ CheckProtocol: true,\n+ Src: localIPv4Addr1,\n+ SrcMask: tcpip.Address(\"\\xff\\xff\\xff\\xff\"),\n+ }\n+ tbl.Rules[ruleIdx].Target = &stack.RedirectTarget{\n+ Port: localServerPort,\n+ NetworkProtocol: ipv4.ProtocolNumber,\n+ }\n+ tbl.Rules[ruleIdx+1].Target = &stack.AcceptTarget{}\n+ if err := ipt.ReplaceTable(stack.NATID, tbl, false /* ipv6 */); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, false): %s\", stack.NATID, err)\n+ }\n+\n+ dialFunc := func(protocol, address string) (net.Conn, error) {\n+ host, port, err := net.SplitHostPort(address)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"unable to parse address: %s, err: %s\", address, err)\n+ }\n+\n+ remoteServerIP := net.ParseIP(host)\n+ remoteServerPort, err := strconv.Atoi(port)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"unable to parse port from string %s, err: %s\", port, err)\n+ }\n+ remoteAddress := tcpip.FullAddress{\n+ Addr: tcpip.Address(remoteServerIP.To4()),\n+ Port: uint16(remoteServerPort),\n+ }\n+\n+ // Dial with an explicit source address bound so that the redirect rule will\n+ // be able to correctly redirect these packets.\n+ localAddr := tcpip.FullAddress{Addr: localIPv4Addr1}\n+ return gonet.DialTCPWithBind(context.Background(), ctx.localStack, localAddr, remoteAddress, ipv4.ProtocolNumber)\n+ }\n+\n+ httpClient := &http.Client{\n+ Transport: &http.Transport{\n+ Dial: dialFunc,\n+ },\n+ }\n+\n+ serverURL := fmt.Sprintf(\"http://[%s]:%d/\", net.IP(remoteIPv4Addr1), remoteServerPort)\n+ response, err := httpClient.Get(serverURL)\n+ if err != nil {\n+ t.Fatalf(\"httpClient.Get(\\\"/\\\") failed: %s\", err)\n+ }\n+ if got, want := response.StatusCode, http.StatusOK; got != want {\n+ t.Fatalf(\"unexpected status code got: %d, want: %d\", got, want)\n+ }\n+ body, err := io.ReadAll(response.Body)\n+ if err != nil {\n+ t.Fatalf(\"io.ReadAll(response.Body) failed: %s\", err)\n+ }\n+ response.Body.Close()\n+ if diff := cmp.Diff(body, ctx.defaultResponse); diff != \"\" {\n+ t.Fatalf(\"unexpected response (-want +got): \\n %s\", diff)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add an integration test for istio like redirect.
Updates #6441,#6317
PiperOrigin-RevId: 404872327 |
259,875 | 23.10.2021 15:38:28 | 25,200 | c0dfa0e845b3571550e84bdebb411b119086b4aa | initialize hostFeatureSet from init function | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid.go",
"new_path": "pkg/cpuid/cpuid.go",
"diff": "@@ -43,7 +43,7 @@ func HostFeatureSet() *FeatureSet {\nreturn hostFeatureSet\n}\n-var hostFeatureSet = getHostFeatureSet()\n+var hostFeatureSet *FeatureSet\n// ErrIncompatible is returned by FeatureSet.HostCompatible if fs is not a\n// subset of the host feature set.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_x86.go",
"new_path": "pkg/cpuid/cpuid_x86.go",
"diff": "@@ -1109,4 +1109,5 @@ func initFeaturesFromString() {\nfunc init() {\ninitCPUFreq()\ninitFeaturesFromString()\n+ hostFeatureSet = getHostFeatureSet()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | initialize hostFeatureSet from init function |
259,853 | 25.10.2021 13:29:21 | 25,200 | a8a66d899fe075c2a23b21edd0aab4e658ad7e81 | Deflake the fcntl test
Wait when a child process will start to measure a blocking time more precise. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/fcntl.cc",
"new_path": "test/syscalls/linux/fcntl.cc",
"diff": "@@ -175,12 +175,19 @@ class FcntlSignalTest : public ::testing::Test {\nnamespace {\nPosixErrorOr<Cleanup> SubprocessLock(std::string const& path, bool for_write,\n- bool blocking, bool retry_eintr, int fd,\n- off_t start, off_t length, pid_t* child) {\n+ bool blocking, bool retry_eintr,\n+ int* socket_pair, off_t start,\n+ off_t length, pid_t* child) {\nstd::vector<std::string> args = {\n- \"/proc/self/exe\", \"--child_set_lock_on\", path,\n- \"--child_set_lock_start\", absl::StrCat(start), \"--child_set_lock_len\",\n- absl::StrCat(length), \"--socket_fd\", absl::StrCat(fd)};\n+ \"/proc/self/exe\",\n+ \"--child_set_lock_on\",\n+ path,\n+ \"--child_set_lock_start\",\n+ absl::StrCat(start),\n+ \"--child_set_lock_len\",\n+ absl::StrCat(length),\n+ \"--socket_fd\",\n+ absl::StrCat(socket_pair ? socket_pair[1] : -1)};\nif (for_write) {\nargs.push_back(\"--child_set_lock_write\");\n@@ -204,6 +211,12 @@ PosixErrorOr<Cleanup> SubprocessLock(std::string const& path, bool for_write,\nreturn PosixError(execve_errno, \"execve\");\n}\n+ if (socket_pair) {\n+ // Wait for when a chill will start.\n+ char c;\n+ EXPECT_THAT(ReadFd(socket_pair[0], reinterpret_cast<void*>(&c), sizeof(c)),\n+ SyscallSucceedsWithValue(sizeof(c)));\n+ }\nreturn std::move(cleanup);\n}\n@@ -540,10 +553,10 @@ TEST_F(FcntlLockTest, SetReadLockMultiProc) {\n// spawn a child process to take a read lock on the same file.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), false /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), false /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -568,10 +581,10 @@ TEST_F(FcntlLockTest, SetReadThenWriteLockMultiProc) {\n// with EAGAIN. It's important that we keep the fd above open so that\n// that the other process will contend with the lock.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), true /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), true /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -584,10 +597,10 @@ TEST_F(FcntlLockTest, SetReadThenWriteLockMultiProc) {\n// Assert that another process can now acquire the lock.\nchild_pid = 0;\n- auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), true /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), true /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n<< \"Exited with code: \" << status;\n@@ -612,10 +625,10 @@ TEST_F(FcntlLockTest, SetWriteThenReadLockMultiProc) {\n// Same as SetReadThenWriteLockMultiProc.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), false /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), false /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -627,10 +640,10 @@ TEST_F(FcntlLockTest, SetWriteThenReadLockMultiProc) {\n// Same as SetReadThenWriteLockMultiProc.\nchild_pid = 0;\n- auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), false /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), false /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n<< \"Exited with code: \" << status;\n@@ -654,10 +667,10 @@ TEST_F(FcntlLockTest, SetWriteLockMultiProc) {\n// Same as SetReadWriteLockMultiProc.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), true /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), true /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == EAGAIN)\n@@ -666,10 +679,10 @@ TEST_F(FcntlLockTest, SetWriteLockMultiProc) {\nfd.reset(); // Close the FD.\n// Same as SetReadWriteLockMultiProc.\nchild_pid = 0;\n- auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), true /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), true /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n<< \"Exited with code: \" << status;\n@@ -694,7 +707,7 @@ TEST_F(FcntlLockTest, SetLockIsRegional) {\nauto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\nSubprocessLock(file.path(), true /* write lock */,\nfalse /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_len, 0, &child_pid));\n+ nullptr /* no socket fd */, fl.l_len, 0, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n@@ -723,10 +736,10 @@ TEST_F(FcntlLockTest, SetLockUpgradeDowngrade) {\n// Same as SetReadWriteLockMultiProc.,\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), false /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), false /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -739,10 +752,10 @@ TEST_F(FcntlLockTest, SetLockUpgradeDowngrade) {\n// Do the same stint as before, but this time it should succeed.\nchild_pid = 0;\n- auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), false /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), false /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n@@ -774,10 +787,10 @@ TEST_F(FcntlLockTest, SetLockDroppedOnClose) {\n// Expect to be able to get the lock, given that the close above dropped it.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n- SubprocessLock(file.path(), true /* write lock */,\n- false /* nonblocking */, false /* no eintr retry */,\n- -1 /* no socket fd */, fl.l_start, fl.l_len, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n+ file.path(), true /* write lock */, false /* nonblocking */,\n+ false /* no eintr retry */, nullptr /* no socket fd */, fl.l_start,\n+ fl.l_len, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -811,9 +824,10 @@ TEST_F(FcntlLockTest, SetLockUnlock) {\n// Another process should fail to take a read lock on the entire file\n// due to the regional write lock.\npid_t child_pid = 0;\n- auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n- file.path(), false /* write lock */, false /* nonblocking */,\n- false /* no eintr retry */, -1 /* no socket fd */, 0, 0, &child_pid));\n+ auto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\n+ SubprocessLock(file.path(), false /* write lock */,\n+ false /* nonblocking */, false /* no eintr retry */,\n+ nullptr /* no socket fd */, 0, 0, &child_pid));\nint status = 0;\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\n@@ -827,9 +841,10 @@ TEST_F(FcntlLockTest, SetLockUnlock) {\n// Another process should now succeed to get a read lock on the entire file.\nchild_pid = 0;\n- auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\n- file.path(), false /* write lock */, false /* nonblocking */,\n- false /* no eintr retry */, -1 /* no socket fd */, 0, 0, &child_pid));\n+ auto cleanup2 = ASSERT_NO_ERRNO_AND_VALUE(\n+ SubprocessLock(file.path(), false /* write lock */,\n+ false /* nonblocking */, false /* no eintr retry */,\n+ nullptr /* no socket fd */, 0, 0, &child_pid));\nASSERT_THAT(RetryEINTR(waitpid)(child_pid, &status, 0), SyscallSucceeds());\nEXPECT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0)\n<< \"Exited with code: \" << status;\n@@ -860,7 +875,7 @@ TEST_F(FcntlLockTest, SetLockAcrossRename) {\npid_t child_pid = 0;\nauto cleanup = ASSERT_NO_ERRNO_AND_VALUE(\nSubprocessLock(newpath, false /* write lock */, false /* nonblocking */,\n- false /* no eintr retry */, -1 /* no socket fd */,\n+ false /* no eintr retry */, nullptr /* no socket fd */,\nfl.l_start, fl.l_len, &child_pid));\nint status = 0;\n@@ -898,7 +913,7 @@ TEST_F(FcntlLockTest, SetWriteLockThenBlockingWriteLock) {\npid_t child_pid = 0;\nauto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\nfile.path(), true /* write lock */, true /* Blocking Lock */,\n- true /* Retry on EINTR */, fds_[1] /* Socket fd for timing information */,\n+ true /* Retry on EINTR */, fds_ /* Socket fd for timing information */,\nfl.l_start, fl.l_len, &child_pid));\n// We will wait kHoldLockForSec before we release our lock allowing the\n@@ -950,7 +965,7 @@ TEST_F(FcntlLockTest, SetReadLockThenBlockingWriteLock) {\npid_t child_pid = 0;\nauto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\nfile.path(), true /* write lock */, true /* Blocking Lock */,\n- true /* Retry on EINTR */, fds_[1] /* Socket fd for timing information */,\n+ true /* Retry on EINTR */, fds_ /* Socket fd for timing information */,\nfl.l_start, fl.l_len, &child_pid));\n// We will wait kHoldLockForSec before we release our lock allowing the\n@@ -1003,7 +1018,7 @@ TEST_F(FcntlLockTest, SetWriteLockThenBlockingReadLock) {\npid_t child_pid = 0;\nauto cleanup = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\nfile.path(), false /* read lock */, true /* Blocking Lock */,\n- true /* Retry on EINTR */, fds_[1] /* Socket fd for timing information */,\n+ true /* Retry on EINTR */, fds_ /* Socket fd for timing information */,\nfl.l_start, fl.l_len, &child_pid));\n// We will wait kHoldLockForSec before we release our lock allowing the\n@@ -1054,8 +1069,8 @@ TEST_F(FcntlLockTest, SetReadLockThenBlockingReadLock) {\npid_t child_pid = 0;\nauto sp = ASSERT_NO_ERRNO_AND_VALUE(SubprocessLock(\nfile.path(), false /* read lock */, true /* Blocking Lock */,\n- true /* Retry on EINTR */, -1 /* No fd, should not block */, fl.l_start,\n- fl.l_len, &child_pid));\n+ true /* Retry on EINTR */, nullptr /* No fd, should not block */,\n+ fl.l_start, fl.l_len, &child_pid));\n// We never release the lock and the subprocess should still obtain it without\n// blocking for any period of time.\n@@ -1958,6 +1973,12 @@ int set_lock() {\nfl.l_start = absl::GetFlag(FLAGS_child_set_lock_start);\nfl.l_len = absl::GetFlag(FLAGS_child_set_lock_len);\n+ if (socket_fd != -1) {\n+ // Send signal to the parent.\n+ char c = 0;\n+ gvisor::testing::WriteFd(socket_fd, reinterpret_cast<void*>(&c),\n+ sizeof(c));\n+ }\n// Test the fcntl.\nint err = 0;\nint ret = 0;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake the fcntl test
Wait when a child process will start to measure a blocking time more precise.
PiperOrigin-RevId: 405478376 |
259,907 | 25.10.2021 13:43:37 | 25,200 | 4d07fc952d6bb5aa70b4bc9ff5e6457987f1721c | Do not leak non-permission mode bits in mq_open(2).
As caught by syzkaller, we were leaking non-permission bits while passing the
user generated mode. DynamicBytesFile panics in this case.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/mq/mq.go",
"new_path": "pkg/sentry/kernel/mq/mq.go",
"diff": "@@ -122,7 +122,7 @@ type OpenOpts struct {\n// FindOrCreate creates a new POSIX message queue or opens an existing queue.\n// See mq_open(2).\n-func (r *Registry) FindOrCreate(ctx context.Context, opts OpenOpts, perm linux.FileMode, attr *linux.MqAttr) (*vfs.FileDescription, error) {\n+func (r *Registry) FindOrCreate(ctx context.Context, opts OpenOpts, mode linux.FileMode, attr *linux.MqAttr) (*vfs.FileDescription, error) {\n// mq_overview(7) mentions that: \"Each message queue is identified by a name\n// of the form '/somename'\", but the mq_open(3) man pages mention:\n// \"The mq_open() library function is implemented on top of a system call\n@@ -182,11 +182,11 @@ func (r *Registry) FindOrCreate(ctx context.Context, opts OpenOpts, perm linux.F\nreturn nil, linuxerr.ENOENT\n}\n- q, err := r.newQueueLocked(auth.CredentialsFromContext(ctx), fs.FileOwnerFromContext(ctx), fs.FilePermsFromMode(perm), attr)\n+ q, err := r.newQueueLocked(auth.CredentialsFromContext(ctx), fs.FileOwnerFromContext(ctx), fs.FilePermsFromMode(mode), attr)\nif err != nil {\nreturn nil, err\n}\n- return r.impl.New(ctx, opts.Name, q, opts.Access, opts.Block, perm, flags)\n+ return r.impl.New(ctx, opts.Name, q, opts.Access, opts.Block, mode.Permissions(), flags)\n}\n// newQueueLocked creates a new queue using the given attributes. If attr is nil\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mq.cc",
"new_path": "test/syscalls/linux/mq.cc",
"diff": "@@ -34,8 +34,6 @@ namespace gvisor {\nnamespace testing {\nnamespace {\n-using ::testing::_;\n-\n// PosixQueue is a RAII class used to automatically clean POSIX message queues.\nclass PosixQueue {\npublic:\n@@ -124,8 +122,13 @@ PosixError MqClose(mqd_t fd) {\n// Test simple opening and closing of a message queue.\nTEST(MqTest, Open) {\nSKIP_IF(IsRunningWithVFS1());\n- EXPECT_THAT(MqOpen(O_RDWR | O_CREAT | O_EXCL, 0777, nullptr),\n- IsPosixErrorOkAndHolds(_));\n+ ASSERT_NO_ERRNO(MqOpen(O_RDWR | O_CREAT | O_EXCL, 0777, nullptr));\n+}\n+\n+TEST(MqTest, ModeWithFileType) {\n+ SKIP_IF(IsRunningWithVFS1());\n+ // S_IFIFO should be ignored.\n+ ASSERT_NO_ERRNO(MqOpen(O_RDWR | O_CREAT | O_EXCL, 0777 | S_IFIFO, nullptr));\n}\n// Test mq_open(2) after mq_unlink(2).\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not leak non-permission mode bits in mq_open(2).
As caught by syzkaller, we were leaking non-permission bits while passing the
user generated mode. DynamicBytesFile panics in this case.
Reported-by: [email protected]
PiperOrigin-RevId: 405481392 |
259,885 | 26.10.2021 00:19:54 | 25,200 | 12480f1c4b49234a3761856e40d4d122695b610f | Ensure statfs::f_namelen is set by VFS2 gofer statfs/fstatfs.
VFS1 discards the value of f_namelen returned by the filesystem and returns
NAME_MAX unconditionally instead, so it doesn't run into this. Also set
f_frsize for completeness. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -1696,7 +1696,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nif err := d.controlFDLisa.StatFSTo(ctx, &statFS); err != nil {\nreturn linux.Statfs{}, err\n}\n- if statFS.NameLength > maxFilenameLen {\n+ if statFS.NameLength == 0 || statFS.NameLength > maxFilenameLen {\nstatFS.NameLength = maxFilenameLen\n}\nreturn linux.Statfs{\n@@ -1705,6 +1705,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\n// something completely random, use a standard value.\nType: linux.V9FS_MAGIC,\nBlockSize: statFS.BlockSize,\n+ FragmentSize: statFS.BlockSize,\nBlocks: statFS.Blocks,\nBlocksFree: statFS.BlocksFree,\nBlocksAvailable: statFS.BlocksAvailable,\n@@ -1718,7 +1719,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nreturn linux.Statfs{}, err\n}\nnameLen := uint64(fsstat.NameLength)\n- if nameLen > maxFilenameLen {\n+ if nameLen == 0 || nameLen > maxFilenameLen {\nnameLen = maxFilenameLen\n}\nreturn linux.Statfs{\n@@ -1727,6 +1728,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\n// something completely random, use a standard value.\nType: linux.V9FS_MAGIC,\nBlockSize: int64(fsstat.BlockSize),\n+ FragmentSize: int64(fsstat.BlockSize),\nBlocks: fsstat.Blocks,\nBlocksFree: fsstat.BlocksFree,\nBlocksAvailable: fsstat.BlocksAvailable,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/statfs.cc",
"new_path": "test/syscalls/linux/statfs.cc",
"diff": "@@ -34,17 +34,19 @@ TEST(StatfsTest, CannotStatBadPath) {\nEXPECT_THAT(statfs(temp_file.c_str(), &st), SyscallFailsWithErrno(ENOENT));\n}\n-TEST(StatfsTest, InternalTmpfs) {\n+TEST(StatfsTest, TempPath) {\nauto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nstruct statfs st;\nEXPECT_THAT(statfs(temp_file.path().c_str(), &st), SyscallSucceeds());\n+ EXPECT_GT(st.f_namelen, 0);\n}\nTEST(StatfsTest, InternalDevShm) {\nstruct statfs st;\nEXPECT_THAT(statfs(\"/dev/shm\", &st), SyscallSucceeds());\n+ EXPECT_GT(st.f_namelen, 0);\n// This assumes that /dev/shm is tmpfs.\n// Note: We could be an overlay on some configurations.\nEXPECT_TRUE(st.f_type == TMPFS_MAGIC || st.f_type == OVERLAYFS_SUPER_MAGIC);\n@@ -55,13 +57,14 @@ TEST(FstatfsTest, CannotStatBadFd) {\nEXPECT_THAT(fstatfs(-1, &st), SyscallFailsWithErrno(EBADF));\n}\n-TEST(FstatfsTest, InternalTmpfs) {\n+TEST(FstatfsTest, TempPath) {\nauto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY));\nstruct statfs st;\nEXPECT_THAT(fstatfs(fd.get(), &st), SyscallSucceeds());\n+ EXPECT_GT(st.f_namelen, 0);\n}\nTEST(FstatfsTest, CanStatFileWithOpath) {\n@@ -81,6 +84,10 @@ TEST(FstatfsTest, InternalDevShm) {\nstruct statfs st;\nEXPECT_THAT(fstatfs(fd.get(), &st), SyscallSucceeds());\n+ EXPECT_GT(st.f_namelen, 0);\n+ // This assumes that /dev/shm is tmpfs.\n+ // Note: We could be an overlay on some configurations.\n+ EXPECT_TRUE(st.f_type == TMPFS_MAGIC || st.f_type == OVERLAYFS_SUPER_MAGIC);\n}\n} // namespace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure statfs::f_namelen is set by VFS2 gofer statfs/fstatfs.
VFS1 discards the value of f_namelen returned by the filesystem and returns
NAME_MAX unconditionally instead, so it doesn't run into this. Also set
f_frsize for completeness.
PiperOrigin-RevId: 405579707 |
259,898 | 26.10.2021 10:11:19 | 25,200 | c8d835470037be9efcad13091fb6d173c68cc0ca | Remove superfluous SO_RCVBUFFORCE | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/rawsockets.go",
"new_path": "test/packetimpact/testbench/rawsockets.go",
"diff": "@@ -58,9 +58,6 @@ func (n *DUTTestNet) NewSniffer(t *testing.T) (Sniffer, error) {\nif err := unix.Bind(snifferFd, &sa); err != nil {\nreturn Sniffer{}, err\n}\n- if err := unix.SetsockoptInt(snifferFd, unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, 1); err != nil {\n- t.Fatalf(\"can't set sockopt SO_RCVBUFFORCE to 1: %s\", err)\n- }\nif err := unix.SetsockoptInt(snifferFd, unix.SOL_SOCKET, unix.SO_RCVBUF, 1e7); err != nil {\nt.Fatalf(\"can't setsockopt SO_RCVBUF to 10M: %s\", err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove superfluous SO_RCVBUFFORCE
PiperOrigin-RevId: 405674425 |
260,001 | 26.10.2021 11:48:33 | 25,200 | 8b2e8caad400fd3e7d3e4e235d26dd2d556bf65c | Move attestation definitions to standalone package | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/abi/attestation/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"attestation\",\n+ srcs = [\"attestation.go\"],\n+ visibility = [\"//visibility:public\"],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/abi/attestation/attestation.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 attestation includes definitions needed for gVisor attestation.\n+package attestation\n+\n+// Attestation ioctls.\n+const (\n+ SIGN_ATTESTATION_REPORT = 0\n+)\n+\n+// SizeOfQuoteInputData is the number of bytes in the input data of ioctl call\n+// to get quote.\n+const SizeOfQuoteInputData = 64\n+\n+// SignReport is a struct that gets signed quote from input data. The\n+// serialized quote is copied to buf.\n+// size is an input that specifies the size of buf. When returned, it's updated\n+// to the size of quote.\n+type SignReport struct {\n+ data [64]byte\n+ size uint32\n+ buf []byte\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/ioctl.go",
"new_path": "pkg/abi/linux/ioctl.go",
"diff": "@@ -170,22 +170,3 @@ const (\nKCOV_MODE_TRACE_PC = 2\nKCOV_MODE_TRACE_CMP = 3\n)\n-\n-// Attestation ioctls.\n-var (\n- SIGN_ATTESTATION_REPORT = IOC(_IOC_READ, 's', 1, 65)\n-)\n-\n-// SizeOfQuoteInputData is the number of bytes in the input data of ioctl call\n-// to get quote.\n-const SizeOfQuoteInputData = 64\n-\n-// SignReport is a struct that gets signed quote from input data. The\n-// serialized quote is copied to buf.\n-// size is an input that specifies the size of buf. When returned, it's updated\n-// to the size of quote.\n-type SignReport struct {\n- data [64]byte\n- size uint32\n- buf []byte\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move attestation definitions to standalone package
PiperOrigin-RevId: 405698863 |
259,907 | 26.10.2021 11:56:09 | 25,200 | 763d7e6e396d8d4c67d650e02bd2350b22606ada | Obtain ref on root dentry in mqfs.GetFilesystem.
As documented in FilesystemType.GetFilesystem, a reference should be taken on
the returned dentry and filesystem by GetFilesystem implementation. mqfs did
not do that.
Additionally cleanup and clarify ref counting of dentry, filesystem and mount
in mqfs.
Reported-by:
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/mqfs/mqfs.go",
"new_path": "pkg/sentry/fsimpl/mqfs/mqfs.go",
"diff": "@@ -75,6 +75,7 @@ func (ft FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualF\nimpl.fs.MaxCachedDentries = maxCachedDentries\nimpl.fs.VFSFilesystem().IncRef()\n+ impl.root.IncRef()\nreturn impl.fs.VFSFilesystem(), impl.root.VFSDentry(), nil\n}\n@@ -100,10 +101,6 @@ func maxCachedDentries(ctx context.Context, mopts map[string]string) (_ uint64,\ntype filesystem struct {\nkernfs.Filesystem\ndevMinor uint32\n-\n- // root is the filesystem's root dentry. Since we take a reference on it in\n- // GetFilesystem, we should release it when the fs is released.\n- root *kernfs.Dentry\n}\n// Release implements vfs.FilesystemImpl.Release.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/mqfs/registry.go",
"new_path": "pkg/sentry/fsimpl/mqfs/registry.go",
"diff": "@@ -57,16 +57,19 @@ func NewRegistryImpl(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *\nreturn nil, err\n}\n- var dentry kernfs.Dentry\nfs := &filesystem{\ndevMinor: devMinor,\n- root: &dentry,\n}\nfs.VFSFilesystem().Init(vfsObj, &FilesystemType{}, fs)\nvfsfs := fs.VFSFilesystem()\n+ // NewDisconnectedMount will obtain a ref on dentry and vfsfs which is\n+ // transferred to mount. vfsfs was initiated with 1 ref already. So get rid\n+ // of the extra ref.\n+ defer vfsfs.DecRef(ctx)\n+ // dentry is initialized with 1 ref which is transferred to fs.\n+ var dentry kernfs.Dentry\ndentry.InitRoot(&fs.Filesystem, fs.newRootInode(ctx, creds))\n- defer vfsfs.DecRef(ctx) // NewDisconnectedMount will obtain a ref on success.\nmount, err := vfsObj.NewDisconnectedMount(vfsfs, dentry.VFSDentry(), &vfs.MountOptions{})\nif err != nil {\n@@ -82,7 +85,7 @@ func NewRegistryImpl(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *\n// Get implements mq.RegistryImpl.Get.\nfunc (r *RegistryImpl) Get(ctx context.Context, name string, access mq.AccessType, block bool, flags uint32) (*vfs.FileDescription, bool, error) {\n- inode, err := r.lookup(ctx, name)\n+ inode, err := r.root.Inode().(*rootInode).Lookup(ctx, name)\nif err != nil {\nreturn nil, false, nil\n}\n@@ -120,7 +123,7 @@ func (r *RegistryImpl) Unlink(ctx context.Context, name string) error {\n}\nroot := r.root.Inode().(*rootInode)\n- inode, err := r.lookup(ctx, name)\n+ inode, err := root.Lookup(ctx, name)\nif err != nil {\nreturn err\n}\n@@ -133,16 +136,6 @@ func (r *RegistryImpl) Destroy(ctx context.Context) {\nr.mount.DecRef(ctx)\n}\n-// lookup retreives a kernfs.Inode using a name.\n-func (r *RegistryImpl) lookup(ctx context.Context, name string) (kernfs.Inode, error) {\n- inode := r.root.Inode().(*rootInode)\n- lookup, err := inode.Lookup(ctx, name)\n- if err != nil {\n- return nil, err\n- }\n- return lookup, nil\n-}\n-\n// newFD returns a new file description created using the given queue and inode.\nfunc (r *RegistryImpl) newFD(q *mq.Queue, inode *queueInode, access mq.AccessType, block bool, flags uint32) (*vfs.FileDescription, error) {\nview, err := mq.NewView(q, access, block)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/mqfs/root.go",
"new_path": "pkg/sentry/fsimpl/mqfs/root.go",
"diff": "@@ -34,7 +34,6 @@ type rootInode struct {\nkernfs.InodeNotSymlink\nkernfs.InodeTemporary\nkernfs.OrderedChildren\n- implStatFS\nlocks vfs.FileLocks\n}\n@@ -77,13 +76,7 @@ func (*rootInode) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, v\nreturn linuxerr.EPERM\n}\n-// implStatFS provides an implementation of kernfs.Inode.StatFS for message\n-// queues to be embedded in inodes.\n-//\n-// +stateify savable\n-type implStatFS struct{}\n-\n// StatFS implements kernfs.Inode.StatFS.\n-func (*implStatFS) StatFS(context.Context, *vfs.Filesystem) (linux.Statfs, error) {\n+func (*rootInode) StatFS(context.Context, *vfs.Filesystem) (linux.Statfs, error) {\nreturn vfs.GenericStatFS(linux.MQUEUE_MAGIC), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem_type.go",
"new_path": "pkg/sentry/vfs/filesystem_type.go",
"diff": "@@ -28,7 +28,7 @@ import (\ntype FilesystemType interface {\n// GetFilesystem returns a Filesystem configured by the given options,\n// along with its mount root. A reference is taken on the returned\n- // Filesystem and Dentry.\n+ // Filesystem and Dentry whose ownership is transferred to the caller.\nGetFilesystem(ctx context.Context, vfsObj *VirtualFilesystem, creds *auth.Credentials, source string, opts GetFilesystemOptions) (*Filesystem, *Dentry, error)\n// Name returns the name of this FilesystemType.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -4209,6 +4209,7 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\"//test/util:capability_util\",\n+ \"//test/util:cleanup\",\n\"//test/util:fs_util\",\n\"//test/util:mount_util\",\n\"//test/util:posix_error\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mq.cc",
"new_path": "test/syscalls/linux/mq.cc",
"diff": "#include <string>\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/mount_util.h\"\n#include \"test/util/posix_error.h\"\n@@ -286,18 +287,25 @@ TEST(MqTest, Mount) {\nTEST(MqTest, MountSeveral) {\nSKIP_IF(IsRunningWithVFS1() ||\n!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+ constexpr int numMounts = 3;\n+ // mountDirs should outlive mountCUs and queue so that its destructor succeeds\n+ // in unlinking the mountpoints and does not interfere with queue destruction.\n+ testing::TempPath mountDirs[numMounts];\n+ testing::Cleanup mountCUs[numMounts];\nPosixQueue queue = ASSERT_NO_ERRNO_AND_VALUE(\nMqOpen(O_RDWR | O_CREAT | O_EXCL, 0777, nullptr));\n- auto const dir1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- // Assign the pointer so it doesn't get destroyed before the second mount is\n- // created.\n- auto mnt =\n- ASSERT_NO_ERRNO_AND_VALUE(Mount(\"none\", dir1.path(), \"mqueue\", 0, \"\", 0));\n+ for (int i = 0; i < numMounts; ++i) {\n+ mountDirs[i] = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ mountCUs[i] = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"none\", mountDirs[i].path(), \"mqueue\", 0, \"\", 0));\n+ }\n- auto const dir2 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- ASSERT_NO_ERRNO(Mount(\"none\", dir2.path(), \"mqueue\", 0, \"\", 0));\n+ // Ensure that queue is visible from all mounts.\n+ for (int i = 0; i < numMounts; ++i) {\n+ ASSERT_NO_ERRNO(Stat(JoinPath(mountDirs[i].path(), queue.name())));\n+ }\n}\n// Test mounting mqueue and opening a queue as normal file.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Obtain ref on root dentry in mqfs.GetFilesystem.
As documented in FilesystemType.GetFilesystem, a reference should be taken on
the returned dentry and filesystem by GetFilesystem implementation. mqfs did
not do that.
Additionally cleanup and clarify ref counting of dentry, filesystem and mount
in mqfs.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 405700565 |
260,004 | 26.10.2021 12:37:43 | 25,200 | 07b22740a11632c0641657cc4dd145bd0d1e5afb | Run packet socket tests on Fuchsia | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -94,7 +94,9 @@ TEST_P(PacketSocketTest, GetSockName) {\nEq(sizeof(addr) - sizeof(addr.sll_addr))));\nEXPECT_EQ(addr.sll_family, AF_PACKET);\nEXPECT_EQ(addr.sll_ifindex, 0);\n- if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {\n+\n+ if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&\n+ GvisorPlatform() != Platform::kFuchsia) {\n// TODO(https://gvisor.dev/issue/6530): Do not assume all interfaces have\n// an ethernet address.\nEXPECT_EQ(addr.sll_halen, ETH_ALEN);\n@@ -130,7 +132,8 @@ TEST_P(PacketSocketTest, GetSockName) {\nEXPECT_EQ(addr.sll_addr[i], 0) << \"byte mismatch @ idx = \" << i;\n}\nEXPECT_EQ(ntohs(addr.sll_protocol), htons(addr.sll_protocol));\n- if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {\n+ if (IsRunningOnGvisor() && !IsRunningWithHostinet() &&\n+ GvisorPlatform() != Platform::kFuchsia) {\n// TODO(https://gvisor.dev/issue/6621): Support populating sll_hatype.\nEXPECT_EQ(addr.sll_hatype, 0);\n} else {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run packet socket tests on Fuchsia
Bug: https://fxbug.dev/81592
PiperOrigin-RevId: 405710156 |
259,853 | 26.10.2021 15:20:07 | 25,200 | f54a25c1f03e705f2fb65be7389ddeb37bc5e64e | Validate an icmp header before accessing it
A header can't be smaller than header.ICMPv4MinimumSize.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/icmp.go",
"new_path": "pkg/tcpip/network/ipv4/icmp.go",
"diff": "@@ -572,6 +572,10 @@ func (p *protocol) returnError(reason icmpReason, pkt *stack.PacketBuffer) tcpip\n// if problems arise this could be reversed. It was judged less of a breach\n// of protocol to not respond to unknown non-error packets than to respond\n// to unknown error packets so we take the first approach.\n+ if len(transportHeader) < header.ICMPv4MinimumSize {\n+ // The packet is malformed.\n+ return nil\n+ }\nswitch header.ICMPv4(transportHeader).Type() {\ncase\nheader.ICMPv4EchoReply,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Validate an icmp header before accessing it
A header can't be smaller than header.ICMPv4MinimumSize.
Reported-by: [email protected]
PiperOrigin-RevId: 405748438 |
259,907 | 26.10.2021 16:57:12 | 25,200 | 7b8f19dc76a9fecbf4d2e5f43a47c6d47d53e100 | Simplify vfs.NewDisconnectedMount signature and callpoints.
vfs.NewDisconnectedMount has no error paths. Its much prettier without the
error return value.
Also simplify MountDisconnected which would immediately drop the refs taken by
NewDisconnectedMount. Instead make it directly call newMount. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/mqfs/registry.go",
"new_path": "pkg/sentry/fsimpl/mqfs/registry.go",
"diff": "@@ -71,10 +71,7 @@ func NewRegistryImpl(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *\nvar dentry kernfs.Dentry\ndentry.InitRoot(&fs.Filesystem, fs.newRootInode(ctx, creds))\n- mount, err := vfsObj.NewDisconnectedMount(vfsfs, dentry.VFSDentry(), &vfs.MountOptions{})\n- if err != nil {\n- return nil, err\n- }\n+ mount := vfsObj.NewDisconnectedMount(vfsfs, dentry.VFSDentry(), &vfs.MountOptions{})\nreturn &RegistryImpl{\nroot: &dentry,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"new_path": "pkg/sentry/fsimpl/overlay/overlay.go",
"diff": "@@ -314,10 +314,7 @@ func clonePrivateMount(vfsObj *vfs.VirtualFilesystem, vd vfs.VirtualDentry, forc\nif forceReadOnly {\nopts.ReadOnly = true\n}\n- newmnt, err := vfsObj.NewDisconnectedMount(oldmnt.Filesystem(), vd.Dentry(), &opts)\n- if err != nil {\n- return vfs.VirtualDentry{}, err\n- }\n+ newmnt := vfsObj.NewDisconnectedMount(oldmnt.Filesystem(), vd.Dentry(), &opts)\n// Take a reference on the dentry which will be owned by the returned\n// VirtualDentry.\nd := vd.Dentry()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/kernel.go",
"new_path": "pkg/sentry/kernel/kernel.go",
"diff": "@@ -418,10 +418,7 @@ func (k *Kernel) Init(args InitKernelArgs) error {\nreturn fmt.Errorf(\"failed to create pipefs filesystem: %v\", err)\n}\ndefer pipeFilesystem.DecRef(ctx)\n- pipeMount, err := k.vfs.NewDisconnectedMount(pipeFilesystem, nil, &vfs.MountOptions{})\n- if err != nil {\n- return fmt.Errorf(\"failed to create pipefs mount: %v\", err)\n- }\n+ pipeMount := k.vfs.NewDisconnectedMount(pipeFilesystem, nil, &vfs.MountOptions{})\nk.pipeMount = pipeMount\ntmpfsFilesystem, tmpfsRoot, err := tmpfs.NewFilesystem(ctx, &k.vfs, auth.NewRootCredentials(k.rootUserNamespace))\n@@ -430,22 +427,14 @@ func (k *Kernel) Init(args InitKernelArgs) error {\n}\ndefer tmpfsFilesystem.DecRef(ctx)\ndefer tmpfsRoot.DecRef(ctx)\n- shmMount, err := k.vfs.NewDisconnectedMount(tmpfsFilesystem, tmpfsRoot, &vfs.MountOptions{})\n- if err != nil {\n- return fmt.Errorf(\"failed to create tmpfs mount: %v\", err)\n- }\n- k.shmMount = shmMount\n+ k.shmMount = k.vfs.NewDisconnectedMount(tmpfsFilesystem, tmpfsRoot, &vfs.MountOptions{})\nsocketFilesystem, err := sockfs.NewFilesystem(&k.vfs)\nif err != nil {\nreturn fmt.Errorf(\"failed to create sockfs filesystem: %v\", err)\n}\ndefer socketFilesystem.DecRef(ctx)\n- socketMount, err := k.vfs.NewDisconnectedMount(socketFilesystem, nil, &vfs.MountOptions{})\n- if err != nil {\n- return fmt.Errorf(\"failed to create sockfs mount: %v\", err)\n- }\n- k.socketMount = socketMount\n+ k.socketMount = k.vfs.NewDisconnectedMount(socketFilesystem, nil, &vfs.MountOptions{})\nk.socketsVFS2 = make(map[*vfs.FileDescription]*SocketRecord)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/mount.go",
"new_path": "pkg/sentry/vfs/mount.go",
"diff": "@@ -178,12 +178,12 @@ func (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth\n// (which may be nil). The new Mount is not associated with any MountNamespace\n// and is not connected to any other Mounts. References are taken on fs and\n// root.\n-func (vfs *VirtualFilesystem) NewDisconnectedMount(fs *Filesystem, root *Dentry, opts *MountOptions) (*Mount, error) {\n+func (vfs *VirtualFilesystem) NewDisconnectedMount(fs *Filesystem, root *Dentry, opts *MountOptions) *Mount {\nfs.IncRef()\nif root != nil {\nroot.IncRef()\n}\n- return newMount(vfs, fs, root, nil /* mntns */, opts), nil\n+ return newMount(vfs, fs, root, nil /* mntns */, opts)\n}\n// MountDisconnected creates a Filesystem configured by the given arguments,\n@@ -201,9 +201,7 @@ func (vfs *VirtualFilesystem) MountDisconnected(ctx context.Context, creds *auth\nif err != nil {\nreturn nil, err\n}\n- defer root.DecRef(ctx)\n- defer fs.DecRef(ctx)\n- return vfs.NewDisconnectedMount(fs, root, opts)\n+ return newMount(vfs, fs, root, nil /* mntns */, opts), nil\n}\n// ConnectMountAt connects mnt at the path represented by target.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -150,12 +150,7 @@ func (vfs *VirtualFilesystem) Init(ctx context.Context) error {\n}\nanonfs.vfsfs.Init(vfs, &anonFilesystemType{}, &anonfs)\ndefer anonfs.vfsfs.DecRef(ctx)\n- anonMount, err := vfs.NewDisconnectedMount(&anonfs.vfsfs, nil, &MountOptions{})\n- if err != nil {\n- // We should not be passing any MountOptions that would cause\n- // construction of this mount to fail.\n- panic(fmt.Sprintf(\"VirtualFilesystem.Init: anonfs mount failed: %v\", err))\n- }\n+ anonMount := vfs.NewDisconnectedMount(&anonfs.vfsfs, nil, &MountOptions{})\nvfs.anonMount = anonMount\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -411,11 +411,7 @@ func New(args Args) (*Loader, error) {\nreturn nil, fmt.Errorf(\"failed to create hostfs filesystem: %w\", err)\n}\ndefer hostFilesystem.DecRef(k.SupervisorContext())\n- hostMount, err := k.VFS().NewDisconnectedMount(hostFilesystem, nil, &vfs.MountOptions{})\n- if err != nil {\n- return nil, fmt.Errorf(\"failed to create hostfs mount: %w\", err)\n- }\n- k.SetHostMount(hostMount)\n+ k.SetHostMount(k.VFS().NewDisconnectedMount(hostFilesystem, nil, &vfs.MountOptions{}))\n}\neid := execID{cid: args.ID}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -769,10 +769,7 @@ func (c *containerMounter) mountSharedSubmountVFS2(ctx context.Context, conf *co\nif err != nil {\nreturn nil, err\n}\n- newMnt, err := c.k.VFS().NewDisconnectedMount(source.vfsMount.Filesystem(), source.vfsMount.Root(), opts)\n- if err != nil {\n- return nil, err\n- }\n+ newMnt := c.k.VFS().NewDisconnectedMount(source.vfsMount.Filesystem(), source.vfsMount.Root(), opts)\ndefer newMnt.DecRef(ctx)\nroot := mns.Root()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify vfs.NewDisconnectedMount signature and callpoints.
vfs.NewDisconnectedMount has no error paths. Its much prettier without the
error return value.
Also simplify MountDisconnected which would immediately drop the refs taken by
NewDisconnectedMount. Instead make it directly call newMount.
PiperOrigin-RevId: 405767966 |
259,977 | 27.10.2021 10:03:11 | 25,200 | 22a6a37079c69129d10abfbdd6fdfdf7a9d4a68d | Record counts of packets with unknown L3/L4 numbers
Previously, we recorded a single aggregated count. These per-protocol counts
can help us debug field issues when frames are dropped for this reason. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -81,8 +81,6 @@ func mustCreateGauge(name, description string) *tcpip.StatCounter {\nvar Metrics = tcpip.Stats{\nDroppedPackets: mustCreateMetric(\"/netstack/dropped_packets\", \"Number of packets dropped at the transport layer.\"),\nNICs: tcpip.NICStats{\n- UnknownL3ProtocolRcvdPackets: mustCreateMetric(\"/netstack/nic/unknown_l3_protocol_received_packets\", \"Number of packets received that were for an unknown or unsupported L3 protocol.\"),\n- UnknownL4ProtocolRcvdPackets: mustCreateMetric(\"/netstack/nic/unknown_l4_protocol_received_packets\", \"Number of packets received that were for an unknown or unsupported L4 protocol.\"),\nMalformedL4RcvdPackets: mustCreateMetric(\"/netstack/nic/malformed_l4_received_packets\", \"Number of packets received that failed L4 header parsing.\"),\nTx: tcpip.NICPacketStats{\nPackets: mustCreateMetric(\"/netstack/nic/tx/packets\", \"Number of packets transmitted.\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/arp/stats_test.go",
"new_path": "pkg/tcpip/network/arp/stats_test.go",
"diff": "@@ -45,7 +45,10 @@ func TestMultiCounterStatsInitialization(t *testing.T) {\n// expected to be bound by a MultiCounterStat.\nrefStack := s.Stats()\nrefEP := 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+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.arp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.ARP).Elem(), reflect.ValueOf(&refStack.ARP).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/stats_test.go",
"new_path": "pkg/tcpip/network/ipv4/stats_test.go",
"diff": "@@ -87,13 +87,22 @@ func TestMultiCounterStatsInitialization(t *testing.T) {\n// expected to be bound by a MultiCounterStat.\nrefStack := s.Stats()\nrefEP := ep.stats.localStats\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.ip).Elem(), []reflect.Value{reflect.ValueOf(&refEP.IP).Elem(), reflect.ValueOf(&refStack.IP).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.ip).Elem(), []reflect.Value{reflect.ValueOf(&refEP.IP).Elem(), reflect.ValueOf(&refStack.IP).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.icmp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.ICMP).Elem(), reflect.ValueOf(&refStack.ICMP.V4).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.icmp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.ICMP).Elem(), reflect.ValueOf(&refStack.ICMP.V4).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.igmp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.IGMP).Elem(), reflect.ValueOf(&refStack.IGMP).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.igmp).Elem(), []reflect.Value{reflect.ValueOf(&refEP.IGMP).Elem(), reflect.ValueOf(&refStack.IGMP).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6_test.go",
"diff": "@@ -3515,10 +3515,16 @@ func TestMultiCounterStatsInitialization(t *testing.T) {\n// supposed to be bound.\nrefStack := s.Stats()\nrefEP := ep.stats.localStats\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.ip).Elem(), []reflect.Value{reflect.ValueOf(&refStack.IP).Elem(), reflect.ValueOf(&refEP.IP).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.ip).Elem(), []reflect.Value{reflect.ValueOf(&refStack.IP).Elem(), reflect.ValueOf(&refEP.IP).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.icmp).Elem(), []reflect.Value{reflect.ValueOf(&refStack.ICMP.V6).Elem(), reflect.ValueOf(&refEP.ICMP).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&ep.stats.icmp).Elem(), []reflect.Value{reflect.ValueOf(&refStack.ICMP.V6).Elem(), reflect.ValueOf(&refEP.ICMP).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: false,\n+ }); err != nil {\nt.Error(err)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -727,7 +727,7 @@ func (n *nic) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\nnetworkEndpoint, ok := n.networkEndpoints[protocol]\nif !ok {\n- n.stats.unknownL3ProtocolRcvdPackets.Increment()\n+ n.stats.unknownL3ProtocolRcvdPacketCounts.Increment(uint64(protocol))\nreturn\n}\n@@ -827,7 +827,7 @@ func (n *nic) deliverOutboundPacket(remote tcpip.LinkAddress, pkt *PacketBuffer)\nfunc (n *nic) DeliverTransportPacket(protocol tcpip.TransportProtocolNumber, pkt *PacketBuffer) TransportPacketDisposition {\nstate, ok := n.stack.transportProtocols[protocol]\nif !ok {\n- n.stats.unknownL4ProtocolRcvdPackets.Increment()\n+ n.stats.unknownL4ProtocolRcvdPacketCounts.Increment(uint64(protocol))\nreturn TransportPacketProtocolUnreachable\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic_stats.go",
"new_path": "pkg/tcpip/stack/nic_stats.go",
"diff": "@@ -35,7 +35,7 @@ func (m *multiCounterNICPacketStats) init(a, b *tcpip.NICPacketStats) {\nm.bytes.Init(a.Bytes, b.Bytes)\n}\n-// LINT.ThenChange(../../tcpip.go:NICPacketStats)\n+// LINT.ThenChange(../tcpip.go:NICPacketStats)\n// LINT.IfChange(multiCounterNICNeighborStats)\n@@ -47,13 +47,13 @@ func (m *multiCounterNICNeighborStats) init(a, b *tcpip.NICNeighborStats) {\nm.unreachableEntryLookups.Init(a.UnreachableEntryLookups, b.UnreachableEntryLookups)\n}\n-// LINT.ThenChange(../../tcpip.go:NICNeighborStats)\n+// LINT.ThenChange(../tcpip.go:NICNeighborStats)\n// LINT.IfChange(multiCounterNICStats)\ntype multiCounterNICStats struct {\n- unknownL3ProtocolRcvdPackets tcpip.MultiCounterStat\n- unknownL4ProtocolRcvdPackets tcpip.MultiCounterStat\n+ unknownL3ProtocolRcvdPacketCounts tcpip.MultiIntegralStatCounterMap\n+ unknownL4ProtocolRcvdPacketCounts tcpip.MultiIntegralStatCounterMap\nmalformedL4RcvdPackets tcpip.MultiCounterStat\ntx multiCounterNICPacketStats\nrx multiCounterNICPacketStats\n@@ -62,8 +62,8 @@ type multiCounterNICStats struct {\n}\nfunc (m *multiCounterNICStats) init(a, b *tcpip.NICStats) {\n- m.unknownL3ProtocolRcvdPackets.Init(a.UnknownL3ProtocolRcvdPackets, b.UnknownL3ProtocolRcvdPackets)\n- m.unknownL4ProtocolRcvdPackets.Init(a.UnknownL4ProtocolRcvdPackets, b.UnknownL4ProtocolRcvdPackets)\n+ m.unknownL3ProtocolRcvdPacketCounts.Init(a.UnknownL3ProtocolRcvdPacketCounts, b.UnknownL3ProtocolRcvdPacketCounts)\n+ m.unknownL4ProtocolRcvdPacketCounts.Init(a.UnknownL4ProtocolRcvdPacketCounts, b.UnknownL4ProtocolRcvdPacketCounts)\nm.malformedL4RcvdPackets.Init(a.MalformedL4RcvdPackets, b.MalformedL4RcvdPackets)\nm.tx.init(&a.Tx, &b.Tx)\nm.rx.init(&a.Rx, &b.Rx)\n@@ -71,4 +71,4 @@ func (m *multiCounterNICStats) init(a, b *tcpip.NICStats) {\nm.neighbor.init(&a.Neighbor, &b.Neighbor)\n}\n-// LINT.ThenChange(../../tcpip.go:NICStats)\n+// LINT.ThenChange(../tcpip.go:NICStats)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic_test.go",
"new_path": "pkg/tcpip/stack/nic_test.go",
"diff": "@@ -206,6 +206,45 @@ func TestDisabledRxStatsWhenNICDisabled(t *testing.T) {\n}\n}\n+func TestPacketWithUnknownNetworkProtocolNumber(t *testing.T) {\n+ nic := nic{\n+ stats: makeNICStats(tcpip.NICStats{}.FillIn()),\n+ enabled: 1,\n+ }\n+ // IPv4 isn't recognized since we haven't initialized the NIC with an IPv4\n+ // endpoint.\n+ nic.DeliverNetworkPacket(\"\", \"\", header.IPv4ProtocolNumber, NewPacketBuffer(PacketBufferOptions{\n+ Data: buffer.View([]byte{1, 2, 3, 4}).ToVectorisedView(),\n+ }))\n+ var count uint64\n+ if got, ok := nic.stats.local.UnknownL3ProtocolRcvdPacketCounts.Get(uint64(header.IPv4ProtocolNumber)); ok {\n+ count = got.Value()\n+ }\n+ if count != 1 {\n+ t.Errorf(\"got UnknownL3ProtocolRcvdPacketCounts[header.IPv4ProtocolNumber] = %d, want = 1\", count)\n+ }\n+}\n+\n+func TestPacketWithUnknownTransportProtocolNumber(t *testing.T) {\n+ nic := nic{\n+ stack: &Stack{},\n+ stats: makeNICStats(tcpip.NICStats{}.FillIn()),\n+ enabled: 1,\n+ }\n+ // UDP isn't recognized since we haven't initialized the NIC with a UDP\n+ // protocol.\n+ nic.DeliverTransportPacket(header.UDPProtocolNumber, NewPacketBuffer(PacketBufferOptions{\n+ Data: buffer.View([]byte{1, 2, 3, 4}).ToVectorisedView(),\n+ }))\n+ var count uint64\n+ if got, ok := nic.stats.local.UnknownL4ProtocolRcvdPacketCounts.Get(uint64(header.UDPProtocolNumber)); ok {\n+ count = got.Value()\n+ }\n+ if count != 1 {\n+ t.Errorf(\"got UnknownL4ProtocolRcvdPacketCounts[header.UDPProtocolNumber] = %d, want = 1\", count)\n+ }\n+}\n+\nfunc TestMultiCounterStatsInitialization(t *testing.T) {\nglobal := tcpip.NICStats{}.FillIn()\nnic := nic{\n@@ -213,7 +252,10 @@ func TestMultiCounterStatsInitialization(t *testing.T) {\n}\nmulti := nic.stats.multiCounterNICStats\nlocal := nic.stats.local\n- if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&multi).Elem(), []reflect.Value{reflect.ValueOf(&local).Elem(), reflect.ValueOf(&global).Elem()}); err != nil {\n+ if err := testutil.ValidateMultiCounterStats(reflect.ValueOf(&multi).Elem(), []reflect.Value{reflect.ValueOf(&local).Elem(), reflect.ValueOf(&global).Elem()}, testutil.ValidateMultiCounterStatsOptions{\n+ ExpectMultiCounterStat: true,\n+ ExpectMultiIntegralStatCounterMap: true,\n+ }); err != nil {\nt.Error(err)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -1301,7 +1301,8 @@ func (s *StatCounter) String() string {\n// A MultiCounterStat keeps track of two counters at once.\ntype MultiCounterStat struct {\n- a, b *StatCounter\n+ a *StatCounter\n+ b *StatCounter\n}\n// Init sets both internal counters to point to a and b.\n@@ -1923,17 +1924,89 @@ type NICPacketStats struct {\n// LINT.ThenChange(stack/nic_stats.go:multiCounterNICPacketStats)\n}\n+// IntegralStatCounterMap holds a map associating integral keys with\n+// StatCounters.\n+type IntegralStatCounterMap struct {\n+ mu sync.RWMutex\n+ // +checklocks:mu\n+ counterMap map[uint64]*StatCounter\n+}\n+\n+// Keys returns all keys present in the map.\n+func (m *IntegralStatCounterMap) Keys() []uint64 {\n+ m.mu.RLock()\n+ defer m.mu.RUnlock()\n+ var keys []uint64\n+ for k := range m.counterMap {\n+ keys = append(keys, k)\n+ }\n+ return keys\n+}\n+\n+// Get returns the counter mapped by the provided key.\n+func (m *IntegralStatCounterMap) Get(key uint64) (*StatCounter, bool) {\n+ m.mu.RLock()\n+ defer m.mu.RUnlock()\n+ counter, ok := m.counterMap[key]\n+ return counter, ok\n+}\n+\n+// Init initializes the map.\n+func (m *IntegralStatCounterMap) Init() {\n+ m.mu.Lock()\n+ defer m.mu.Unlock()\n+ m.counterMap = make(map[uint64]*StatCounter)\n+}\n+\n+// Increment increments the counter associated with the provided key.\n+func (m *IntegralStatCounterMap) Increment(key uint64) {\n+ m.mu.RLock()\n+ counter, ok := m.counterMap[key]\n+ m.mu.RUnlock()\n+\n+ if !ok {\n+ m.mu.Lock()\n+ counter, ok = m.counterMap[key]\n+ if !ok {\n+ counter = new(StatCounter)\n+ m.counterMap[key] = counter\n+ }\n+ m.mu.Unlock()\n+ }\n+ counter.Increment()\n+}\n+\n+// A MultiIntegralStatCounterMap keeps track of two integral counter maps at\n+// once.\n+type MultiIntegralStatCounterMap struct {\n+ a *IntegralStatCounterMap\n+ b *IntegralStatCounterMap\n+}\n+\n+// Init sets the internal integral counter maps to point to a and b.\n+func (m *MultiIntegralStatCounterMap) Init(a, b *IntegralStatCounterMap) {\n+ m.a = a\n+ m.b = b\n+}\n+\n+// Increment increments the counter in each map corresponding to the\n+// provided key.\n+func (m *MultiIntegralStatCounterMap) Increment(key uint64) {\n+ m.a.Increment(key)\n+ m.b.Increment(key)\n+}\n+\n// NICStats holds NIC statistics.\ntype NICStats struct {\n// LINT.IfChange(NICStats)\n- // UnknownL3ProtocolRcvdPackets is the number of packets received that were\n- // for an unknown or unsupported network protocol.\n- UnknownL3ProtocolRcvdPackets *StatCounter\n+ // UnknownL3ProtocolRcvdPacketCounts records the number of packets recieved\n+ // for each unknown or unsupported netowrk protocol number.\n+ UnknownL3ProtocolRcvdPacketCounts *IntegralStatCounterMap\n- // UnknownL4ProtocolRcvdPackets is the number of packets received that were\n- // for an unknown or unsupported transport protocol.\n- UnknownL4ProtocolRcvdPackets *StatCounter\n+ // UnknownL4ProtocolRcvdPacketCounts records the number of packets recieved\n+ // for each unknown or unsupported transport protocol number.\n+ UnknownL4ProtocolRcvdPacketCounts *IntegralStatCounterMap\n// MalformedL4RcvdPackets is the number of packets received by a NIC that\n// could not be delivered to a transport endpoint because the L4 header could\n@@ -2103,6 +2176,11 @@ func InitStatCounters(v reflect.Value) {\nif *s == nil {\n*s = new(StatCounter)\n}\n+ } else if s, ok := v.Addr().Interface().(**IntegralStatCounterMap); ok {\n+ if *s == nil {\n+ *s = new(IntegralStatCounterMap)\n+ (*s).Init()\n+ }\n} else {\nInitStatCounters(v)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/testutil/testutil.go",
"new_path": "pkg/tcpip/testutil/testutil.go",
"diff": "@@ -77,12 +77,43 @@ func validateField(ref reflect.Value, refName string, m tcpip.MultiCounterStat,\nreturn nil\n}\n-// ValidateMultiCounterStats verifies that every counter stored in multi is\n-// correctly tracking its counterpart in the given counters.\n-func ValidateMultiCounterStats(multi reflect.Value, counters []reflect.Value) error {\n+func validateIntegralMapField(ref reflect.Value, refName string, m tcpip.MultiIntegralStatCounterMap, multiName string) error {\n+ // The field names are expected to match (case insensitive).\n+ if !strings.EqualFold(refName, multiName) {\n+ return fmt.Errorf(\"wrong field name: got = %s, want = %s\", multiName, refName)\n+ }\n+ s, ok := ref.Addr().Interface().(**tcpip.IntegralStatCounterMap)\n+ if !ok {\n+ return fmt.Errorf(\"field is not an IntegralStatCounterMap\")\n+ }\n+\n+ const key = 42\n+\n+ getValue := func() uint64 {\n+ counter, ok := (*s).Get(key)\n+ if !ok {\n+ return 0\n+ }\n+ return counter.Value()\n+ }\n+\n+ before := getValue()\n+\n+ m.Increment(key)\n+\n+ after := getValue()\n+\n+ if after != before+1 {\n+ return fmt.Errorf(\"updates to the '%s MultiCounterStat' counters are not reflected in the '%s CounterStat'\", multiName, refName)\n+ }\n+\n+ return nil\n+}\n+\n+func validateMultiCounterStats(multi reflect.Value, counters []reflect.Value) (foundMultiCounterStat, foundMultiIntegralStatCounterMap bool, err error) {\nfor _, c := range counters {\nif err := checkFieldCounts(c, multi); err != nil {\n- return err\n+ return false, false, err\n}\n}\n@@ -90,21 +121,57 @@ func ValidateMultiCounterStats(multi reflect.Value, counters []reflect.Value) er\nmultiName := multi.Type().Field(i).Name\nmultiUnsafe := unsafeExposeUnexportedFields(multi.Field(i))\n- if m, ok := multiUnsafe.Addr().Interface().(*tcpip.MultiCounterStat); ok {\n+ switch m := multiUnsafe.Addr().Interface().(type) {\n+ case *tcpip.MultiCounterStat:\n+ foundMultiCounterStat = true\nfor _, c := range counters {\nif err := validateField(unsafeExposeUnexportedFields(c.Field(i)), c.Type().Field(i).Name, *m, multiName); err != nil {\n- return err\n+ return false, false, err\n}\n}\n- } else {\n+ case *tcpip.MultiIntegralStatCounterMap:\n+ foundMultiIntegralStatCounterMap = true\n+ for _, c := range counters {\n+ if err := validateIntegralMapField(unsafeExposeUnexportedFields(c.Field(i)), c.Type().Field(i).Name, *m, multiName); err != nil {\n+ return false, false, err\n+ }\n+ }\n+ default:\nvar countersNextField []reflect.Value\nfor _, c := range counters {\ncountersNextField = append(countersNextField, c.Field(i))\n}\n- if err := ValidateMultiCounterStats(multi.Field(i), countersNextField); err != nil {\n+ innerFoundMultiCounterStat, innerFoundMultiIntegralStatCounterMap, err := validateMultiCounterStats(multi.Field(i), countersNextField)\n+ if err != nil {\n+ return false, false, err\n+ }\n+ foundMultiCounterStat = foundMultiCounterStat || innerFoundMultiCounterStat\n+ foundMultiIntegralStatCounterMap = foundMultiIntegralStatCounterMap || innerFoundMultiIntegralStatCounterMap\n+ }\n+ }\n+\n+ return foundMultiCounterStat, foundMultiIntegralStatCounterMap, nil\n+}\n+\n+// ValidateMultiCounterStatsOptions holds options used when validating multi\n+// counter stat structs.\n+type ValidateMultiCounterStatsOptions struct {\n+ ExpectMultiCounterStat bool\n+ ExpectMultiIntegralStatCounterMap bool\n+}\n+\n+// ValidateMultiCounterStats verifies that every counter stored in multi is\n+// correctly tracking its counterpart in the given counters.\n+func ValidateMultiCounterStats(multi reflect.Value, counters []reflect.Value, options ValidateMultiCounterStatsOptions) error {\n+ foundMultiCounterStat, foundMultiIntegralStatCounterMap, err := validateMultiCounterStats(multi, counters)\n+ if err != nil {\nreturn err\n}\n+ if foundMultiCounterStat != options.ExpectMultiCounterStat {\n+ return fmt.Errorf(\"got %T presence: %t, want: %t\", (*tcpip.MultiCounterStat)(nil), foundMultiCounterStat, options.ExpectMultiCounterStat)\n}\n+ if foundMultiIntegralStatCounterMap != options.ExpectMultiIntegralStatCounterMap {\n+ return fmt.Errorf(\"got %T presence: %t, want: %t\", (*tcpip.MultiIntegralStatCounterMap)(nil), foundMultiIntegralStatCounterMap, options.ExpectMultiIntegralStatCounterMap)\n}\nreturn nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Record counts of packets with unknown L3/L4 numbers
Previously, we recorded a single aggregated count. These per-protocol counts
can help us debug field issues when frames are dropped for this reason.
PiperOrigin-RevId: 405913911 |
260,004 | 27.10.2021 13:39:24 | 25,200 | 3015c0ac67ef7703899e753121efe326dc0cbecd | NAT ICMPv4 errors
...so a NAT-ed connection's socket can handle ICMP errors.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -209,19 +209,120 @@ type bucket struct {\ntuples tupleList\n}\n-func getTransportHeader(pkt *PacketBuffer) (header.ChecksummableTransport, bool) {\n+func getHeaders(pkt *PacketBuffer) (netHdr header.Network, transHdr header.ChecksummableTransport, isICMPError bool, ok bool) {\nswitch pkt.TransportProtocolNumber {\ncase header.TCPProtocolNumber:\nif tcpHeader := header.TCP(pkt.TransportHeader().View()); len(tcpHeader) >= header.TCPMinimumSize {\n- return tcpHeader, true\n+ return pkt.Network(), tcpHeader, false, true\n}\ncase header.UDPProtocolNumber:\nif udpHeader := header.UDP(pkt.TransportHeader().View()); len(udpHeader) >= header.UDPMinimumSize {\n- return udpHeader, true\n+ return pkt.Network(), udpHeader, false, true\n+ }\n+ case header.ICMPv4ProtocolNumber:\n+ h, ok := pkt.Data().PullUp(header.IPv4MinimumSize)\n+ if !ok {\n+ panic(fmt.Sprintf(\"should have a valid IPv4 packet; only have %d bytes, want at least %d bytes\", pkt.Data().Size(), header.IPv4MinimumSize))\n+ }\n+\n+ ipv4 := header.IPv4(h)\n+ if ipv4.HeaderLength() > header.IPv4MinimumSize {\n+ // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n+ panic(\"should have dropped packets with IPv4 options\")\n+ }\n+\n+ switch pkt.tuple.id().transProto {\n+ case header.TCPProtocolNumber:\n+ // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n+ netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.TCPMinimumSize)\n+ if !ok {\n+ return nil, nil, false, false\n+ }\n+ netHeader := header.IPv4(netAndTransHeader)\n+ return netHeader, header.TCP(netHeader.Payload()), true, true\n+ case header.UDPProtocolNumber:\n+ // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n+ netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.UDPMinimumSize)\n+ if !ok {\n+ return nil, nil, false, false\n+ }\n+ netHeader := header.IPv4(netAndTransHeader)\n+ return netHeader, header.UDP(netHeader.Payload()), true, true\n+ }\n+ }\n+\n+ return nil, nil, false, false\n+}\n+\n+func getTupleIDForRegularPacket(netHdr header.Network, netProto tcpip.NetworkProtocolNumber, transHdr header.Transport, transProto tcpip.TransportProtocolNumber) tupleID {\n+ return tupleID{\n+ srcAddr: netHdr.SourceAddress(),\n+ srcPort: transHdr.SourcePort(),\n+ dstAddr: netHdr.DestinationAddress(),\n+ dstPort: transHdr.DestinationPort(),\n+ transProto: transProto,\n+ netProto: netProto,\n+ }\n+}\n+\n+func getTupleIDForPacketInICMPError(netHdr header.Network, netProto tcpip.NetworkProtocolNumber, transHdr header.Transport, transProto tcpip.TransportProtocolNumber) tupleID {\n+ return tupleID{\n+ srcAddr: netHdr.DestinationAddress(),\n+ srcPort: transHdr.DestinationPort(),\n+ dstAddr: netHdr.SourceAddress(),\n+ dstPort: transHdr.SourcePort(),\n+ transProto: transProto,\n+ netProto: netProto,\n+ }\n+}\n+\n+func getTupleID(pkt *PacketBuffer) (tid tupleID, isICMPError bool, ok bool) {\n+ switch pkt.TransportProtocolNumber {\n+ case header.TCPProtocolNumber:\n+ if transHeader := header.TCP(pkt.TransportHeader().View()); len(transHeader) >= header.TCPMinimumSize {\n+ return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), false, true\n+ }\n+ case header.UDPProtocolNumber:\n+ if transHeader := header.UDP(pkt.TransportHeader().View()); len(transHeader) >= header.UDPMinimumSize {\n+ return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), false, true\n+ }\n+ case header.ICMPv4ProtocolNumber:\n+ icmp := header.ICMPv4(pkt.TransportHeader().View())\n+ if len(icmp) < header.ICMPv4MinimumSize {\n+ return tupleID{}, false, false\n+ }\n+\n+ switch icmp.Type() {\n+ case header.ICMPv4DstUnreachable, header.ICMPv4TimeExceeded, header.ICMPv4ParamProblem:\n+ default:\n+ return tupleID{}, false, false\n+ }\n+\n+ h, ok := pkt.Data().PullUp(header.IPv4MinimumSize)\n+ if !ok {\n+ return tupleID{}, false, false\n+ }\n+\n+ ipv4 := header.IPv4(h)\n+ if ipv4.HeaderLength() > header.IPv4MinimumSize {\n+ // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n+ return tupleID{}, false, false\n+ }\n+ switch ipv4.TransportProtocol() {\n+ case header.TCPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.TCPMinimumSize); ok {\n+ netHdr := header.IPv4(netAndTransHeader)\n+ return getTupleIDForPacketInICMPError(netHdr, header.IPv4ProtocolNumber, header.TCP(netHdr.Payload()), header.TCPProtocolNumber), true, true\n+ }\n+ case header.UDPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.UDPMinimumSize); ok {\n+ netHdr := header.IPv4(netAndTransHeader)\n+ return getTupleIDForPacketInICMPError(netHdr, header.IPv4ProtocolNumber, header.UDP(netHdr.Payload()), header.UDPProtocolNumber), true, true\n+ }\n}\n}\n- return nil, false\n+ return tupleID{}, false, false\n}\nfunc (ct *ConnTrack) init() {\n@@ -231,21 +332,11 @@ func (ct *ConnTrack) init() {\n}\nfunc (ct *ConnTrack) getConnOrMaybeInsertNoop(pkt *PacketBuffer) *tuple {\n- netHeader := pkt.Network()\n- transportHeader, ok := getTransportHeader(pkt)\n+ tid, isICMPError, ok := getTupleID(pkt)\nif !ok {\nreturn nil\n}\n- tid := tupleID{\n- srcAddr: netHeader.SourceAddress(),\n- srcPort: transportHeader.SourcePort(),\n- dstAddr: netHeader.DestinationAddress(),\n- dstPort: transportHeader.DestinationPort(),\n- transProto: pkt.TransportProtocolNumber,\n- netProto: pkt.NetworkProtocolNumber,\n- }\n-\nbktID := ct.bucket(tid)\nct.mu.RLock()\n@@ -257,6 +348,11 @@ func (ct *ConnTrack) getConnOrMaybeInsertNoop(pkt *PacketBuffer) *tuple {\nreturn t\n}\n+ if isICMPError {\n+ // Do not create a noop entry in response to an ICMP error.\n+ return nil\n+ }\n+\nbkt.mu.Lock()\ndefer bkt.mu.Unlock()\n@@ -407,7 +503,7 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\n//\n// Returns true if the packet can skip the NAT table.\nfunc (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\n- transportHeader, ok := getTransportHeader(pkt)\n+ netHdr, transHdr, isICMPError, ok := getHeaders(pkt)\nif !ok {\nreturn false\n}\n@@ -498,9 +594,9 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\n}\nrewritePacket(\n- pkt.Network(),\n- transportHeader,\n- !dnat,\n+ netHdr,\n+ transHdr,\n+ !dnat != isICMPError,\nfullChecksum,\nupdatePseudoHeader,\nnewPort,\n@@ -508,6 +604,28 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\n)\n*natDone = true\n+\n+ if !isICMPError {\n+ return true\n+ }\n+\n+ // We performed NAT on (erroneous) packet that triggered an ICMP response, but\n+ // not the ICMP packet itself.\n+ switch pkt.TransportProtocolNumber {\n+ case header.ICMPv4ProtocolNumber:\n+ icmp := header.ICMPv4(pkt.TransportHeader().View())\n+ // TODO(https://gvisor.dev/issue/6788): Incrementally update ICMP checksum.\n+ icmp.SetChecksum(0)\n+ icmp.SetChecksum(header.ICMPv4Checksum(icmp, pkt.Data().AsRange().Checksum()))\n+\n+ network := header.IPv4(pkt.NetworkHeader().View())\n+ if dnat {\n+ network.SetDestinationAddressWithChecksumUpdate(tid.srcAddr)\n+ } else {\n+ network.SetSourceAddressWithChecksumUpdate(tid.dstAddr)\n+ }\n+ }\n+\nreturn true\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1779,3 +1779,296 @@ func TestNAT(t *testing.T) {\n})\n}\n}\n+\n+func TestNATICMPError(t *testing.T) {\n+ const srcPort = 1234\n+ const dstPort = 5432\n+\n+ type icmpTypeTest struct {\n+ name string\n+ val uint8\n+ expectResponse bool\n+ }\n+\n+ type transportTypeTest struct {\n+ name string\n+ proto tcpip.TransportProtocolNumber\n+ buf buffer.View\n+ checkNATed func(*testing.T, buffer.View)\n+ }\n+\n+ ipHdr := func(v buffer.View, totalLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\n+ ip := header.IPv4(v)\n+ ip.Encode(&header.IPv4Fields{\n+ TotalLength: uint16(totalLen),\n+ Protocol: uint8(transProto),\n+ TTL: 64,\n+ SrcAddr: srcAddr,\n+ DstAddr: dstAddr,\n+ })\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+ }\n+\n+ tests := []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ host1Addr tcpip.Address\n+ icmpError func(*testing.T, buffer.View, uint8) buffer.View\n+ decrementTTL func(buffer.View)\n+ checkNATedError func(*testing.T, buffer.View, buffer.View, uint8)\n+\n+ transportTypes []transportTypeTest\n+ icmpTypes []icmpTypeTest\n+ }{\n+ {\n+ name: \"IPv4\",\n+ netProto: ipv4.ProtocolNumber,\n+ host1Addr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ icmpError: func(t *testing.T, original buffer.View, icmpType uint8) buffer.View {\n+ totalLen := header.IPv4MinimumSize + header.ICMPv4MinimumSize + len(original)\n+ hdr := buffer.NewPrependable(totalLen)\n+ if n := copy(hdr.Prepend(len(original)), original); n != len(original) {\n+ t.Fatalf(\"got copy(...) = %d, want = %d\", n, len(original))\n+ }\n+ icmp := header.ICMPv4(hdr.Prepend(header.ICMPv4MinimumSize))\n+ icmp.SetType(header.ICMPv4Type(icmpType))\n+ icmp.SetChecksum(0)\n+ icmp.SetChecksum(header.ICMPv4Checksum(icmp, 0))\n+ ipHdr(hdr.Prepend(header.IPv4MinimumSize),\n+ totalLen,\n+ header.ICMPv4ProtocolNumber,\n+ utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ },\n+ decrementTTL: func(v buffer.View) {\n+ ip := header.IPv4(v)\n+ ip.SetTTL(ip.TTL() - 1)\n+ ip.SetChecksum(0)\n+ ip.SetChecksum(^ip.CalculateChecksum())\n+ },\n+ checkNATedError: func(t *testing.T, v buffer.View, original buffer.View, icmpType uint8) {\n+ checker.IPv4(t, v,\n+ checker.SrcAddr(utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host2IPv4Addr.AddressWithPrefix.Address),\n+ checker.ICMPv4(\n+ checker.ICMPv4Type(header.ICMPv4Type(icmpType)),\n+ checker.ICMPv4Checksum(),\n+ checker.ICMPv4Payload(original),\n+ ),\n+ )\n+ },\n+ transportTypes: []transportTypeTest{\n+ {\n+ name: \"UDP\",\n+ proto: header.UDPProtocolNumber,\n+ buf: func() buffer.View {\n+ totalLen := header.IPv4MinimumSize + header.UDPMinimumSize\n+ hdr := buffer.NewPrependable(totalLen)\n+ udp := header.UDP(hdr.Prepend(header.UDPMinimumSize))\n+ udp.SetSourcePort(srcPort)\n+ udp.SetDestinationPort(dstPort)\n+ udp.SetChecksum(0)\n+ udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.UDPProtocolNumber,\n+ utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ uint16(len(udp)),\n+ )))\n+ ipHdr(hdr.Prepend(header.IPv4MinimumSize),\n+ totalLen,\n+ header.UDPProtocolNumber,\n+ utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ }(),\n+ checkNATed: func(t *testing.T, v buffer.View) {\n+ checker.IPv4(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv4Addr.AddressWithPrefix.Address),\n+ checker.UDP(\n+ checker.SrcPort(srcPort),\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+ },\n+ },\n+ {\n+ name: \"TCP\",\n+ proto: header.TCPProtocolNumber,\n+ buf: func() buffer.View {\n+ totalLen := header.IPv4MinimumSize + header.TCPMinimumSize\n+ hdr := buffer.NewPrependable(totalLen)\n+ tcp := header.TCP(hdr.Prepend(header.TCPMinimumSize))\n+ tcp.SetSourcePort(srcPort)\n+ tcp.SetDestinationPort(dstPort)\n+ tcp.SetDataOffset(header.TCPMinimumSize)\n+ tcp.SetChecksum(0)\n+ tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.TCPProtocolNumber,\n+ utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ uint16(len(tcp)),\n+ )))\n+ ipHdr(hdr.Prepend(header.IPv4MinimumSize),\n+ totalLen,\n+ header.TCPProtocolNumber,\n+ utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ }(),\n+ checkNATed: func(t *testing.T, v buffer.View) {\n+ checker.IPv4(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv4Addr.AddressWithPrefix.Address),\n+ checker.TCP(\n+ checker.SrcPort(srcPort),\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+ },\n+ },\n+ },\n+ icmpTypes: []icmpTypeTest{\n+ {\n+ name: \"Destination Unreachable\",\n+ val: uint8(header.ICMPv4DstUnreachable),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Time Exceeded\",\n+ val: uint8(header.ICMPv4TimeExceeded),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Parameter Problem\",\n+ val: uint8(header.ICMPv4ParamProblem),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Echo Request\",\n+ val: uint8(header.ICMPv4Echo),\n+ expectResponse: false,\n+ },\n+ {\n+ name: \"Echo Reply\",\n+ val: uint8(header.ICMPv4EchoReply),\n+ expectResponse: false,\n+ },\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ for _, transportType := range test.transportTypes {\n+ t.Run(transportType.name, func(t *testing.T) {\n+ for _, icmpType := range test.icmpTypes {\n+ t.Run(icmpType.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, tcp.NewProtocol},\n+ })\n+\n+ ep1 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ ep2 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ utils.SetupRouterStack(t, s, ep1, ep2)\n+\n+ ipv6 := test.netProto == ipv6.ProtocolNumber\n+ ipt := s.IPTables()\n+\n+ table := stack.Table{\n+ Rules: []stack.Rule{\n+ // Prerouting\n+ {\n+ Filter: stack.IPHeaderFilter{\n+ Protocol: transportType.proto,\n+ CheckProtocol: true,\n+ InputInterface: utils.RouterNIC2Name,\n+ },\n+ Target: &stack.DNATTarget{NetworkProtocol: test.netProto, Addr: test.host1Addr, Port: dstPort},\n+ },\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Input\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Forward\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Output\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Postrouting\n+ {\n+ Filter: stack.IPHeaderFilter{\n+ Protocol: transportType.proto,\n+ CheckProtocol: true,\n+ OutputInterface: utils.RouterNIC1Name,\n+ },\n+ Target: &stack.MasqueradeTarget{NetworkProtocol: test.netProto},\n+ },\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+ },\n+ BuiltinChains: [stack.NumHooks]int{\n+ stack.Prerouting: 0,\n+ stack.Input: 2,\n+ stack.Forward: 3,\n+ stack.Output: 4,\n+ stack.Postrouting: 5,\n+ },\n+ }\n+\n+ if err := ipt.ReplaceTable(stack.NATID, table, ipv6); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n+ }\n+\n+ ep2.InjectInbound(test.netProto, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: append(buffer.View(nil), transportType.buf...).ToVectorisedView(),\n+ }))\n+\n+ {\n+ pkt, ok := ep1.Read()\n+ if !ok {\n+ t.Fatal(\"expected to read a packet on ep1\")\n+ }\n+ pktView := stack.PayloadSince(pkt.Pkt.NetworkHeader())\n+ transportType.checkNATed(t, pktView)\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ ep1.InjectInbound(test.netProto, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: test.icmpError(t, pktView, icmpType.val).ToVectorisedView(),\n+ }))\n+ }\n+\n+ pkt, ok := ep2.Read()\n+ if ok != icmpType.expectResponse {\n+ t.Fatalf(\"got ep2.Read() = (%#v, %t), want = (_, %t)\", pkt, ok, icmpType.expectResponse)\n+ }\n+ if !icmpType.expectResponse {\n+ return\n+ }\n+ test.decrementTTL(transportType.buf)\n+ test.checkNATedError(t, stack.PayloadSince(pkt.Pkt.NetworkHeader()), transportType.buf, icmpType.val)\n+ })\n+ }\n+ })\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/utils/utils.go",
"new_path": "pkg/tcpip/tests/utils/utils.go",
"diff": "@@ -213,30 +213,83 @@ func (e *EndpointWithDestinationCheck) DeliverNetworkPacket(src, dst tcpip.LinkA\n}\n}\n+// SetupRouterStack creates the NICs, sets forwarding, adds addresses and sets\n+// the route table for a stack that should operate as a router.\n+func SetupRouterStack(t *testing.T, s *stack.Stack, ep1, ep2 stack.LinkEndpoint) {\n+\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d): %s\", ipv4.ProtocolNumber, err)\n+ }\n+ if err := s.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n+ t.Fatalf(\"s.SetForwardingDefaultAndAllNICs(%d): %s\", ipv6.ProtocolNumber, err)\n+ }\n+\n+ for _, setup := range []struct {\n+ nicID tcpip.NICID\n+ nicName string\n+ ep stack.LinkEndpoint\n+\n+ addresses [2]tcpip.ProtocolAddress\n+ }{\n+ {\n+ nicID: RouterNICID1,\n+ nicName: RouterNIC1Name,\n+ ep: ep1,\n+ addresses: [2]tcpip.ProtocolAddress{RouterNIC1IPv4Addr, RouterNIC1IPv6Addr},\n+ },\n+ {\n+ nicID: RouterNICID2,\n+ nicName: RouterNIC2Name,\n+ ep: ep2,\n+ addresses: [2]tcpip.ProtocolAddress{RouterNIC2IPv4Addr, RouterNIC2IPv6Addr},\n+ },\n+ } {\n+ opts := stack.NICOptions{Name: setup.nicName}\n+ if err := s.CreateNICWithOptions(setup.nicID, setup.ep, opts); err != nil {\n+ t.Fatalf(\"s.CreateNICWithOptions(%d, _, %#v): %s\", setup.nicID, opts, err)\n+ }\n+\n+ for _, addr := range setup.addresses {\n+ if err := s.AddProtocolAddress(setup.nicID, addr, stack.AddressProperties{}); err != nil {\n+ t.Fatalf(\"s.AddProtocolAddress(%d, %#v, {}): %s\", setup.nicID, addr, err)\n+ }\n+ }\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: RouterNIC1IPv4Addr.AddressWithPrefix.Subnet(),\n+ NIC: RouterNICID1,\n+ },\n+ {\n+ Destination: RouterNIC1IPv6Addr.AddressWithPrefix.Subnet(),\n+ NIC: RouterNICID1,\n+ },\n+ {\n+ Destination: RouterNIC2IPv4Addr.AddressWithPrefix.Subnet(),\n+ NIC: RouterNICID2,\n+ },\n+ {\n+ Destination: RouterNIC2IPv6Addr.AddressWithPrefix.Subnet(),\n+ NIC: RouterNICID2,\n+ },\n+ })\n+}\n+\n// SetupRoutedStacks creates the NICs, sets forwarding, adds addresses and sets\n// the route tables for the passed stacks.\nfunc SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack) {\nhost1NIC, routerNIC1 := pipe.New(LinkAddr1, LinkAddr2)\nrouterNIC2, host2NIC := pipe.New(LinkAddr3, LinkAddr4)\n+ SetupRouterStack(t, routerStack, NewEthernetEndpoint(routerNIC1), NewEthernetEndpoint(routerNIC2))\n+\n{\nopts := stack.NICOptions{Name: Host1NICName}\nif err := host1Stack.CreateNICWithOptions(Host1NICID, NewEthernetEndpoint(host1NIC), opts); err != nil {\nt.Fatalf(\"host1Stack.CreateNICWithOptions(%d, _, %#v): %s\", Host1NICID, opts, err)\n}\n}\n- {\n- opts := stack.NICOptions{Name: RouterNIC1Name}\n- if err := routerStack.CreateNICWithOptions(RouterNICID1, NewEthernetEndpoint(routerNIC1), opts); err != nil {\n- t.Fatalf(\"routerStack.CreateNICWithOptions(%d, _, %#v): %s\", RouterNICID1, opts, err)\n- }\n- }\n- {\n- opts := stack.NICOptions{Name: RouterNIC2Name}\n- if err := routerStack.CreateNICWithOptions(RouterNICID2, NewEthernetEndpoint(routerNIC2), opts); err != nil {\n- t.Fatalf(\"routerStack.CreateNICWithOptions(%d, _, %#v): %s\", RouterNICID2, opts, err)\n- }\n- }\n{\nopts := stack.NICOptions{Name: Host2NICName}\nif err := host2Stack.CreateNICWithOptions(Host2NICID, NewEthernetEndpoint(host2NIC), opts); err != nil {\n@@ -244,34 +297,15 @@ func SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.\n}\n}\n- if err := routerStack.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"routerStack.SetForwardingDefaultAndAllNICs(%d): %s\", ipv4.ProtocolNumber, err)\n- }\n- if err := routerStack.SetForwardingDefaultAndAllNICs(ipv6.ProtocolNumber, true); err != nil {\n- t.Fatalf(\"routerStack.SetForwardingDefaultAndAllNICs(%d): %s\", ipv6.ProtocolNumber, err)\n- }\n-\nif err := host1Stack.AddProtocolAddress(Host1NICID, Host1IPv4Addr, stack.AddressProperties{}); err != nil {\nt.Fatalf(\"host1Stack.AddProtocolAddress(%d, %+v, {}): %s\", Host1NICID, Host1IPv4Addr, err)\n}\n- if err := routerStack.AddProtocolAddress(RouterNICID1, RouterNIC1IPv4Addr, stack.AddressProperties{}); err != nil {\n- t.Fatalf(\"routerStack.AddProtocolAddress(%d, %+v, {}): %s\", RouterNICID1, RouterNIC1IPv4Addr, err)\n- }\n- if err := routerStack.AddProtocolAddress(RouterNICID2, RouterNIC2IPv4Addr, stack.AddressProperties{}); err != nil {\n- t.Fatalf(\"routerStack.AddProtocolAddress(%d, %+v, {}): %s\", RouterNICID2, RouterNIC2IPv4Addr, err)\n- }\nif err := host2Stack.AddProtocolAddress(Host2NICID, Host2IPv4Addr, stack.AddressProperties{}); err != nil {\nt.Fatalf(\"host2Stack.AddProtocolAddress(%d, %+v, {}): %s\", Host2NICID, Host2IPv4Addr, err)\n}\nif err := host1Stack.AddProtocolAddress(Host1NICID, Host1IPv6Addr, stack.AddressProperties{}); err != nil {\nt.Fatalf(\"host1Stack.AddProtocolAddress(%d, %+v, {}): %s\", Host1NICID, Host1IPv6Addr, err)\n}\n- if err := routerStack.AddProtocolAddress(RouterNICID1, RouterNIC1IPv6Addr, stack.AddressProperties{}); err != nil {\n- t.Fatalf(\"routerStack.AddProtocolAddress(%d, %+v, {}): %s\", RouterNICID1, RouterNIC1IPv6Addr, err)\n- }\n- if err := routerStack.AddProtocolAddress(RouterNICID2, RouterNIC2IPv6Addr, stack.AddressProperties{}); err != nil {\n- t.Fatalf(\"routerStack.AddProtocolAddress(%d, %+v, {}): %s\", RouterNICID2, RouterNIC2IPv6Addr, err)\n- }\nif err := host2Stack.AddProtocolAddress(Host2NICID, Host2IPv6Addr, stack.AddressProperties{}); err != nil {\nt.Fatalf(\"host2Stack.AddProtocolAddress(%d, %+v, {}): %s\", Host2NICID, Host2IPv6Addr, err)\n}\n@@ -296,24 +330,6 @@ func SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.\nNIC: Host1NICID,\n},\n})\n- routerStack.SetRouteTable([]tcpip.Route{\n- {\n- Destination: RouterNIC1IPv4Addr.AddressWithPrefix.Subnet(),\n- NIC: RouterNICID1,\n- },\n- {\n- Destination: RouterNIC1IPv6Addr.AddressWithPrefix.Subnet(),\n- NIC: RouterNICID1,\n- },\n- {\n- Destination: RouterNIC2IPv4Addr.AddressWithPrefix.Subnet(),\n- NIC: RouterNICID2,\n- },\n- {\n- Destination: RouterNIC2IPv6Addr.AddressWithPrefix.Subnet(),\n- NIC: RouterNICID2,\n- },\n- })\nhost2Stack.SetRouteTable([]tcpip.Route{\n{\nDestination: Host2IPv4Addr.AddressWithPrefix.Subnet(),\n"
}
] | Go | Apache License 2.0 | google/gvisor | NAT ICMPv4 errors
...so a NAT-ed connection's socket can handle ICMP errors.
Updates #5916.
PiperOrigin-RevId: 405970089 |
259,891 | 27.10.2021 15:37:20 | 25,200 | 9541a5842bf843414d872a539d32ce6e3202bf04 | rename tcp_conntrack inbound/outbound to reply/original
Connection tracking is agnostic to whether the packet is inbound or outbound. It
cares who initiated the connection. The naming can get confusing as conntrack
can track connections originating from any host.
Part of resolving | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -164,9 +164,9 @@ func (cn *conn) updateLocked(pkt *PacketBuffer, reply bool) {\n}\nif reply {\n- cn.tcb.UpdateStateInbound(tcpHeader)\n+ cn.tcb.UpdateStateReply(tcpHeader)\n} else {\n- cn.tcb.UpdateStateOutbound(tcpHeader)\n+ cn.tcb.UpdateStateOriginal(tcpHeader)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"diff": "@@ -22,8 +22,8 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n)\n-// Result is returned when the state of a TCB is updated in response to an\n-// inbound or outbound segment.\n+// Result is returned when the state of a TCB is updated in response to a\n+// segment.\ntype Result int\nconst (\n@@ -40,24 +40,24 @@ const (\n// ResultReset indicates that the connection was reset.\nResultReset\n- // ResultClosedByPeer indicates that the connection was gracefully\n- // closed, and the inbound stream was closed first.\n- ResultClosedByPeer\n+ // ResultClosedByResponder indicates that the connection was gracefully\n+ // closed, and the reply stream was closed first.\n+ ResultClosedByResponder\n- // ResultClosedBySelf indicates that the connection was gracefully\n- // closed, and the outbound stream was closed first.\n- ResultClosedBySelf\n+ // ResultClosedByOriginator indicates that the connection was gracefully\n+ // closed, and the original stream was closed first.\n+ ResultClosedByOriginator\n)\n// TCB is a TCP Control Block. It holds state necessary to keep track of a TCP\n// connection and inform the caller when the connection has been closed.\ntype TCB struct {\n- inbound stream\n- outbound stream\n+ reply stream\n+ original stream\n// State handlers.\n- handlerInbound func(*TCB, header.TCP) Result\n- handlerOutbound func(*TCB, header.TCP) Result\n+ handlerReply func(*TCB, header.TCP) Result\n+ handlerOriginal func(*TCB, header.TCP) Result\n// firstFin holds a pointer to the first stream to send a FIN.\nfirstFin *stream\n@@ -68,38 +68,38 @@ type TCB struct {\n// Init initializes the state of the TCB according to the initial SYN.\nfunc (t *TCB) Init(initialSyn header.TCP) Result {\n- t.handlerInbound = synSentStateInbound\n- t.handlerOutbound = synSentStateOutbound\n+ t.handlerReply = synSentStateReply\n+ t.handlerOriginal = synSentStateOriginal\niss := seqnum.Value(initialSyn.SequenceNumber())\n- t.outbound.una = iss\n- t.outbound.nxt = iss.Add(logicalLen(initialSyn))\n- t.outbound.end = t.outbound.nxt\n+ t.original.una = iss\n+ t.original.nxt = iss.Add(logicalLen(initialSyn))\n+ t.original.end = t.original.nxt\n// Even though \"end\" is a sequence number, we don't know the initial\n// receive sequence number yet, so we store the window size until we get\n- // a SYN from the peer.\n- t.inbound.una = 0\n- t.inbound.nxt = 0\n- t.inbound.end = seqnum.Value(initialSyn.WindowSize())\n+ // a SYN from the server.\n+ t.reply.una = 0\n+ t.reply.nxt = 0\n+ t.reply.end = seqnum.Value(initialSyn.WindowSize())\nt.state = ResultConnecting\nreturn t.state\n}\n-// UpdateStateInbound updates the state of the TCB based on the supplied inbound\n+// UpdateStateReply updates the state of the TCB based on the supplied reply\n// segment.\n-func (t *TCB) UpdateStateInbound(tcp header.TCP) Result {\n- st := t.handlerInbound(t, tcp)\n+func (t *TCB) UpdateStateReply(tcp header.TCP) Result {\n+ st := t.handlerReply(t, tcp)\nif st != ResultDrop {\nt.state = st\n}\nreturn st\n}\n-// UpdateStateOutbound updates the state of the TCB based on the supplied\n-// outbound segment.\n-func (t *TCB) UpdateStateOutbound(tcp header.TCP) Result {\n- st := t.handlerOutbound(t, tcp)\n+// UpdateStateOriginal updates the state of the TCB based on the supplied\n+// original segment.\n+func (t *TCB) UpdateStateOriginal(tcp header.TCP) Result {\n+ st := t.handlerOriginal(t, tcp)\nif st != ResultDrop {\nt.state = st\n}\n@@ -114,46 +114,47 @@ func (t *TCB) State() Result {\n// IsAlive returns true as long as the connection is established(Alive)\n// or connecting state.\nfunc (t *TCB) IsAlive() bool {\n- return !t.inbound.rstSeen && !t.outbound.rstSeen && (!t.inbound.closed() || !t.outbound.closed())\n+ return !t.reply.rstSeen && !t.original.rstSeen && (!t.reply.closed() || !t.original.closed())\n}\n-// OutboundSendSequenceNumber returns the snd.NXT for the outbound stream.\n-func (t *TCB) OutboundSendSequenceNumber() seqnum.Value {\n- return t.outbound.nxt\n+// OriginalSendSequenceNumber returns the snd.NXT for the original stream.\n+func (t *TCB) OriginalSendSequenceNumber() seqnum.Value {\n+ return t.original.nxt\n}\n-// InboundSendSequenceNumber returns the snd.NXT for the inbound stream.\n-func (t *TCB) InboundSendSequenceNumber() seqnum.Value {\n- return t.inbound.nxt\n+// ReplySendSequenceNumber returns the snd.NXT for the reply stream.\n+func (t *TCB) ReplySendSequenceNumber() seqnum.Value {\n+ return t.reply.nxt\n}\n// adapResult modifies the supplied \"Result\" according to the state of the TCB;\n// if r is anything other than \"Alive\", or if one of the streams isn't closed\n// yet, it is returned unmodified. Otherwise it's converted to either\n-// ClosedBySelf or ClosedByPeer depending on which stream was closed first.\n+// ClosedByOriginator or ClosedByResponder depending on which stream was closed\n+// first.\nfunc (t *TCB) adaptResult(r Result) Result {\n// Check the unmodified case.\n- if r != ResultAlive || !t.inbound.closed() || !t.outbound.closed() {\n+ if r != ResultAlive || !t.reply.closed() || !t.original.closed() {\nreturn r\n}\n// Find out which was closed first.\n- if t.firstFin == &t.outbound {\n- return ResultClosedBySelf\n+ if t.firstFin == &t.original {\n+ return ResultClosedByOriginator\n}\n- return ResultClosedByPeer\n+ return ResultClosedByResponder\n}\n-// synSentStateInbound is the state handler for inbound segments when the\n+// synSentStateReply is the state handler for reply segments when the\n// connection is in SYN-SENT state.\n-func synSentStateInbound(t *TCB, tcp header.TCP) Result {\n+func synSentStateReply(t *TCB, tcp header.TCP) Result {\nflags := tcp.Flags()\nackPresent := flags&header.TCPFlagAck != 0\nack := seqnum.Value(tcp.AckNumber())\n// Ignore segment if ack is present but not acceptable.\n- if ackPresent && !(ack-1).InRange(t.outbound.una, t.outbound.nxt) {\n+ if ackPresent && !(ack-1).InRange(t.original.una, t.original.nxt) {\nreturn ResultConnecting\n}\n@@ -162,7 +163,7 @@ func synSentStateInbound(t *TCB, tcp header.TCP) Result {\n// implicitly acceptable).\nif flags&header.TCPFlagRst != 0 {\nif ackPresent {\n- t.inbound.rstSeen = true\n+ t.reply.rstSeen = true\nreturn ResultReset\n}\nreturn ResultConnecting\n@@ -175,62 +176,62 @@ func synSentStateInbound(t *TCB, tcp header.TCP) Result {\n// Update state informed by this SYN.\nirs := seqnum.Value(tcp.SequenceNumber())\n- t.inbound.una = irs\n- t.inbound.nxt = irs.Add(logicalLen(tcp))\n- t.inbound.end += irs\n+ t.reply.una = irs\n+ t.reply.nxt = irs.Add(logicalLen(tcp))\n+ t.reply.end += irs\n- t.outbound.end = t.outbound.una.Add(seqnum.Size(tcp.WindowSize()))\n+ t.original.end = t.original.una.Add(seqnum.Size(tcp.WindowSize()))\n// If the ACK was set (it is acceptable), update our unacknowledgement\n// tracking.\nif ackPresent {\n- // Advance the \"una\" and \"end\" indices of the outbound stream.\n- if t.outbound.una.LessThan(ack) {\n- t.outbound.una = ack\n+ // Advance the \"una\" and \"end\" indices of the original stream.\n+ if t.original.una.LessThan(ack) {\n+ t.original.una = ack\n}\n- if end := ack.Add(seqnum.Size(tcp.WindowSize())); t.outbound.end.LessThan(end) {\n- t.outbound.end = end\n+ if end := ack.Add(seqnum.Size(tcp.WindowSize())); t.original.end.LessThan(end) {\n+ t.original.end = end\n}\n}\n// Update handlers so that new calls will be handled by new state.\n- t.handlerInbound = allOtherInbound\n- t.handlerOutbound = allOtherOutbound\n+ t.handlerReply = allOtherReply\n+ t.handlerOriginal = allOtherOriginal\nreturn ResultAlive\n}\n-// synSentStateOutbound is the state handler for outbound segments when the\n+// synSentStateOriginal is the state handler for original segments when the\n// connection is in SYN-SENT state.\n-func synSentStateOutbound(t *TCB, tcp header.TCP) Result {\n- // Drop outbound segments that aren't retransmits of the original one.\n+func synSentStateOriginal(t *TCB, tcp header.TCP) Result {\n+ // Drop original segments that aren't retransmits of the original one.\nif tcp.Flags() != header.TCPFlagSyn ||\n- tcp.SequenceNumber() != uint32(t.outbound.una) {\n+ tcp.SequenceNumber() != uint32(t.original.una) {\nreturn ResultDrop\n}\n// Update the receive window. We only remember the largest value seen.\n- if wnd := seqnum.Value(tcp.WindowSize()); wnd > t.inbound.end {\n- t.inbound.end = wnd\n+ if wnd := seqnum.Value(tcp.WindowSize()); wnd > t.reply.end {\n+ t.reply.end = wnd\n}\nreturn ResultConnecting\n}\n-// update updates the state of inbound and outbound streams, given the supplied\n-// inbound segment. For outbound segments, this same function can be called with\n-// swapped inbound/outbound streams.\n-func update(tcp header.TCP, inbound, outbound *stream, firstFin **stream) Result {\n+// update updates the state of reply and original streams, given the supplied\n+// reply segment. For original segments, this same function can be called with\n+// swapped reply/original streams.\n+func update(tcp header.TCP, reply, original *stream, firstFin **stream) Result {\n// Ignore segments out of the window.\ns := seqnum.Value(tcp.SequenceNumber())\n- if !inbound.acceptable(s, dataLen(tcp)) {\n+ if !reply.acceptable(s, dataLen(tcp)) {\nreturn ResultAlive\n}\nflags := tcp.Flags()\nif flags&header.TCPFlagRst != 0 {\n- inbound.rstSeen = true\n+ reply.rstSeen = true\nreturn ResultReset\n}\n@@ -242,49 +243,49 @@ func update(tcp header.TCP, inbound, outbound *stream, firstFin **stream) Result\n// Ignore segments that acknowledge not yet sent data.\nack := seqnum.Value(tcp.AckNumber())\n- if outbound.nxt.LessThan(ack) {\n+ if original.nxt.LessThan(ack) {\nreturn ResultAlive\n}\n- // Advance the \"una\" and \"end\" indices of the outbound stream.\n- if outbound.una.LessThan(ack) {\n- outbound.una = ack\n+ // Advance the \"una\" and \"end\" indices of the original stream.\n+ if original.una.LessThan(ack) {\n+ original.una = ack\n}\n- if end := ack.Add(seqnum.Size(tcp.WindowSize())); outbound.end.LessThan(end) {\n- outbound.end = end\n+ if end := ack.Add(seqnum.Size(tcp.WindowSize())); original.end.LessThan(end) {\n+ original.end = end\n}\n- // Advance the \"nxt\" index of the inbound stream.\n+ // Advance the \"nxt\" index of the reply stream.\nend := s.Add(logicalLen(tcp))\n- if inbound.nxt.LessThan(end) {\n- inbound.nxt = end\n+ if reply.nxt.LessThan(end) {\n+ reply.nxt = end\n}\n// Note the index of the FIN segment. And stash away a pointer to the\n// first stream to see a FIN.\n- if flags&header.TCPFlagFin != 0 && !inbound.finSeen {\n- inbound.finSeen = true\n- inbound.fin = end - 1\n+ if flags&header.TCPFlagFin != 0 && !reply.finSeen {\n+ reply.finSeen = true\n+ reply.fin = end - 1\nif *firstFin == nil {\n- *firstFin = inbound\n+ *firstFin = reply\n}\n}\nreturn ResultAlive\n}\n-// allOtherInbound is the state handler for inbound segments in all states\n+// allOtherReply is the state handler for reply segments in all states\n// except SYN-SENT.\n-func allOtherInbound(t *TCB, tcp header.TCP) Result {\n- return t.adaptResult(update(tcp, &t.inbound, &t.outbound, &t.firstFin))\n+func allOtherReply(t *TCB, tcp header.TCP) Result {\n+ return t.adaptResult(update(tcp, &t.reply, &t.original, &t.firstFin))\n}\n-// allOtherOutbound is the state handler for outbound segments in all states\n+// allOtherOriginal is the state handler for original segments in all states\n// except SYN-SENT.\n-func allOtherOutbound(t *TCB, tcp header.TCP) Result {\n- return t.adaptResult(update(tcp, &t.outbound, &t.inbound, &t.firstFin))\n+func allOtherOriginal(t *TCB, tcp header.TCP) Result {\n+ return t.adaptResult(update(tcp, &t.original, &t.reply, &t.firstFin))\n}\n// streams holds the state of a TCP unidirectional stream.\n@@ -345,7 +346,7 @@ func logicalLen(tcp header.TCP) seqnum.Size {\n// IsEmpty returns true if tcb is not initialized.\nfunc (t *TCB) IsEmpty() bool {\n- if t.inbound != (stream{}) || t.outbound != (stream{}) {\n+ if t.reply != (stream{}) || t.original != (stream{}) {\nreturn false\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack_test.go",
"new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack_test.go",
"diff": "@@ -46,7 +46,7 @@ func connected(t *testing.T, iss, irs uint32, isw, irw uint16) *tcpconntrack.TCB\nWindowSize: isw,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -59,7 +59,7 @@ func connected(t *testing.T, iss, irs uint32, isw, irw uint16) *tcpconntrack.TCB\nWindowSize: irw,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -89,7 +89,7 @@ func TestConnectionRefused(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -117,7 +117,7 @@ func TestConnectionRefusedInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -130,7 +130,7 @@ func TestConnectionRefusedInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -158,7 +158,7 @@ func TestConnectionResetInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -170,7 +170,7 @@ func TestConnectionResetInSynRcvd(t *testing.T) {\nFlags: header.TCPFlagRst,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -190,7 +190,7 @@ func TestRetransmitOnSynSent(t *testing.T) {\ntcb.Init(tcp)\n// Retransmit the same SYN.\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultConnecting {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultConnecting {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultConnecting)\n}\n}\n@@ -218,7 +218,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -231,7 +231,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -244,12 +244,12 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n-func TestClosedBySelf(t *testing.T) {\n+func TestClosedByOriginator(t *testing.T) {\ntcb := connected(t, 1234, 789, 30000, 50000)\n// Send FIN.\n@@ -262,7 +262,7 @@ func TestClosedBySelf(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -275,7 +275,7 @@ func TestClosedBySelf(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -288,12 +288,12 @@ func TestClosedBySelf(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultClosedBySelf {\n- t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedBySelf)\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultClosedByOriginator {\n+ t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByOriginator)\n}\n}\n-func TestClosedByPeer(t *testing.T) {\n+func TestClosedByResponder(t *testing.T) {\ntcb := connected(t, 1234, 789, 30000, 50000)\n// Receive FIN.\n@@ -306,7 +306,7 @@ func TestClosedByPeer(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -319,7 +319,7 @@ func TestClosedByPeer(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -332,12 +332,12 @@ func TestClosedByPeer(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultClosedByPeer {\n- t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByPeer)\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultClosedByResponder {\n+ t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByResponder)\n}\n}\n-func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\n+func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nsseq := uint32(1234)\nrseq := uint32(789)\ntcb := connected(t, sseq, rseq, 30000, 50000)\n@@ -358,7 +358,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\n})\nsseq += uint32(len(tcp)) - header.TCPMinimumSize\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -371,7 +371,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -387,7 +387,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\n})\nrseq += uint32(len(tcp)) - header.TCPMinimumSize\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -400,7 +400,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -416,7 +416,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\n})\nsseq++\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -430,7 +430,7 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\n})\nrseq++\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -443,8 +443,8 @@ func TestSendAndReceiveDataClosedBySelf(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultClosedBySelf {\n- t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedBySelf)\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultClosedByOriginator {\n+ t.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByOriginator)\n}\n}\n@@ -476,7 +476,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultConnecting {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultConnecting {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -492,7 +492,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateInbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -505,7 +505,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOutbound(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | rename tcp_conntrack inbound/outbound to reply/original
Connection tracking is agnostic to whether the packet is inbound or outbound. It
cares who initiated the connection. The naming can get confusing as conntrack
can track connections originating from any host.
Part of resolving #6736.
PiperOrigin-RevId: 405997540 |
259,985 | 27.10.2021 17:58:29 | 25,200 | 6078d26588c021d4b78501ad25cb725ff2db797e | Sychronize access to cpuset controller bitmaps.
Reported-by:
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -36,6 +37,8 @@ type cpusetController struct {\nmaxCpus uint32\nmaxMems uint32\n+ mu sync.Mutex `state:\"nosave\"`\n+\ncpus *bitmap.Bitmap\nmems *bitmap.Bitmap\n}\n@@ -71,6 +74,8 @@ type cpusData struct {\n// Generate implements vfs.DynamicBytesSource.Generate.\nfunc (d *cpusData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nfmt.Fprintf(buf, \"%s\\n\", formatBitmap(d.c.cpus))\nreturn nil\n}\n@@ -101,6 +106,8 @@ func (d *cpusData) Write(ctx context.Context, src usermem.IOSequence, offset int\nreturn 0, linuxerr.EINVAL\n}\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nd.c.cpus = b\nreturn int64(n), nil\n}\n@@ -112,6 +119,8 @@ type memsData struct {\n// Generate implements vfs.DynamicBytesSource.Generate.\nfunc (d *memsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nfmt.Fprintf(buf, \"%s\\n\", formatBitmap(d.c.mems))\nreturn nil\n}\n@@ -142,6 +151,8 @@ func (d *memsData) Write(ctx context.Context, src usermem.IOSequence, offset int\nreturn 0, linuxerr.EINVAL\n}\n+ d.c.mu.Lock()\n+ defer d.c.mu.Unlock()\nd.c.mems = b\nreturn int64(n), nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Sychronize access to cpuset controller bitmaps.
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 406024052 |
260,004 | 28.10.2021 19:33:32 | 25,200 | 1953d2ad28d405a3ab028feba7b6fca18339e9be | NAT ICMPv6 errors
...so a NAT-ed connection's socket can handle ICMP errors.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -209,6 +209,22 @@ type bucket struct {\ntuples tupleList\n}\n+func getEmbeddedNetAndTransHeaders(pkt *PacketBuffer, netHdrLength int, netHdrFunc func([]byte) header.Network) (header.Network, header.ChecksummableTransport, bool) {\n+ switch pkt.tuple.id().transProto {\n+ case header.TCPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(netHdrLength + header.TCPMinimumSize); ok {\n+ netHeader := netHdrFunc(netAndTransHeader)\n+ return netHeader, header.TCP(netHeader.Payload()), true\n+ }\n+ case header.UDPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(netHdrLength + header.UDPMinimumSize); ok {\n+ netHeader := netHdrFunc(netAndTransHeader)\n+ return netHeader, header.UDP(netHeader.Payload()), true\n+ }\n+ }\n+ return nil, nil, false\n+}\n+\nfunc getHeaders(pkt *PacketBuffer) (netHdr header.Network, transHdr header.ChecksummableTransport, isICMPError bool, ok bool) {\nswitch pkt.TransportProtocolNumber {\ncase header.TCPProtocolNumber:\n@@ -225,29 +241,31 @@ func getHeaders(pkt *PacketBuffer) (netHdr header.Network, transHdr header.Check\npanic(fmt.Sprintf(\"should have a valid IPv4 packet; only have %d bytes, want at least %d bytes\", pkt.Data().Size(), header.IPv4MinimumSize))\n}\n- ipv4 := header.IPv4(h)\n- if ipv4.HeaderLength() > header.IPv4MinimumSize {\n+ if header.IPv4(h).HeaderLength() > header.IPv4MinimumSize {\n// TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\npanic(\"should have dropped packets with IPv4 options\")\n}\n- switch pkt.tuple.id().transProto {\n- case header.TCPProtocolNumber:\n- // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n- netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.TCPMinimumSize)\n- if !ok {\n- return nil, nil, false, false\n+ if netHdr, transHdr, ok := getEmbeddedNetAndTransHeaders(pkt, header.IPv4MinimumSize, func(b []byte) header.Network { return header.IPv4(b) }); ok {\n+ return netHdr, transHdr, true, true\n}\n- netHeader := header.IPv4(netAndTransHeader)\n- return netHeader, header.TCP(netHeader.Payload()), true, true\n- case header.UDPProtocolNumber:\n- // TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n- netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.UDPMinimumSize)\n+ case header.ICMPv6ProtocolNumber:\n+ h, ok := pkt.Data().PullUp(header.IPv6MinimumSize)\nif !ok {\n- return nil, nil, false, false\n+ panic(fmt.Sprintf(\"should have a valid IPv6 packet; only have %d bytes, want at least %d bytes\", pkt.Data().Size(), header.IPv6MinimumSize))\n+ }\n+\n+ // We do not support extension headers in ICMP errors so the next header\n+ // in the IPv6 packet should be a tracked protocol if we reach this point.\n+ //\n+ // TODO(https://gvisor.dev/issue/6789): Support extension headers.\n+ transProto := pkt.tuple.id().transProto\n+ if got := header.IPv6(h).TransportProtocol(); got != transProto {\n+ panic(fmt.Sprintf(\"got TransportProtocol() = %d, want = %d\", got, transProto))\n}\n- netHeader := header.IPv4(netAndTransHeader)\n- return netHeader, header.UDP(netHeader.Payload()), true, true\n+\n+ if netHdr, transHdr, ok := getEmbeddedNetAndTransHeaders(pkt, header.IPv6MinimumSize, func(b []byte) header.Network { return header.IPv6(b) }); ok {\n+ return netHdr, transHdr, true, true\n}\n}\n@@ -265,7 +283,12 @@ func getTupleIDForRegularPacket(netHdr header.Network, netProto tcpip.NetworkPro\n}\n}\n-func getTupleIDForPacketInICMPError(netHdr header.Network, netProto tcpip.NetworkProtocolNumber, transHdr header.Transport, transProto tcpip.TransportProtocolNumber) tupleID {\n+func getTupleIDForPacketInICMPError(pkt *PacketBuffer, netHdrFunc func([]byte) header.Network, netProto tcpip.NetworkProtocolNumber, netLen int, transProto tcpip.TransportProtocolNumber) (tupleID, bool) {\n+ switch transProto {\n+ case header.TCPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(netLen + header.TCPMinimumSize); ok {\n+ netHdr := netHdrFunc(netAndTransHeader)\n+ transHdr := header.TCP(netHdr.Payload())\nreturn tupleID{\nsrcAddr: netHdr.DestinationAddress(),\nsrcPort: transHdr.DestinationPort(),\n@@ -273,7 +296,24 @@ func getTupleIDForPacketInICMPError(netHdr header.Network, netProto tcpip.Networ\ndstPort: transHdr.SourcePort(),\ntransProto: transProto,\nnetProto: netProto,\n+ }, true\n}\n+ case header.UDPProtocolNumber:\n+ if netAndTransHeader, ok := pkt.Data().PullUp(netLen + header.UDPMinimumSize); ok {\n+ netHdr := netHdrFunc(netAndTransHeader)\n+ transHdr := header.UDP(netHdr.Payload())\n+ return tupleID{\n+ srcAddr: netHdr.DestinationAddress(),\n+ srcPort: transHdr.DestinationPort(),\n+ dstAddr: netHdr.SourceAddress(),\n+ dstPort: transHdr.SourcePort(),\n+ transProto: transProto,\n+ netProto: netProto,\n+ }, true\n+ }\n+ }\n+\n+ return tupleID{}, false\n}\nfunc getTupleID(pkt *PacketBuffer) (tid tupleID, isICMPError bool, ok bool) {\n@@ -308,17 +348,30 @@ func getTupleID(pkt *PacketBuffer) (tid tupleID, isICMPError bool, ok bool) {\n// TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\nreturn tupleID{}, false, false\n}\n- switch ipv4.TransportProtocol() {\n- case header.TCPProtocolNumber:\n- if netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.TCPMinimumSize); ok {\n- netHdr := header.IPv4(netAndTransHeader)\n- return getTupleIDForPacketInICMPError(netHdr, header.IPv4ProtocolNumber, header.TCP(netHdr.Payload()), header.TCPProtocolNumber), true, true\n+\n+ if tid, ok := getTupleIDForPacketInICMPError(pkt, func(b []byte) header.Network { return header.IPv4(b) }, header.IPv4ProtocolNumber, header.IPv4MinimumSize, ipv4.TransportProtocol()); ok {\n+ return tid, true, true\n}\n- case header.UDPProtocolNumber:\n- if netAndTransHeader, ok := pkt.Data().PullUp(header.IPv4MinimumSize + header.UDPMinimumSize); ok {\n- netHdr := header.IPv4(netAndTransHeader)\n- return getTupleIDForPacketInICMPError(netHdr, header.IPv4ProtocolNumber, header.UDP(netHdr.Payload()), header.UDPProtocolNumber), true, true\n+ case header.ICMPv6ProtocolNumber:\n+ icmp := header.ICMPv6(pkt.TransportHeader().View())\n+ if len(icmp) < header.ICMPv6MinimumSize {\n+ return tupleID{}, false, false\n}\n+\n+ switch icmp.Type() {\n+ case header.ICMPv6DstUnreachable, header.ICMPv6PacketTooBig, header.ICMPv6TimeExceeded, header.ICMPv6ParamProblem:\n+ default:\n+ return tupleID{}, false, false\n+ }\n+\n+ h, ok := pkt.Data().PullUp(header.IPv6MinimumSize)\n+ if !ok {\n+ return tupleID{}, false, false\n+ }\n+\n+ // TODO(https://gvisor.dev/issue/6789): Handle extension headers.\n+ if tid, ok := getTupleIDForPacketInICMPError(pkt, func(b []byte) header.Network { return header.IPv6(b) }, header.IPv6ProtocolNumber, header.IPv6MinimumSize, header.IPv6(h).TransportProtocol()); ok {\n+ return tid, true, true\n}\n}\n@@ -624,6 +677,33 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\n} else {\nnetwork.SetSourceAddressWithChecksumUpdate(tid.dstAddr)\n}\n+ case header.ICMPv6ProtocolNumber:\n+ network := header.IPv6(pkt.NetworkHeader().View())\n+ srcAddr := network.SourceAddress()\n+ dstAddr := network.DestinationAddress()\n+ if dnat {\n+ dstAddr = tid.srcAddr\n+ } else {\n+ srcAddr = tid.dstAddr\n+ }\n+\n+ icmp := header.ICMPv6(pkt.TransportHeader().View())\n+ // TODO(https://gvisor.dev/issue/6788): Incrementally update ICMP checksum.\n+ icmp.SetChecksum(0)\n+ payload := pkt.Data()\n+ icmp.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\n+ Header: icmp,\n+ Src: srcAddr,\n+ Dst: dstAddr,\n+ PayloadCsum: payload.AsRange().Checksum(),\n+ PayloadLen: payload.Size(),\n+ }))\n+\n+ if dnat {\n+ network.SetDestinationAddress(dstAddr)\n+ } else {\n+ network.SetSourceAddress(srcAddr)\n+ }\n}\nreturn true\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1809,6 +1809,17 @@ func TestNATICMPError(t *testing.T) {\nip.SetChecksum(^ip.CalculateChecksum())\n}\n+ ip6Hdr := func(v buffer.View, payloadLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\n+ ip := header.IPv6(v)\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLen),\n+ TransportProtocol: transProto,\n+ HopLimit: 64,\n+ SrcAddr: srcAddr,\n+ DstAddr: dstAddr,\n+ })\n+ }\n+\ntests := []struct {\nname string\nnetProto tcpip.NetworkProtocolNumber\n@@ -1960,6 +1971,150 @@ func TestNATICMPError(t *testing.T) {\n},\n},\n},\n+ {\n+ name: \"IPv6\",\n+ netProto: ipv6.ProtocolNumber,\n+ host1Addr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ icmpError: func(t *testing.T, original buffer.View, icmpType uint8) buffer.View {\n+ payloadLen := header.ICMPv6MinimumSize + len(original)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + payloadLen)\n+ icmp := header.ICMPv6(hdr.Prepend(payloadLen))\n+ icmp.SetType(header.ICMPv6Type(icmpType))\n+ if n := copy(icmp.Payload(), original); n != len(original) {\n+ t.Fatalf(\"got copy(...) = %d, want = %d\", n, len(original))\n+ }\n+ icmp.SetChecksum(0)\n+ icmp.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\n+ Header: icmp,\n+ Src: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ Dst: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n+ }))\n+ ip6Hdr(hdr.Prepend(header.IPv6MinimumSize),\n+ payloadLen,\n+ header.ICMPv6ProtocolNumber,\n+ utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ },\n+ decrementTTL: func(v buffer.View) {\n+ ip := header.IPv6(v)\n+ ip.SetHopLimit(ip.HopLimit() - 1)\n+ },\n+ checkNATedError: func(t *testing.T, v buffer.View, original buffer.View, icmpType uint8) {\n+ checker.IPv6(t, v,\n+ checker.SrcAddr(utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host2IPv6Addr.AddressWithPrefix.Address),\n+ checker.ICMPv6(\n+ checker.ICMPv6Type(header.ICMPv6Type(icmpType)),\n+ checker.ICMPv6Payload(original),\n+ ),\n+ )\n+ },\n+ transportTypes: []transportTypeTest{\n+ {\n+ name: \"UDP\",\n+ proto: header.UDPProtocolNumber,\n+ buf: func() buffer.View {\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + header.UDPMinimumSize)\n+ udp := header.UDP(hdr.Prepend(header.UDPMinimumSize))\n+ udp.SetSourcePort(srcPort)\n+ udp.SetDestinationPort(dstPort)\n+ udp.SetChecksum(0)\n+ udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.UDPProtocolNumber,\n+ utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ uint16(len(udp)),\n+ )))\n+ ip6Hdr(hdr.Prepend(header.IPv6MinimumSize),\n+ header.UDPMinimumSize,\n+ header.UDPProtocolNumber,\n+ utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ }(),\n+ checkNATed: func(t *testing.T, v buffer.View) {\n+ checker.IPv6(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv6Addr.AddressWithPrefix.Address),\n+ checker.UDP(\n+ checker.SrcPort(srcPort),\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+ },\n+ },\n+ {\n+ name: \"TCP\",\n+ proto: header.TCPProtocolNumber,\n+ buf: func() buffer.View {\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + header.TCPMinimumSize)\n+ tcp := header.TCP(hdr.Prepend(header.TCPMinimumSize))\n+ tcp.SetSourcePort(srcPort)\n+ tcp.SetDestinationPort(dstPort)\n+ tcp.SetDataOffset(header.TCPMinimumSize)\n+ tcp.SetChecksum(0)\n+ tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.TCPProtocolNumber,\n+ utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ uint16(len(tcp)),\n+ )))\n+ ip6Hdr(hdr.Prepend(header.IPv6MinimumSize),\n+ header.TCPMinimumSize,\n+ header.TCPProtocolNumber,\n+ utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n+ )\n+ return hdr.View()\n+ }(),\n+ checkNATed: func(t *testing.T, v buffer.View) {\n+ checker.IPv6(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv6Addr.AddressWithPrefix.Address),\n+ checker.TCP(\n+ checker.SrcPort(srcPort),\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+ },\n+ },\n+ },\n+ icmpTypes: []icmpTypeTest{\n+ {\n+ name: \"Destination Unreachable\",\n+ val: uint8(header.ICMPv6DstUnreachable),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Packet Too Big\",\n+ val: uint8(header.ICMPv6PacketTooBig),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Time Exceeded\",\n+ val: uint8(header.ICMPv6TimeExceeded),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Parameter Problem\",\n+ val: uint8(header.ICMPv6ParamProblem),\n+ expectResponse: true,\n+ },\n+ {\n+ name: \"Echo Request\",\n+ val: uint8(header.ICMPv6EchoRequest),\n+ expectResponse: false,\n+ },\n+ {\n+ name: \"Echo Reply\",\n+ val: uint8(header.ICMPv6EchoReply),\n+ expectResponse: false,\n+ },\n+ },\n+ },\n}\nfor _, test := range tests {\n"
}
] | Go | Apache License 2.0 | google/gvisor | NAT ICMPv6 errors
...so a NAT-ed connection's socket can handle ICMP errors.
Updates #5916.
PiperOrigin-RevId: 406270868 |
260,029 | 31.10.2021 17:40:02 | -19,080 | 40bf5aa790004178ad315328e4d75bf9af0a4451 | Update REDME.md
Grammar correction. | [
{
"change_type": "MODIFY",
"old_path": "g3doc/README.md",
"new_path": "g3doc/README.md",
"diff": "@@ -23,7 +23,7 @@ links below to see detailed instructions for each of them:\ngVisor provides a virtualized environment in order to sandbox containers. The\nsystem interfaces normally implemented by the host kernel are moved into a\n-distinct, per-sandbox application kernel in order to minimize the risk of an\n+distinct, per-sandbox application kernel in order to minimize the risk of a\ncontainer escape exploit. gVisor does not introduce large fixed overheads\nhowever, and still retains a process-like model with respect to resource\nutilization.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update REDME.md
Grammar correction. |
259,858 | 01.11.2021 16:05:18 | 25,200 | 9776edb3fa9e67a28182aedc9342ef9c1b556d7c | Move ThreadGroupIDFromContext to kernel/auth.
This function doesn't belong in the global context package. Move to a more
suitable package to break the dependency cycle. | [
{
"change_type": "MODIFY",
"old_path": "pkg/context/context.go",
"new_path": "pkg/context/context.go",
"diff": "@@ -29,26 +29,6 @@ import (\n\"gvisor.dev/gvisor/pkg/log\"\n)\n-type contextID int\n-\n-// Globally accessible values from a context. These keys are defined in the\n-// context package to resolve dependency cycles by not requiring the caller to\n-// import packages usually required to get these information.\n-const (\n- // CtxThreadGroupID is the current thread group ID when a context represents\n- // a task context. The value is represented as an int32.\n- CtxThreadGroupID contextID = iota\n-)\n-\n-// ThreadGroupIDFromContext returns the current thread group ID when ctx\n-// represents a task context.\n-func ThreadGroupIDFromContext(ctx Context) (tgid int32, ok bool) {\n- if tgid := ctx.Value(CtxThreadGroupID); tgid != nil {\n- return tgid.(int32), true\n- }\n- return 0, false\n-}\n-\n// A Context represents a thread of execution (hereafter \"goroutine\" to reflect\n// Go idiosyncrasy). It carries state associated with the goroutine across API\n// boundaries.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/auth/context.go",
"new_path": "pkg/sentry/kernel/auth/context.go",
"diff": "@@ -24,6 +24,10 @@ type contextID int\nconst (\n// CtxCredentials is a Context.Value key for Credentials.\nCtxCredentials contextID = iota\n+\n+ // CtxThreadGroupID is the current thread group ID when a context represents\n+ // a task context. The value is represented as an int32.\n+ CtxThreadGroupID contextID = iota\n)\n// CredentialsFromContext returns a copy of the Credentials used by ctx, or a\n@@ -35,6 +39,15 @@ func CredentialsFromContext(ctx context.Context) *Credentials {\nreturn NewAnonymousCredentials()\n}\n+// ThreadGroupIDFromContext returns the current thread group ID when ctx\n+// represents a task context.\n+func ThreadGroupIDFromContext(ctx context.Context) (tgid int32, ok bool) {\n+ if tgid := ctx.Value(CtxThreadGroupID); tgid != nil {\n+ return tgid.(int32), true\n+ }\n+ return 0, false\n+}\n+\n// ContextWithCredentials returns a copy of ctx carrying creds.\nfunc ContextWithCredentials(ctx context.Context, creds *Credentials) context.Context {\nreturn &authContext{ctx, creds}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/mq/mq.go",
"new_path": "pkg/sentry/kernel/mq/mq.go",
"diff": "@@ -399,7 +399,7 @@ func (q *Queue) Flush(ctx context.Context) {\nq.mu.Lock()\ndefer q.mu.Unlock()\n- pid, ok := context.ThreadGroupIDFromContext(ctx)\n+ pid, ok := auth.ThreadGroupIDFromContext(ctx)\nif ok {\nif q.subscriber != nil && pid == q.subscriber.pid {\nq.subscriber = nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/shm/shm.go",
"new_path": "pkg/sentry/kernel/shm/shm.go",
"diff": "@@ -444,7 +444,7 @@ func (s *Shm) AddMapping(ctx context.Context, _ memmap.MappingSpace, _ hostarch.\ns.mu.Lock()\ndefer s.mu.Unlock()\ns.attachTime = ktime.NowFromContext(ctx)\n- if pid, ok := context.ThreadGroupIDFromContext(ctx); ok {\n+ if pid, ok := auth.ThreadGroupIDFromContext(ctx); ok {\ns.lastAttachDetachPID = pid\n} else {\n// AddMapping is called during a syscall, so ctx should always be a task\n@@ -468,7 +468,7 @@ func (s *Shm) RemoveMapping(ctx context.Context, _ memmap.MappingSpace, _ hostar\n// If called from a non-task context we also won't have a threadgroup\n// id. Silently skip updating the lastAttachDetachPid in that case.\n- if pid, ok := context.ThreadGroupIDFromContext(ctx); ok {\n+ if pid, ok := auth.ThreadGroupIDFromContext(ctx); ok {\ns.lastAttachDetachPID = pid\n} else {\nlog.Debugf(\"Couldn't obtain pid when removing mapping to %s, not updating the last detach pid.\", s.debugLocked())\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_context.go",
"new_path": "pkg/sentry/kernel/task_context.go",
"diff": "@@ -86,7 +86,7 @@ func (t *Task) contextValue(key interface{}, isTaskGoroutine bool) interface{} {\nreturn t\ncase auth.CtxCredentials:\nreturn t.creds.Load()\n- case context.CtxThreadGroupID:\n+ case auth.CtxThreadGroupID:\nreturn int32(t.tg.ID())\ncase fs.CtxRoot:\nif !isTaskGoroutine {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move ThreadGroupIDFromContext to kernel/auth.
This function doesn't belong in the global context package. Move to a more
suitable package to break the dependency cycle.
PiperOrigin-RevId: 406942122 |
259,907 | 01.11.2021 16:48:16 | 25,200 | 58017e655399384afed2cedea0e269cb1ad2dd7e | Handle UMOUNT_NOFOLLOW in VFS2 umount(2).
Reported-by:
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/mount.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/mount.go",
"diff": "@@ -136,14 +136,14 @@ func Umount2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\nif err != nil {\nreturn 0, nil, err\n}\n- tpop, err := getTaskPathOperation(t, linux.AT_FDCWD, path, disallowEmptyPath, nofollowFinalSymlink)\n+ tpop, err := getTaskPathOperation(t, linux.AT_FDCWD, path, disallowEmptyPath, shouldFollowFinalSymlink(flags&linux.UMOUNT_NOFOLLOW == 0))\nif err != nil {\nreturn 0, nil, err\n}\ndefer tpop.Release(t)\nopts := vfs.UmountOptions{\n- Flags: uint32(flags),\n+ Flags: uint32(flags &^ linux.UMOUNT_NOFOLLOW),\n}\nreturn 0, nil, t.Kernel().VFS().UmountAt(t, creds, &tpop.pop, &opts)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mount.cc",
"new_path": "test/syscalls/linux/mount.cc",
"diff": "@@ -115,6 +115,40 @@ TEST(MountTest, OpenFileBusy) {\nEXPECT_THAT(umount(dir.path().c_str()), SyscallFailsWithErrno(EBUSY));\n}\n+TEST(MountTest, UmountNoFollow) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n+\n+ auto const dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+\n+ auto const mountPoint = NewTempAbsPathInDir(dir.path());\n+ ASSERT_THAT(mkdir(mountPoint.c_str(), 0777), SyscallSucceeds());\n+\n+ // Create a symlink in dir which will point to the actual mountpoint.\n+ const std::string symlinkInDir = NewTempAbsPathInDir(dir.path());\n+ EXPECT_THAT(symlink(mountPoint.c_str(), symlinkInDir.c_str()),\n+ SyscallSucceeds());\n+\n+ // Create a symlink to the dir.\n+ const std::string symlinkToDir = NewTempAbsPath();\n+ EXPECT_THAT(symlink(dir.path().c_str(), symlinkToDir.c_str()),\n+ SyscallSucceeds());\n+\n+ // Should fail with ELOOP when UMOUNT_NOFOLLOW is specified and the last\n+ // component is a symlink.\n+ auto mount = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mount(\"\", mountPoint, \"tmpfs\", 0, \"mode=0700\", 0));\n+ EXPECT_THAT(umount2(symlinkInDir.c_str(), UMOUNT_NOFOLLOW),\n+ SyscallFailsWithErrno(EINVAL));\n+ EXPECT_THAT(unlink(symlinkInDir.c_str()), SyscallSucceeds());\n+\n+ // UMOUNT_NOFOLLOW should only apply to the last path component. A symlink in\n+ // non-last path component should be just fine.\n+ EXPECT_THAT(umount2(JoinPath(symlinkToDir, Basename(mountPoint)).c_str(),\n+ UMOUNT_NOFOLLOW),\n+ SyscallSucceeds());\n+ mount.Release();\n+}\n+\nTEST(MountTest, UmountDetach) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle UMOUNT_NOFOLLOW in VFS2 umount(2).
Reported-by: [email protected]
Reported-by: [email protected]
PiperOrigin-RevId: 406951359 |
259,892 | 31.10.2021 16:33:32 | -7,200 | a0849e657836cc76fc94e09bcae0755944b46a5c | copy PERM ARP entries from namespace on boot
copy and setup PERMANENT (static) ARP entries
from CNI namespace to the sandbox
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/network.go",
"new_path": "runsc/boot/network.go",
"diff": "@@ -78,6 +78,11 @@ type DefaultRoute struct {\nName string\n}\n+type Neighbor struct {\n+ IP net.IP\n+ HardwareAddr net.HardwareAddr\n+}\n+\n// FDBasedLink configures an fd-based link.\ntype FDBasedLink struct {\nName string\n@@ -90,6 +95,7 @@ type FDBasedLink struct {\nRXChecksumOffload bool\nLinkAddress net.HardwareAddr\nQDisc config.QueueingDiscipline\n+ Neighbors []Neighbor\n// NumChannels controls how many underlying FD's are to be used to\n// create this endpoint.\n@@ -241,6 +247,11 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\nroutes = append(routes, route)\n}\n+\n+ for _, neigh := range link.Neighbors {\n+ proto, tcpipAddr := ipToAddressAndProto(neigh.IP)\n+ n.Stack.AddStaticNeighbor(nicID, proto, tcpipAddr, tcpip.LinkAddress(neigh.HardwareAddr))\n+ }\n}\nif !args.Defaultv4Gateway.Route.Empty() {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/network.go",
"new_path": "runsc/sandbox/network.go",
"diff": "@@ -173,6 +173,23 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\ncontinue\n}\n+ // Collect data from the ARP table.\n+ dump, err := netlink.NeighList(iface.Index, 0)\n+ if err != nil {\n+ return fmt.Errorf(\"fetching ARP table for %q: %w\", iface.Name, err)\n+ }\n+\n+ var neighbors []boot.Neighbor\n+ for _, n := range dump {\n+ // There are only two \"good\" states NUD_PERMANENT and NUD_REACHABLE,\n+ // but NUD_REACHABLE is fully dynamic and will be re-probed anyway.\n+ if n.State == netlink.NUD_PERMANENT {\n+ log.Debugf(\"Copying a static ARP entry: %+v %+v\", n.IP, n.HardwareAddr)\n+ // No flags are copied because Stack.AddStaticNeighbor does not support flags right now.\n+ neighbors = append(neighbors, boot.Neighbor{IP: n.IP, HardwareAddr: n.HardwareAddr})\n+ }\n+ }\n+\n// Scrape the routes before removing the address, since that\n// will remove the routes as well.\nroutes, defv4, defv6, err := routesForIface(iface)\n@@ -203,6 +220,7 @@ func createInterfacesAndRoutesFromNS(conn *urpc.Client, nsPath string, hardwareG\nRXChecksumOffload: rxChecksumOffload,\nNumChannels: numNetworkChannels,\nQDisc: qDisc,\n+ Neighbors: neighbors,\n}\n// Get the link for the interface.\n"
}
] | Go | Apache License 2.0 | google/gvisor | copy PERM ARP entries from namespace on boot
copy and setup PERMANENT (static) ARP entries
from CNI namespace to the sandbox
Fixes #3301 |
259,992 | 02.11.2021 12:26:18 | 25,200 | 1e1d6b2be37873c5e62461834df973f41565c662 | Allow SetAttr and Allocate for deleted files
It's safe to call SetAttr and Allocate on fsgofer because the
file path is not used to open the file, if needed.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/p9/file.go",
"new_path": "pkg/p9/file.go",
"diff": "@@ -21,13 +21,37 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n)\n+// AttacherOptions contains Attacher configuration.\n+type AttacherOptions struct {\n+ // SetAttrOnDeleted is set to true if it's safe to call File.SetAttr for\n+ // deleted files.\n+ SetAttrOnDeleted bool\n+\n+ // AllocateOnDeleted is set to true if it's safe to call File.Allocate for\n+ // deleted files.\n+ AllocateOnDeleted bool\n+}\n+\n+// NoServerOptions partially implements Attacher with empty AttacherOptions.\n+type NoServerOptions struct{}\n+\n+// ServerOptions implements Attacher.\n+func (*NoServerOptions) ServerOptions() AttacherOptions {\n+ return AttacherOptions{}\n+}\n+\n// Attacher is provided by the server.\ntype Attacher interface {\n// Attach returns a new File.\n//\n- // The client-side attach will be translate to a series of walks from\n+ // The client-side attach will be translated to a series of walks from\n// the file returned by this Attach call.\nAttach() (File, error)\n+\n+ // ServerOptions returns configuration options for this attach point.\n+ //\n+ // This is never caller in the client-side.\n+ ServerOptions() AttacherOptions\n}\n// File is a set of operations corresponding to a single node.\n@@ -301,7 +325,7 @@ type File interface {\ntype DefaultWalkGetAttr struct{}\n// WalkGetAttr implements File.WalkGetAttr.\n-func (DefaultWalkGetAttr) WalkGetAttr([]string) ([]QID, File, AttrMask, Attr, error) {\n+func (*DefaultWalkGetAttr) WalkGetAttr([]string) ([]QID, File, AttrMask, Attr, error) {\nreturn nil, nil, AttrMask{}, Attr{}, unix.ENOSYS\n}\n@@ -309,7 +333,7 @@ func (DefaultWalkGetAttr) WalkGetAttr([]string) ([]QID, File, AttrMask, Attr, er\ntype DisallowClientCalls struct{}\n// SetAttrClose implements File.SetAttrClose.\n-func (DisallowClientCalls) SetAttrClose(SetAttrMask, SetAttr) error {\n+func (*DisallowClientCalls) SetAttrClose(SetAttrMask, SetAttr) error {\npanic(\"SetAttrClose should not be called on the server\")\n}\n@@ -321,6 +345,11 @@ func (*DisallowServerCalls) Renamed(File, string) {\npanic(\"Renamed should not be called on the client\")\n}\n+// ServerOptions implements Attacher.\n+func (*DisallowServerCalls) ServerOptions() AttacherOptions {\n+ panic(\"ServerOptions should not be called on the client\")\n+}\n+\n// DefaultMultiGetAttr implements File.MultiGetAttr() on top of File.\nfunc DefaultMultiGetAttr(start File, names []string) ([]FullStat, error) {\nstats := make([]FullStat, 0, len(names))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/handlers.go",
"new_path": "pkg/p9/handlers.go",
"diff": "@@ -178,7 +178,7 @@ func (t *Tsetattrclunk) handle(cs *connState) message {\n// This might be technically incorrect, as it's possible that\n// there were multiple links and you can still change the\n// corresponding inode information.\n- if ref.isDeleted() {\n+ if !cs.server.options.SetAttrOnDeleted && ref.isDeleted() {\nreturn unix.EINVAL\n}\n@@ -913,7 +913,7 @@ func (t *Tsetattr) handle(cs *connState) message {\n// This might be technically incorrect, as it's possible that\n// there were multiple links and you can still change the\n// corresponding inode information.\n- if ref.isDeleted() {\n+ if !cs.server.options.SetAttrOnDeleted && ref.isDeleted() {\nreturn unix.EINVAL\n}\n@@ -946,7 +946,7 @@ func (t *Tallocate) handle(cs *connState) message {\n}\n// We don't allow allocate on files that have been deleted.\n- if ref.isDeleted() {\n+ if !cs.server.options.AllocateOnDeleted && ref.isDeleted() {\nreturn unix.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/p9test/BUILD",
"new_path": "pkg/p9/p9test/BUILD",
"diff": "@@ -12,7 +12,7 @@ MOCK_SRC_PACKAGE = \"gvisor.dev/gvisor/pkg/p9\"\n# mockgen_reflect is a source file that contains mock generation code that\n# imports the p9 package and generates a specification via reflection. The\n# usual generation path must be split into two distinct parts because the full\n-# source tree is not available to all build targets. Only declared depencies\n+# source tree is not available to all build targets. Only declared dependencies\n# are available (and even then, not the Go source files).\ngenrule(\nname = \"mockgen_reflect\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/p9test/p9test.go",
"new_path": "pkg/p9/p9test/p9test.go",
"diff": "@@ -307,6 +307,7 @@ func NewHarness(t *testing.T) (*Harness, *p9.Client) {\n}\n// Start the server, synchronized on exit.\n+ h.Attacher.EXPECT().ServerOptions().Return(p9.AttacherOptions{}).Times(1)\nserver := p9.NewServer(h.Attacher)\nh.wg.Add(1)\ngo func() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/p9/server.go",
"new_path": "pkg/p9/server.go",
"diff": "@@ -34,6 +34,8 @@ type Server struct {\n// attacher provides the attach function.\nattacher Attacher\n+ options AttacherOptions\n+\n// pathTree is the full set of paths opened on this server.\n//\n// These may be across different connections, but rename operations\n@@ -48,10 +50,15 @@ type Server struct {\nrenameMu sync.RWMutex\n}\n-// NewServer returns a new server.\n+// NewServer returns a new server. attacher may be nil.\nfunc NewServer(attacher Attacher) *Server {\n+ opts := AttacherOptions{}\n+ if attacher != nil {\n+ opts = attacher.ServerOptions()\n+ }\nreturn &Server{\nattacher: attacher,\n+ options: opts,\npathTree: newPathNode(),\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -140,6 +140,17 @@ func (a *attachPoint) Attach() (p9.File, error) {\nreturn lf, nil\n}\n+// ServerOptions implements p9.Attacher. It's safe to call SetAttr and Allocate\n+// on deleted files because fsgofer either uses an existing FD or opens a new\n+// one using the magic symlink in `/proc/[pid]/fd` and cannot mistakely open\n+// a file that was created in the same path as the delete file.\n+func (a *attachPoint) ServerOptions() p9.AttacherOptions {\n+ return p9.AttacherOptions{\n+ SetAttrOnDeleted: true,\n+ AllocateOnDeleted: true,\n+ }\n+}\n+\n// makeQID returns a unique QID for the given stat buffer.\nfunc (a *attachPoint) makeQID(stat *unix.Stat_t) p9.QID {\na.deviceMu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -1053,3 +1053,7 @@ syscall_test(\nsyscall_test(\ntest = \"//test/syscalls/linux:verity_mount_test\",\n)\n+\n+syscall_test(\n+ test = \"//test/syscalls/linux:deleted_test\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -4432,3 +4432,18 @@ cc_binary(\n\"@com_google_absl//absl/container:flat_hash_set\",\n],\n)\n+\n+cc_binary(\n+ name = \"deleted_test\",\n+ testonly = 1,\n+ srcs = [\"deleted.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:fs_util\",\n+ gtest,\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/deleted.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 <errno.h>\n+#include <fcntl.h>\n+#include <time.h>\n+#include <unistd.h>\n+\n+#include <string>\n+\n+#include \"gmock/gmock.h\"\n+#include \"gtest/gtest.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+\n+constexpr mode_t mode = 1;\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+PosixErrorOr<FileDescriptor> createdDeleted() {\n+ auto path = NewTempAbsPath();\n+ PosixErrorOr<FileDescriptor> fd = Open(path, O_RDWR | O_CREAT, mode);\n+ if (!fd.ok()) {\n+ return fd.error();\n+ }\n+\n+ auto err = Unlink(path);\n+ if (!err.ok()) {\n+ return err;\n+ }\n+ return fd;\n+}\n+\n+TEST(DeletedTest, Utime) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(createdDeleted());\n+\n+ const struct timespec times[2] = {{10, 0}, {20, 0}};\n+ EXPECT_THAT(futimens(fd.get(), times), SyscallSucceeds());\n+\n+ struct stat stat;\n+ ASSERT_THAT(fstat(fd.get(), &stat), SyscallSucceeds());\n+ EXPECT_EQ(10, stat.st_atime);\n+ EXPECT_EQ(20, stat.st_mtime);\n+}\n+\n+TEST(DeletedTest, Chmod) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(createdDeleted());\n+\n+ ASSERT_THAT(fchmod(fd.get(), mode + 1), SyscallSucceeds());\n+\n+ struct stat stat;\n+ ASSERT_THAT(fstat(fd.get(), &stat), SyscallSucceeds());\n+ EXPECT_EQ(mode + 1, stat.st_mode & ~S_IFMT);\n+}\n+\n+TEST(DeletedTest, Truncate) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(createdDeleted());\n+ const std::string data = \"foobar\";\n+ ASSERT_THAT(write(fd.get(), data.c_str(), data.size()), SyscallSucceeds());\n+\n+ ASSERT_THAT(ftruncate(fd.get(), 0), SyscallSucceeds());\n+\n+ struct stat stat;\n+ ASSERT_THAT(fstat(fd.get(), &stat), SyscallSucceeds());\n+ ASSERT_EQ(stat.st_size, 0);\n+}\n+\n+TEST(DeletedTest, Fallocate) {\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(createdDeleted());\n+\n+ ASSERT_THAT(fallocate(fd.get(), 0, 0, 123), SyscallSucceeds());\n+\n+ struct stat stat;\n+ ASSERT_THAT(fstat(fd.get(), &stat), SyscallSucceeds());\n+ EXPECT_EQ(123, stat.st_size);\n+}\n+\n+// Tests that a file can be created with the same path as a deleted file that\n+// still have an open FD to it.\n+TEST(DeletedTest, Replace) {\n+ auto path = NewTempAbsPath();\n+ auto fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR | O_CREAT, mode));\n+ ASSERT_NO_ERRNO(Unlink(path));\n+\n+ auto other =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR | O_CREAT | O_EXCL, mode));\n+\n+ auto stat = ASSERT_NO_ERRNO_AND_VALUE(Fstat(fd.get()));\n+ auto stat_other = ASSERT_NO_ERRNO_AND_VALUE(Fstat(other.get()));\n+ ASSERT_NE(stat.st_ino, stat_other.st_ino);\n+\n+ // Check that the path points to the new file.\n+ stat = ASSERT_NO_ERRNO_AND_VALUE(Stat(path));\n+ ASSERT_EQ(stat.st_ino, stat_other.st_ino);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/fs_util.cc",
"new_path": "test/util/fs_util.cc",
"diff": "@@ -188,6 +188,14 @@ PosixError MknodAt(const FileDescriptor& dfd, absl::string_view path, int mode,\nreturn NoError();\n}\n+PosixError Unlink(absl::string_view path) {\n+ int res = unlink(std::string(path).c_str());\n+ if (res < 0) {\n+ return PosixError(errno, absl::StrCat(\"unlink \", path));\n+ }\n+ return NoError();\n+}\n+\nPosixError UnlinkAt(const FileDescriptor& dfd, absl::string_view path,\nint flags) {\nint res = unlinkat(dfd.get(), std::string(path).c_str(), flags);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/fs_util.h",
"new_path": "test/util/fs_util.h",
"diff": "@@ -71,6 +71,7 @@ PosixError MknodAt(const FileDescriptor& dfd, absl::string_view path, int mode,\ndev_t dev);\n// Unlink the file.\n+PosixError Unlink(absl::string_view path);\nPosixError UnlinkAt(const FileDescriptor& dfd, absl::string_view path,\nint flags);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow SetAttr and Allocate for deleted files
It's safe to call SetAttr and Allocate on fsgofer because the
file path is not used to open the file, if needed.
Fixes #3654
PiperOrigin-RevId: 407149393 |
260,004 | 02.11.2021 14:51:10 | 25,200 | 88cf2e93e5ca3ce0f852a0e3dfb06099777c08c0 | Extract tcb & lastUsed to its own lock
These fields do not need to synchronize reads/writes with the rest of
the connection. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -119,22 +119,24 @@ type conn struct {\n//\n// +checklocks:mu\ndestinationManip bool\n+\n+ stateMu sync.RWMutex `state:\"nosave\"`\n// tcb is TCB control block. It is used to keep track of states\n// of tcp connection.\n//\n- // +checklocks:mu\n+ // +checklocks:stateMu\ntcb tcpconntrack.TCB\n// lastUsed is the last time the connection saw a relevant packet, and\n// is updated by each packet on the connection.\n//\n- // +checklocks:mu\n+ // +checklocks:stateMu\nlastUsed tcpip.MonotonicTime\n}\n// timedOut returns whether the connection timed out based on its state.\nfunc (cn *conn) timedOut(now tcpip.MonotonicTime) bool {\n- cn.mu.RLock()\n- defer cn.mu.RUnlock()\n+ cn.stateMu.RLock()\n+ defer cn.stateMu.RUnlock()\nif cn.tcb.State() == tcpconntrack.ResultAlive {\n// Use the same default as Linux, which doesn't delete\n// established connections for 5(!) days.\n@@ -147,7 +149,7 @@ func (cn *conn) timedOut(now tcpip.MonotonicTime) bool {\n// update the connection tracking state.\n//\n-// +checklocks:cn.mu\n+// +checklocks:cn.stateMu\nfunc (cn *conn) updateLocked(pkt *PacketBuffer, reply bool) {\nif pkt.TransportProtocolNumber != header.TCPProtocolNumber {\nreturn\n@@ -607,14 +609,17 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, rt *Route) bool {\n// packets are fragmented.\nreply := pkt.tuple.reply\n- tid, performManip := func() (tupleID, bool) {\n- cn.mu.Lock()\n- defer cn.mu.Unlock()\n+ cn.stateMu.Lock()\n// Mark the connection as having been used recently so it isn't reaped.\ncn.lastUsed = cn.ct.clock.NowMonotonic()\n// Update connection state.\ncn.updateLocked(pkt, reply)\n+ cn.stateMu.Unlock()\n+\n+ tid, performManip := func() (tupleID, bool) {\n+ cn.mu.RLock()\n+ defer cn.mu.RUnlock()\nvar tuple *tuple\nif reply {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Extract tcb & lastUsed to its own lock
These fields do not need to synchronize reads/writes with the rest of
the connection.
PiperOrigin-RevId: 407183693 |
259,975 | 04.11.2021 14:52:36 | 25,200 | fe8e48fc6d5094fe34783b1040b2ae4ba05349b5 | [syserr] Move ConvertIntr function to linuxerr package
Move ConverIntr out of syserr package and delete an unused function. | [
{
"change_type": "MODIFY",
"old_path": "pkg/errors/linuxerr/internal.go",
"new_path": "pkg/errors/linuxerr/internal.go",
"diff": "@@ -118,3 +118,12 @@ func SyscallRestartErrorFromReturn(rv uintptr) (*errors.Error, bool) {\nerr, ok := restartMap[int(rv)]\nreturn err, ok\n}\n+\n+// ConvertIntr converts the provided error code (err) to another one (intr) if\n+// the first error corresponds to an interrupted operation.\n+func ConvertIntr(err, intr error) error {\n+ if err == ErrInterrupted {\n+ return intr\n+ }\n+ return err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_exit.go",
"new_path": "pkg/sentry/kernel/task_exit.go",
"diff": "@@ -32,7 +32,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -866,7 +865,7 @@ func (t *Task) Wait(opts *WaitOptions) (*WaitResult, error) {\nreturn wr, err\n}\nif err := t.Block(ch); err != nil {\n- return wr, syserr.ConvertIntr(err, opts.BlockInterruptErr)\n+ return wr, linuxerr.ConvertIntr(err, opts.BlockInterruptErr)\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_aio.go",
"new_path": "pkg/sentry/syscalls/linux/sys_aio.go",
"diff": "@@ -26,7 +26,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/eventfd\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -138,7 +137,7 @@ func IoGetevents(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nif count > 0 || linuxerr.Equals(linuxerr.ETIMEDOUT, err) {\nreturn uintptr(count), nil, nil\n}\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.EINTR)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.EINTR)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"diff": "@@ -22,7 +22,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/epoll\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -109,7 +108,7 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nfunc waitEpoll(t *kernel.Task, fd int32, eventsAddr hostarch.Addr, max int, timeoutInNanos int64) (uintptr, *kernel.SyscallControl, error) {\nr, err := syscalls.WaitEpoll(t, fd, max, timeoutInNanos)\nif err != nil {\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.EINTR)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.EINTR)\n}\nif len(r) != 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -30,7 +30,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/fasync\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// fileOpAt performs an operation on the second last component in the path.\n@@ -177,7 +176,7 @@ func openAt(t *kernel.Task, dirFD int32, addr hostarch.Addr, flags uint) (fd uin\nfile, err := d.Inode.GetFile(t, d, fileFlags)\nif err != nil {\n- return syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\ndefer file.DecRef(t)\n@@ -416,7 +415,7 @@ func createAt(t *kernel.Task, dirFD int32, addr hostarch.Addr, flags uint, mode\n// Create a new fs.File.\nnewFile, err = found.Inode.GetFile(t, found, fileFlags)\nif err != nil {\n- return syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\ndefer newFile.DecRef(t)\ncase linuxerr.Equals(linuxerr.ENOENT, err):\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_futex.go",
"new_path": "pkg/sentry/syscalls/linux/sys_futex.go",
"diff": "@@ -23,7 +23,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// futexWaitRestartBlock encapsulates the state required to restart futex(2)\n@@ -75,7 +74,7 @@ func futexWaitAbsolute(t *kernel.Task, clockRealtime bool, ts linux.Timespec, fo\n}\nt.Futex().WaitComplete(w, t)\n- return 0, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n// futexWaitDuration performs a FUTEX_WAIT, blocking until the wait is\n@@ -150,7 +149,7 @@ func futexLockPI(t *kernel.Task, ts linux.Timespec, forever bool, addr hostarch.\n}\nt.Futex().WaitComplete(w, t)\n- return syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\nfunc tryLockPI(t *kernel.Task, addr hostarch.Addr, private bool) error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_mmap.go",
"new_path": "pkg/sentry/syscalls/linux/sys_mmap.go",
"diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/mm\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// Brk implements linux syscall brk(2).\n@@ -277,7 +276,7 @@ func Msync(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\n})\n// MSync calls fsync, the same interrupt conversion rules apply, see\n// mm/msync.c, fsync POSIX.1-2008.\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n// Mlock implements linux syscall mlock(2).\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_poll.go",
"diff": "@@ -25,7 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -185,7 +184,7 @@ func doPoll(t *kernel.Task, addr hostarch.Addr, nfds uint, timeout time.Duration\npfd[i].Events |= linux.POLLHUP | linux.POLLERR\n}\nremainingTimeout, n, err := pollBlock(t, pfd, timeout)\n- err = syserr.ConvertIntr(err, linuxerr.EINTR)\n+ err = linuxerr.ConvertIntr(err, linuxerr.EINTR)\n// The poll entries are copied out regardless of whether\n// any are set or not. This aligns with the Linux behavior.\n@@ -295,7 +294,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs hostarch.Ad\n// Do the syscall, then count the number of bits set.\nif _, _, err = pollBlock(t, pfd, timeout); err != nil {\n- return 0, syserr.ConvertIntr(err, linuxerr.EINTR)\n+ return 0, linuxerr.ConvertIntr(err, linuxerr.EINTR)\n}\n// r, w, and e are currently event mask bitsets; unset bits corresponding\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_signal.go",
"new_path": "pkg/sentry/syscalls/linux/sys_signal.go",
"diff": "@@ -25,7 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/signalfd\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// \"For a process to have permission to send a signal it must\n@@ -348,7 +347,7 @@ func Sigaltstack(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\n// Pause implements linux syscall pause(2).\nfunc Pause(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- return 0, nil, syserr.ConvertIntr(t.Block(nil), linuxerr.ERESTARTNOHAND)\n+ return 0, nil, linuxerr.ConvertIntr(t.Block(nil), linuxerr.ERESTARTNOHAND)\n}\n// RtSigpending implements linux syscall rt_sigpending(2).\n@@ -496,7 +495,7 @@ func RtSigsuspend(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.\nt.SetSavedSignalMask(oldmask)\n// Perform the wait.\n- return 0, nil, syserr.ConvertIntr(t.Block(nil), linuxerr.ERESTARTNOHAND)\n+ return 0, nil, linuxerr.ConvertIntr(t.Block(nil), linuxerr.ERESTARTNOHAND)\n}\n// RestartSyscall implements the linux syscall restart_syscall(2).\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"new_path": "pkg/sentry/syscalls/linux/sys_socket.go",
"diff": "@@ -269,7 +269,7 @@ func Connect(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\nblocking := !file.Flags().NonBlocking\n- return 0, nil, syserr.ConvertIntr(s.Connect(t, a, blocking).ToError(), linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(s.Connect(t, a, blocking).ToError(), linuxerr.ERESTARTSYS)\n}\n// accept is the implementation of the accept syscall. It is called by accept\n@@ -300,7 +300,7 @@ func accept(t *kernel.Task, fd int32, addr hostarch.Addr, addrLen hostarch.Addr,\npeerRequested := addrLen != 0\nnfd, peer, peerLen, e := s.Accept(t, peerRequested, flags, blocking)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\nif peerRequested {\n// NOTE(magi): Linux does not give you an error if it can't\n@@ -762,7 +762,7 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr hostarch.Addr, flags\nif msg.ControlLen == 0 && msg.NameLen == 0 {\nn, mflags, _, _, cms, err := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, false, 0)\nif err != nil {\n- return 0, syserr.ConvertIntr(err.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(err.ToError(), linuxerr.ERESTARTSYS)\n}\nif !cms.Unix.Empty() {\nmflags |= linux.MSG_CTRUNC\n@@ -784,7 +784,7 @@ func recvSingleMsg(t *kernel.Task, s socket.Socket, msgPtr hostarch.Addr, flags\n}\nn, mflags, sender, senderLen, cms, e := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, msg.NameLen != 0, msg.ControlLen)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\ndefer cms.Release(t)\n@@ -873,7 +873,7 @@ func recvFrom(t *kernel.Task, fd int32, bufPtr hostarch.Addr, bufLen uint64, fla\nn, _, sender, senderLen, cm, e := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, nameLenPtr != 0, 0)\ncm.Release(t)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\n// Copy the address to the caller.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_sync.go",
"new_path": "pkg/sentry/syscalls/linux/sys_sync.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// LINT.IfChange\n@@ -58,7 +57,7 @@ func Fsync(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ndefer file.DecRef(t)\nerr := file.Fsync(t, 0, fs.FileMaxOffset, fs.SyncAll)\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n// Fdatasync implements linux syscall fdatasync(2).\n@@ -74,7 +73,7 @@ func Fdatasync(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\ndefer file.DecRef(t)\nerr := file.Fsync(t, 0, fs.FileMaxOffset, fs.SyncData)\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n// SyncFileRange implements linux syscall sync_file_rage(2)\n@@ -137,7 +136,7 @@ func SyncFileRange(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel\nerr = file.Fsync(t, offset, fs.FileMaxOffset, fs.SyncData)\n}\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n// LINT.ThenChange(vfs2/sync.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/poll.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/poll.go",
"diff": "@@ -26,7 +26,6 @@ import (\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/limits\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -188,7 +187,7 @@ func doPoll(t *kernel.Task, addr hostarch.Addr, nfds uint, timeout time.Duration\npfd[i].Events |= linux.POLLHUP | linux.POLLERR\n}\nremainingTimeout, n, err := pollBlock(t, pfd, timeout)\n- err = syserr.ConvertIntr(err, linuxerr.EINTR)\n+ err = linuxerr.ConvertIntr(err, linuxerr.EINTR)\n// The poll entries are copied out regardless of whether\n// any are set or not. This aligns with the Linux behavior.\n@@ -298,7 +297,7 @@ func doSelect(t *kernel.Task, nfds int, readFDs, writeFDs, exceptFDs hostarch.Ad\n// Do the syscall, then count the number of bits set.\nif _, _, err = pollBlock(t, pfd, timeout); err != nil {\n- return 0, syserr.ConvertIntr(err, linuxerr.EINTR)\n+ return 0, linuxerr.ConvertIntr(err, linuxerr.EINTR)\n}\n// r, w, and e are currently event mask bitsets; unset bits corresponding\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/socket.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/socket.go",
"diff": "@@ -272,7 +272,7 @@ func Connect(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\nblocking := (file.StatusFlags() & linux.SOCK_NONBLOCK) == 0\n- return 0, nil, syserr.ConvertIntr(s.Connect(t, a, blocking).ToError(), linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(s.Connect(t, a, blocking).ToError(), linuxerr.ERESTARTSYS)\n}\n// accept is the implementation of the accept syscall. It is called by accept\n@@ -303,7 +303,7 @@ func accept(t *kernel.Task, fd int32, addr hostarch.Addr, addrLen hostarch.Addr,\npeerRequested := addrLen != 0\nnfd, peer, peerLen, e := s.Accept(t, peerRequested, flags, blocking)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\nif peerRequested {\n// NOTE(magi): Linux does not give you an error if it can't\n@@ -765,7 +765,7 @@ func recvSingleMsg(t *kernel.Task, s socket.SocketVFS2, msgPtr hostarch.Addr, fl\nif msg.ControlLen == 0 && msg.NameLen == 0 {\nn, mflags, _, _, cms, err := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, false, 0)\nif err != nil {\n- return 0, syserr.ConvertIntr(err.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(err.ToError(), linuxerr.ERESTARTSYS)\n}\nif !cms.Unix.Empty() {\nmflags |= linux.MSG_CTRUNC\n@@ -787,7 +787,7 @@ func recvSingleMsg(t *kernel.Task, s socket.SocketVFS2, msgPtr hostarch.Addr, fl\n}\nn, mflags, sender, senderLen, cms, e := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, msg.NameLen != 0, msg.ControlLen)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\ndefer cms.Release(t)\n@@ -876,7 +876,7 @@ func recvFrom(t *kernel.Task, fd int32, bufPtr hostarch.Addr, bufLen uint64, fla\nn, _, sender, senderLen, cm, e := s.RecvMsg(t, dst, int(flags), haveDeadline, deadline, nameLenPtr != 0, 0)\ncm.Release(t)\nif e != nil {\n- return 0, syserr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n+ return 0, linuxerr.ConvertIntr(e.ToError(), linuxerr.ERESTARTSYS)\n}\n// Copy the address to the caller.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/sync.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/sync.go",
"diff": "@@ -19,7 +19,6 @@ import (\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n- \"gvisor.dev/gvisor/pkg/syserr\"\n)\n// Sync implements Linux syscall sync(2).\n@@ -113,7 +112,7 @@ func SyncFileRange(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel\nif flags&linux.SYNC_FILE_RANGE_WAIT_AFTER != 0 {\nif err := file.Sync(t); err != nil {\n- return 0, nil, syserr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n+ return 0, nil, linuxerr.ConvertIntr(err, linuxerr.ERESTARTSYS)\n}\n}\nreturn 0, nil, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/syserr.go",
"new_path": "pkg/syserr/syserr.go",
"diff": "@@ -74,15 +74,6 @@ func NewDynamic(message string, linuxTranslation errno.Errno) *Error {\nreturn &Error{message: message, errno: linuxTranslation}\n}\n-// NewWithoutTranslation creates a new Error. If translation is attempted on\n-// the error, translation will fail.\n-//\n-// NewWithoutTranslation may be called at any time, but static errors should\n-// be declared as global variables and dynamic errors should be used sparingly.\n-func NewWithoutTranslation(message string) *Error {\n- return &Error{message: message, noTranslation: true}\n-}\n-\nfunc newWithHost(message string, linuxTranslation errno.Errno, hostErrno unix.Errno) *Error {\ne := New(message, linuxTranslation)\naddLinuxHostTranslation(hostErrno, e)\n@@ -292,12 +283,3 @@ func FromError(err error) *Error {\nmsg := fmt.Sprintf(\"err: %s type: %T\", err.Error(), err)\npanic(msg)\n}\n-\n-// ConvertIntr converts the provided error code (err) to another one (intr) if\n-// the first error corresponds to an interrupted operation.\n-func ConvertIntr(err, intr error) error {\n- if err == linuxerr.ErrInterrupted {\n- return intr\n- }\n- return err\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | [syserr] Move ConvertIntr function to linuxerr package
Move ConverIntr out of syserr package and delete an unused function.
PiperOrigin-RevId: 407676258 |
259,891 | 07.11.2021 14:54:34 | 28,800 | efe264ef0cdf5929834614b26017f688ac139036 | Use platform-independant iovec functions | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket_unsafe.go",
"new_path": "pkg/sentry/fs/host/socket_unsafe.go",
"diff": "@@ -43,12 +43,12 @@ func fdReadVec(fd int, bufs [][]byte, control []byte, peek bool, maxlen int64) (\nvar msg unix.Msghdr\nif len(control) != 0 {\nmsg.Control = &control[0]\n- msg.Controllen = uint64(len(control))\n+ msg.SetControllen(len(control))\n}\nif len(iovecs) != 0 {\nmsg.Iov = &iovecs[0]\n- msg.Iovlen = uint64(len(iovecs))\n+ msg.SetIovlen(len(iovecs))\n}\nrawN, _, e := unix.RawSyscall(unix.SYS_RECVMSG, uintptr(fd), uintptr(unsafe.Pointer(&msg)), flags)\n@@ -66,10 +66,10 @@ func fdReadVec(fd int, bufs [][]byte, control []byte, peek bool, maxlen int64) (\ncontrolTrunc = msg.Flags&unix.MSG_CTRUNC == unix.MSG_CTRUNC\nif n > length {\n- return length, n, msg.Controllen, controlTrunc, nil\n+ return length, n, uint64(msg.Controllen), controlTrunc, nil\n}\n- return n, n, msg.Controllen, controlTrunc, nil\n+ return n, n, uint64(msg.Controllen), controlTrunc, nil\n}\n// fdWriteVec sends from bufs to fd.\n@@ -91,7 +91,7 @@ func fdWriteVec(fd int, bufs [][]byte, maxlen int64, truncate bool) (int64, int6\nvar msg unix.Msghdr\nif len(iovecs) > 0 {\nmsg.Iov = &iovecs[0]\n- msg.Iovlen = uint64(len(iovecs))\n+ msg.SetIovlen(len(iovecs))\n}\nn, _, e := unix.RawSyscall(unix.SYS_SENDMSG, uintptr(fd), uintptr(unsafe.Pointer(&msg)), unix.MSG_DONTWAIT|unix.MSG_NOSIGNAL)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use platform-independant iovec functions |
259,907 | 08.11.2021 00:37:24 | 28,800 | 4622e17bccc7c40a2698e8314d29bbde87090cec | Simplify {Un}MarshalUnsafeSlice method signatures.
Earlier this function was returning (int, error) much like the Copy{In/Out}
methods. The returned error was always nil. The returned int was never used.
Instead make it returned the shifted buffer which is more useful.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/message.go",
"new_path": "pkg/lisafs/message.go",
"diff": "@@ -307,11 +307,7 @@ func (m *MountResp) MarshalBytes(dst []byte) []byte {\ndst = m.MaxMessageSize.MarshalUnsafe(dst)\nnumSupported := primitive.Uint16(len(m.SupportedMs))\ndst = numSupported.MarshalBytes(dst)\n- n, err := MarshalUnsafeMIDSlice(m.SupportedMs, dst)\n- if err != nil {\n- panic(err)\n- }\n- return dst[n:]\n+ return MarshalUnsafeMIDSlice(m.SupportedMs, dst)\n}\n// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n@@ -320,12 +316,12 @@ func (m *MountResp) UnmarshalBytes(src []byte) []byte {\nsrc = m.MaxMessageSize.UnmarshalUnsafe(src)\nvar numSupported primitive.Uint16\nsrc = numSupported.UnmarshalBytes(src)\n+ if cap(m.SupportedMs) < int(numSupported) {\nm.SupportedMs = make([]MID, numSupported)\n- n, err := UnmarshalUnsafeMIDSlice(m.SupportedMs, src)\n- if err != nil {\n- panic(err)\n+ } else {\n+ m.SupportedMs = m.SupportedMs[:numSupported]\n}\n- return src[n:]\n+ return UnmarshalUnsafeMIDSlice(m.SupportedMs, src)\n}\n// ChannelResp is the response to the create channel request.\n@@ -440,11 +436,7 @@ func (w *WalkResp) MarshalBytes(dst []byte) []byte {\nnumInodes := primitive.Uint32(len(w.Inodes))\ndst = numInodes.MarshalUnsafe(dst)\n- n, err := MarshalUnsafeInodeSlice(w.Inodes, dst)\n- if err != nil {\n- panic(err)\n- }\n- return dst[n:]\n+ return MarshalUnsafeInodeSlice(w.Inodes, dst)\n}\n// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n@@ -459,11 +451,7 @@ func (w *WalkResp) UnmarshalBytes(src []byte) []byte {\n} else {\nw.Inodes = w.Inodes[:numInodes]\n}\n- n, err := UnmarshalUnsafeInodeSlice(w.Inodes, src)\n- if err != nil {\n- panic(err)\n- }\n- return src[n:]\n+ return UnmarshalUnsafeInodeSlice(w.Inodes, src)\n}\n// WalkStatResp is used to communicate stat results for WalkStat.\n@@ -481,11 +469,7 @@ func (w *WalkStatResp) MarshalBytes(dst []byte) []byte {\nnumStats := primitive.Uint32(len(w.Stats))\ndst = numStats.MarshalUnsafe(dst)\n- n, err := linux.MarshalUnsafeStatxSlice(w.Stats, dst)\n- if err != nil {\n- panic(err)\n- }\n- return dst[n:]\n+ return linux.MarshalUnsafeStatxSlice(w.Stats, dst)\n}\n// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n@@ -498,11 +482,7 @@ func (w *WalkStatResp) UnmarshalBytes(src []byte) []byte {\n} else {\nw.Stats = w.Stats[:numStats]\n}\n- n, err := linux.UnmarshalUnsafeStatxSlice(w.Stats, src)\n- if err != nil {\n- panic(err)\n- }\n- return src[n:]\n+ return linux.UnmarshalUnsafeStatxSlice(w.Stats, src)\n}\n// OpenAtReq is used to open existing FDs with the specified flags.\n@@ -578,11 +558,7 @@ func (f *FdArray) SizeBytes() int {\nfunc (f *FdArray) MarshalBytes(dst []byte) []byte {\narrLen := primitive.Uint32(len(*f))\ndst = arrLen.MarshalUnsafe(dst)\n- n, err := MarshalUnsafeFDIDSlice(*f, dst)\n- if err != nil {\n- panic(err)\n- }\n- return dst[n:]\n+ return MarshalUnsafeFDIDSlice(*f, dst)\n}\n// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\n@@ -594,11 +570,7 @@ func (f *FdArray) UnmarshalBytes(src []byte) []byte {\n} else {\n*f = (*f)[:arrLen]\n}\n- n, err := UnmarshalUnsafeFDIDSlice(*f, src)\n- if err != nil {\n- panic(err)\n- }\n- return src[n:]\n+ return UnmarshalUnsafeFDIDSlice(*f, src)\n}\n// CloseReq is used to close(2) FDs.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/sample_message.go",
"new_path": "pkg/lisafs/sample_message.go",
"diff": "@@ -55,22 +55,14 @@ func (m *MsgDynamic) SizeBytes() int {\n// MarshalBytes implements marshal.Marshallable.MarshalBytes.\nfunc (m *MsgDynamic) MarshalBytes(dst []byte) []byte {\ndst = m.N.MarshalUnsafe(dst)\n- n, err := MarshalUnsafeMsg1Slice(m.Arr, dst)\n- if err != nil {\n- panic(err)\n- }\n- return dst[n:]\n+ return MarshalUnsafeMsg1Slice(m.Arr, dst)\n}\n// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes.\nfunc (m *MsgDynamic) UnmarshalBytes(src []byte) []byte {\nsrc = m.N.UnmarshalUnsafe(src)\nm.Arr = make([]MsgSimple, m.N)\n- n, err := UnmarshalUnsafeMsg1Slice(m.Arr, src)\n- if err != nil {\n- panic(err)\n- }\n- return src[n:]\n+ return UnmarshalUnsafeMsg1Slice(m.Arr, src)\n}\n// Randomize randomizes the contents of m.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/marshal/marshal.go",
"new_path": "pkg/marshal/marshal.go",
"diff": "@@ -150,13 +150,13 @@ type Marshallable interface {\n// // might be more efficient that repeatedly calling Foo.MarshalUnsafe\n// // over a []Foo in a loop if the type is Packed.\n// // Preconditions: dst must be at least len(src)*Foo.SizeBytes() in length.\n-// func MarshalUnsafeFooSlice(src []Foo, dst []byte) (int, error) { ... }\n+// func MarshalUnsafeFooSlice(src []Foo, dst []byte) []byte { ... }\n//\n// // UnmarshalUnsafeFooSlice is like Foo.UnmarshalUnsafe, buf for a []Foo. It\n// // might be more efficient that repeatedly calling Foo.UnmarshalUnsafe\n// // over a []Foo in a loop if the type is Packed.\n// // Preconditions: src must be at least len(dst)*Foo.SizeBytes() in length.\n-// func UnmarshalUnsafeFooSlice(dst []Foo, src []byte) (int, error) { ... }\n+// func UnmarshalUnsafeFooSlice(dst []Foo, src []byte) []byte { ... }\n//\n// // CopyFooSliceIn copies in a slice of Foo objects from the task's memory.\n// func CopyFooSliceIn(cc marshal.CopyContext, addr hostarch.Addr, dst []Foo) (int, error) { ... }\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/gomarshal/generator_interfaces_primitive_newtype.go",
"new_path": "tools/go_marshal/gomarshal/generator_interfaces_primitive_newtype.go",
"diff": "@@ -264,36 +264,36 @@ func (g *interfaceGenerator) emitMarshallableSliceForPrimitiveNewtype(nt *ast.Id\ng.emit(\"}\\n\\n\")\ng.emit(\"// MarshalUnsafe%s is like %s.MarshalUnsafe, but for a []%s.\\n\", slice.ident, g.typeName(), g.typeName())\n- g.emit(\"func MarshalUnsafe%s(src []%s, dst []byte) (int, error) {\\n\", slice.ident, g.typeName())\n+ g.emit(\"func MarshalUnsafe%s(src []%s, dst []byte) []byte {\\n\", slice.ident, g.typeName())\ng.inIndent(func() {\ng.emit(\"count := len(src)\\n\")\ng.emit(\"if count == 0 {\\n\")\ng.inIndent(func() {\n- g.emit(\"return 0, nil\\n\")\n+ g.emit(\"return dst\\n\")\n})\ng.emit(\"}\\n\")\ng.emit(\"size := (*%s)(nil).SizeBytes()\\n\\n\", g.typeName())\n- g.emit(\"dst = dst[:size*count]\\n\")\n- g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&src[0]), uintptr(len(dst)))\\n\")\n- g.emit(\"return size*count, nil\\n\")\n+ g.emit(\"buf := dst[:size*count]\\n\")\n+ g.emit(\"gohacks.Memmove(unsafe.Pointer(&buf[0]), unsafe.Pointer(&src[0]), uintptr(len(buf)))\\n\")\n+ g.emit(\"return dst[size*count:]\\n\")\n})\ng.emit(\"}\\n\\n\")\ng.emit(\"// UnmarshalUnsafe%s is like %s.UnmarshalUnsafe, but for a []%s.\\n\", slice.ident, g.typeName(), g.typeName())\n- g.emit(\"func UnmarshalUnsafe%s(dst []%s, src []byte) (int, error) {\\n\", slice.ident, g.typeName())\n+ g.emit(\"func UnmarshalUnsafe%s(dst []%s, src []byte) []byte {\\n\", slice.ident, g.typeName())\ng.inIndent(func() {\ng.emit(\"count := len(dst)\\n\")\ng.emit(\"if count == 0 {\\n\")\ng.inIndent(func() {\n- g.emit(\"return 0, nil\\n\")\n+ g.emit(\"return src\\n\")\n})\ng.emit(\"}\\n\")\ng.emit(\"size := (*%s)(nil).SizeBytes()\\n\\n\", g.typeName())\n- g.emit(\"src = src[:(size*count)]\\n\")\n- g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&src[0]), uintptr(len(src)))\\n\")\n- g.emit(\"return size*count, nil\\n\")\n+ g.emit(\"buf := src[:size*count]\\n\")\n+ g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&buf[0]), uintptr(len(buf)))\\n\")\n+ g.emit(\"return src[size*count:]\\n\")\n})\ng.emit(\"}\\n\\n\")\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/gomarshal/generator_interfaces_struct.go",
"new_path": "tools/go_marshal/gomarshal/generator_interfaces_struct.go",
"diff": "@@ -545,15 +545,14 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.emit(\"}\\n\\n\")\ng.emit(\"// MarshalUnsafe%s is like %s.MarshalUnsafe, but for a []%s.\\n\", slice.ident, g.typeName(), g.typeName())\n- g.emit(\"func MarshalUnsafe%s(src []%s, dst []byte) (int, error) {\\n\", slice.ident, g.typeName())\n+ g.emit(\"func MarshalUnsafe%s(src []%s, dst []byte) []byte {\\n\", slice.ident, g.typeName())\ng.inIndent(func() {\ng.emit(\"count := len(src)\\n\")\ng.emit(\"if count == 0 {\\n\")\ng.inIndent(func() {\n- g.emit(\"return 0, nil\\n\")\n+ g.emit(\"return dst\\n\")\n})\n- g.emit(\"}\\n\")\n- g.emit(\"size := (*%s)(nil).SizeBytes()\\n\\n\", g.typeName())\n+ g.emit(\"}\\n\\n\")\nfallback := func() {\ng.emit(\"// Type %s doesn't have a packed layout in memory, fall back to MarshalBytes.\\n\", g.typeName())\n@@ -562,7 +561,7 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.emit(\"dst = src[idx].MarshalBytes(dst)\\n\")\n})\ng.emit(\"}\\n\")\n- g.emit(\"return size * count, nil\\n\")\n+ g.emit(\"return dst\\n\")\n}\nif thisPacked {\ng.recordUsedImport(\"reflect\")\n@@ -574,9 +573,10 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.inIndent(fallback)\ng.emit(\"}\\n\\n\")\n}\n- g.emit(\"dst = dst[:size*count]\\n\")\n- g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&src[0]), uintptr(len(dst)))\\n\")\n- g.emit(\"return size * count, nil\\n\")\n+ g.emit(\"size := (*%s)(nil).SizeBytes()\\n\", g.typeName())\n+ g.emit(\"buf := dst[:size*count]\\n\")\n+ g.emit(\"gohacks.Memmove(unsafe.Pointer(&buf[0]), unsafe.Pointer(&src[0]), uintptr(len(buf)))\\n\")\n+ g.emit(\"return dst[size*count:]\\n\")\n} else {\nfallback()\n}\n@@ -584,15 +584,14 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.emit(\"}\\n\\n\")\ng.emit(\"// UnmarshalUnsafe%s is like %s.UnmarshalUnsafe, but for a []%s.\\n\", slice.ident, g.typeName(), g.typeName())\n- g.emit(\"func UnmarshalUnsafe%s(dst []%s, src []byte) (int, error) {\\n\", slice.ident, g.typeName())\n+ g.emit(\"func UnmarshalUnsafe%s(dst []%s, src []byte) []byte {\\n\", slice.ident, g.typeName())\ng.inIndent(func() {\ng.emit(\"count := len(dst)\\n\")\ng.emit(\"if count == 0 {\\n\")\ng.inIndent(func() {\n- g.emit(\"return 0, nil\\n\")\n+ g.emit(\"return src\\n\")\n})\n- g.emit(\"}\\n\")\n- g.emit(\"size := (*%s)(nil).SizeBytes()\\n\\n\", g.typeName())\n+ g.emit(\"}\\n\\n\")\nfallback := func() {\ng.emit(\"// Type %s doesn't have a packed layout in memory, fall back to UnmarshalBytes.\\n\", g.typeName())\n@@ -601,7 +600,7 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.emit(\"src = dst[idx].UnmarshalBytes(src)\\n\")\n})\ng.emit(\"}\\n\")\n- g.emit(\"return size * count, nil\\n\")\n+ g.emit(\"return src\\n\")\n}\nif thisPacked {\ng.recordUsedImport(\"gohacks\")\n@@ -613,10 +612,10 @@ func (g *interfaceGenerator) emitMarshallableSliceForStruct(st *ast.StructType,\ng.emit(\"}\\n\\n\")\n}\n- g.emit(\"src = src[:(size*count)]\\n\")\n- g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&src[0]), uintptr(len(src)))\\n\")\n-\n- g.emit(\"return count*size, nil\\n\")\n+ g.emit(\"size := (*%s)(nil).SizeBytes()\\n\", g.typeName())\n+ g.emit(\"buf := src[:size*count]\\n\")\n+ g.emit(\"gohacks.Memmove(unsafe.Pointer(&dst[0]), unsafe.Pointer(&buf[0]), uintptr(len(buf)))\\n\")\n+ g.emit(\"return src[size*count:]\\n\")\n} else {\nfallback()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Simplify {Un}MarshalUnsafeSlice method signatures.
Earlier this function was returning (int, error) much like the Copy{In/Out}
methods. The returned error was always nil. The returned int was never used.
Instead make it returned the shifted buffer which is more useful.
Updates #6450
PiperOrigin-RevId: 408268327 |
259,907 | 08.11.2021 09:41:41 | 28,800 | 55b70552c16232c19f31f1cf9413b8aebd525cda | Replace references of ConnectableEndpoint with BoundEndpoint. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/socket.go",
"new_path": "pkg/sentry/fs/gofer/socket.go",
"diff": "@@ -79,7 +79,7 @@ func sockTypeToP9(t linux.SockType) (p9.ConnectFlags, bool) {\nreturn 0, false\n}\n-// BidirectionalConnect implements ConnectableEndpoint.BidirectionalConnect.\n+// BidirectionalConnect implements BoundEndpoint.BidirectionalConnect.\nfunc (e *endpoint) BidirectionalConnect(ctx context.Context, ce transport.ConnectingEndpoint, returnConnect func(transport.Receiver, transport.ConnectedEndpoint)) *syserr.Error {\ncf, ok := sockTypeToP9(ce.Type())\nif !ok {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/socket.go",
"new_path": "pkg/sentry/fsimpl/gofer/socket.go",
"diff": "@@ -58,7 +58,7 @@ func sockTypeToP9(t linux.SockType) (p9.ConnectFlags, bool) {\nreturn 0, false\n}\n-// BidirectionalConnect implements ConnectableEndpoint.BidirectionalConnect.\n+// BidirectionalConnect implements BoundEndpoint.BidirectionalConnect.\nfunc (e *endpoint) BidirectionalConnect(ctx context.Context, ce transport.ConnectingEndpoint, returnConnect func(transport.Receiver, transport.ConnectedEndpoint)) *syserr.Error {\n// No lock ordering required as only the ConnectingEndpoint has a mutex.\nce.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"new_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"diff": "@@ -44,7 +44,7 @@ type ConnectingEndpoint interface {\n// Type returns the socket type, typically either SockStream or\n// SockSeqpacket. The connection attempt must be aborted if this\n- // value doesn't match the ConnectableEndpoint's type.\n+ // value doesn't match the BoundEndpoint's type.\nType() linux.SockType\n// GetLocalAddress returns the bound path.\n@@ -69,7 +69,7 @@ type ConnectingEndpoint interface {\n}\n// connectionedEndpoint is a Unix-domain connected or connectable endpoint and implements\n-// ConnectingEndpoint, ConnectableEndpoint and tcpip.Endpoint.\n+// ConnectingEndpoint, BoundEndpoint and tcpip.Endpoint.\n//\n// connectionedEndpoints must be in connected state in order to transfer data.\n//\n"
}
] | Go | Apache License 2.0 | google/gvisor | Replace references of ConnectableEndpoint with BoundEndpoint.
PiperOrigin-RevId: 408366542 |
259,907 | 08.11.2021 11:33:07 | 28,800 | 49d23beb283d0306c9ccf5300e73517153ddd3c2 | Allow array and primitive types with names starting with W. | [
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/gomarshal/generator_interfaces_array_newtype.go",
"new_path": "tools/go_marshal/gomarshal/generator_interfaces_array_newtype.go",
"diff": "@@ -139,11 +139,11 @@ func (g *interfaceGenerator) emitMarshallableForArrayNewtype(n *ast.Ident, a *as\ng.emit(\"}\\n\\n\")\ng.emit(\"// WriteTo implements io.WriterTo.WriteTo.\\n\")\n- g.emit(\"func (%s *%s) WriteTo(w io.Writer) (int64, error) {\\n\", g.r, g.typeName())\n+ g.emit(\"func (%s *%s) WriteTo(writer io.Writer) (int64, error) {\\n\", g.r, g.typeName())\ng.inIndent(func() {\ng.emitCastToByteSlice(g.r, \"buf\", fmt.Sprintf(\"%s.SizeBytes()\", g.r))\n- g.emit(\"length, err := w.Write(buf)\\n\")\n+ g.emit(\"length, err := writer.Write(buf)\\n\")\ng.emitKeepAlive(g.r)\ng.emit(\"return int64(length), err\\n\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_marshal/gomarshal/generator_interfaces_primitive_newtype.go",
"new_path": "tools/go_marshal/gomarshal/generator_interfaces_primitive_newtype.go",
"diff": "@@ -199,11 +199,11 @@ func (g *interfaceGenerator) emitMarshallableForPrimitiveNewtype(nt *ast.Ident)\ng.emit(\"}\\n\\n\")\ng.emit(\"// WriteTo implements io.WriterTo.WriteTo.\\n\")\n- g.emit(\"func (%s *%s) WriteTo(w io.Writer) (int64, error) {\\n\", g.r, g.typeName())\n+ g.emit(\"func (%s *%s) WriteTo(writer io.Writer) (int64, error) {\\n\", g.r, g.typeName())\ng.inIndent(func() {\ng.emitCastToByteSlice(g.r, \"buf\", fmt.Sprintf(\"%s.SizeBytes()\", g.r))\n- g.emit(\"length, err := w.Write(buf)\\n\")\n+ g.emit(\"length, err := writer.Write(buf)\\n\")\ng.emitKeepAlive(g.r)\ng.emit(\"return int64(length), err\\n\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow array and primitive types with names starting with W.
PiperOrigin-RevId: 408397832 |
259,853 | 09.11.2021 20:56:41 | 28,800 | 37792ee1e6e12fbc6fb81a5913846a5a80233f0c | Validate ControlMessageHeader.Length
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/BUILD",
"new_path": "pkg/sentry/socket/control/BUILD",
"diff": "@@ -37,6 +37,7 @@ go_test(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/binary\",\n+ \"//pkg/errors/linuxerr\",\n\"//pkg/hostarch\",\n\"//pkg/sentry/socket\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -503,7 +503,7 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte, width uint)\n}\nlength := int(h.Length) - linux.SizeOfControlMessageHeader\n- if length > len(buf) {\n+ if length < 0 || length > len(buf) {\nreturn socket.ControlMessages{}, linuxerr.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control_test.go",
"new_path": "pkg/sentry/socket/control/control_test.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/socket\"\n)\n@@ -57,3 +58,23 @@ func TestParse(t *testing.T) {\nt.Errorf(\"unexpected message parsed, (-want, +got):\\n%s\", diff)\n}\n}\n+\n+func TestParseRightsNegativeLength(t *testing.T) {\n+ // Craft the control message to parse.\n+ length := uint64(linux.SizeOfControlMessageHeader) + 128\n+ hdr := linux.ControlMessageHeader{\n+ Length: uint64(0xffffffff8f000000),\n+ Level: linux.SOL_SOCKET,\n+ Type: linux.SCM_RIGHTS,\n+ }\n+ hdrBuf := make([]byte, 0, length)\n+ hdrBuf = binary.Marshal(hdrBuf, hostarch.ByteOrder, &hdr)\n+\n+ buf := make([]byte, length)\n+ copy(buf, hdrBuf)\n+ cmsg, err := Parse(nil, nil, buf, 8 /* width */)\n+ if err != linuxerr.EINVAL {\n+ t.Fatalf(\"Parse(_, _, %+v, _): %v\", cmsg, err)\n+ }\n+\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Validate ControlMessageHeader.Length
Reported-by: [email protected]
PiperOrigin-RevId: 408776291 |
259,909 | 10.11.2021 14:09:13 | 28,800 | bb1ae811f4eb3ba59ab8e64672f06a83bc17fd4c | Prevent PacketBuffers from being returned to the pool too early in nic.
PacketBuffers were calling DecRef inside the forEach callback in
deliverOutboundPacket and DeliverNetworkPacket, even though
they were referenced in future iterations of the loop. This caused a
data race.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -740,6 +740,11 @@ func (n *nic) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\n// Deliver to interested packet endpoints without holding NIC lock.\nvar packetEPPkt *PacketBuffer\n+ defer func() {\n+ if packetEPPkt != nil {\n+ packetEPPkt.DecRef()\n+ }\n+ }()\ndeliverPacketEPs := func(ep PacketEndpoint) {\nif packetEPPkt == nil {\n// Packet endpoints hold the full packet.\n@@ -754,7 +759,6 @@ func (n *nic) DeliverNetworkPacket(remote, local tcpip.LinkAddress, protocol tcp\npacketEPPkt = NewPacketBuffer(PacketBufferOptions{\nData: PayloadSince(pkt.LinkHeader()).ToVectorisedView(),\n})\n- defer packetEPPkt.DecRef()\n// If a link header was populated in the original packet buffer, then\n// populate it in the packet buffer we provide to packet endpoints as\n// packet endpoints inspect link headers.\n@@ -799,6 +803,11 @@ func (n *nic) deliverOutboundPacket(remote tcpip.LinkAddress, pkt *PacketBuffer)\nlocal := n.LinkAddress()\nvar packetEPPkt *PacketBuffer\n+ defer func() {\n+ if packetEPPkt != nil {\n+ packetEPPkt.DecRef()\n+ }\n+ }()\neps.forEach(func(ep PacketEndpoint) {\nif packetEPPkt == nil {\n// Packet endpoints hold the full packet.\n@@ -814,7 +823,6 @@ func (n *nic) deliverOutboundPacket(remote tcpip.LinkAddress, pkt *PacketBuffer)\nReserveHeaderBytes: pkt.AvailableHeaderBytes(),\nData: PayloadSince(pkt.NetworkHeader()).ToVectorisedView(),\n})\n- defer packetEPPkt.DecRef()\n// Add the link layer header as outgoing packets are intercepted before\n// the link layer header is created and packet endpoints are interested\n// in the link header.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Prevent PacketBuffers from being returned to the pool too early in nic.
PacketBuffers were calling DecRef inside the forEach callback in
deliverOutboundPacket and DeliverNetworkPacket, even though
they were referenced in future iterations of the loop. This caused a
data race.
Reported-by: [email protected]
PiperOrigin-RevId: 408972907 |
259,992 | 10.11.2021 14:58:21 | 28,800 | ffc3a0d840f0a7027d2db9600544a1fbe5f8d004 | Fix socket permission
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"new_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"diff": "@@ -117,7 +117,7 @@ func NewDentry(ctx context.Context, mnt *vfs.Mount) *vfs.Dentry {\nfs := mnt.Filesystem().Impl().(*filesystem)\n// File mode matches net/socket.c:sock_alloc.\n- filemode := linux.FileMode(linux.S_IFSOCK | 0600)\n+ filemode := linux.FileMode(linux.S_IFSOCK | 0777)\ni := &inode{}\ni.InodeAttrs.Init(ctx, auth.CredentialsFromContext(ctx), linux.UNNAMED_MAJOR, fs.devMinor, fs.Filesystem.NextIno(), filemode)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket.cc",
"new_path": "test/syscalls/linux/socket.cc",
"diff": "@@ -183,6 +183,16 @@ TEST(SocketTest, UnixSCMRightsOnlyPassedOnce) {\nASSERT_TRUE(WIFEXITED(status) && WEXITSTATUS(status) == 0);\n}\n+TEST(SocketTest, Permission) {\n+ SKIP_IF(IsRunningWithVFS1());\n+\n+ FileDescriptor socket =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_DGRAM, 0));\n+\n+ auto stat = ASSERT_NO_ERRNO_AND_VALUE(Fstat(socket.get()));\n+ EXPECT_EQ(0777, stat.st_mode & ~S_IFMT);\n+}\n+\nusing SocketOpenTest = ::testing::TestWithParam<int>;\n// UDS cannot be opened.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix socket permission
Closes #6773
PiperOrigin-RevId: 408984647 |
259,992 | 10.11.2021 17:04:36 | 28,800 | 07836a3ff1b0c4612afe80e5914cb637a39f8f0b | Implement ioctl(fd, FIONREAD) for host FDs
Closes | [
{
"change_type": "MODIFY",
"old_path": "images/basic/integrationtest/Dockerfile.x86_64",
"new_path": "images/basic/integrationtest/Dockerfile.x86_64",
"diff": "@@ -11,3 +11,4 @@ RUN gcc -O2 -o test_copy_up test_copy_up.c\nRUN gcc -O2 -o test_rewinddir test_rewinddir.c\nRUN gcc -O2 -o link_test link_test.c\nRUN gcc -O2 -o test_sticky test_sticky.c\n+RUN gcc -O2 -o host_fd host_fd.c\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/basic/integrationtest/host_fd.c",
"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 <err.h>\n+#include <sys/ioctl.h>\n+#include <unistd.h>\n+\n+// Tests that FIONREAD is supported with host FD.\n+int main(int argc, char** argv) {\n+ int size = 0;\n+ if (ioctl(STDOUT_FILENO, FIONREAD, &size) < 0) {\n+ err(1, \"ioctl(stdin, FIONREAD)\");\n+ }\n+ if (size != 0) {\n+ err(1, \"FIONREAD wrong size, want: 0, got: %d\", size);\n+ }\n+ return 0;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -31,6 +31,7 @@ go_library(\n\"connected_endpoint_refs.go\",\n\"control.go\",\n\"host.go\",\n+ \"host_unsafe.go\",\n\"inode_refs.go\",\n\"ioctl_unsafe.go\",\n\"save_restore.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -29,6 +29,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/hostfd\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -910,3 +911,21 @@ func (f *fileDescription) EventUnregister(e *waiter.Entry) {\nfunc (f *fileDescription) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn fdnotifier.NonBlockingPoll(int32(f.inode.hostFD), mask)\n}\n+\n+// Ioctl queries the underlying FD for allowed ioctl commands.\n+func (f *fileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.SyscallArguments) (uintptr, error) {\n+ switch cmd := args[1].Int(); cmd {\n+ case linux.FIONREAD:\n+ v, err := ioctlFionread(f.inode.hostFD)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ var buf [4]byte\n+ hostarch.ByteOrder.PutUint32(buf[:], v)\n+ _, err = uio.CopyOut(ctx, args[2].Pointer(), buf[:], usermem.IOOpts{})\n+ return 0, err\n+ }\n+\n+ return f.FileDescriptionDefaultImpl.Ioctl(ctx, uio, args)\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/host/host_unsafe.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 host\n+\n+import (\n+ \"unsafe\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+func ioctlFionread(fd int) (uint32, error) {\n+ var v uint32\n+ if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), linux.FIONREAD, uintptr(unsafe.Pointer(&v))); errno != 0 {\n+ return 0, errno\n+ }\n+ return v, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -134,9 +134,15 @@ var allowedSyscalls = seccomp.SyscallRules{\n},\nunix.SYS_GETTID: {},\nunix.SYS_GETTIMEOFDAY: {},\n- // SYS_IOCTL is needed for terminal support, but we only allow\n- // setting/getting termios and winsize.\nunix.SYS_IOCTL: []seccomp.Rule{\n+ // These commands are needed for host FD.\n+ {\n+ seccomp.MatchAny{}, /* fd */\n+ seccomp.EqualTo(linux.FIONREAD),\n+ seccomp.MatchAny{}, /* int* */\n+ },\n+ // These commands are needed for terminal support, but we only allow\n+ // setting/getting termios and winsize.\n{\nseccomp.MatchAny{}, /* fd */\nseccomp.EqualTo(linux.TCGETS),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -612,6 +612,16 @@ func TestStickyDir(t *testing.T) {\nrunIntegrationTest(t, nil, \"./test_sticky\")\n}\n+func TestHostFD(t *testing.T) {\n+ if vfs2Used, err := dockerutil.UsingVFS2(); err != nil {\n+ t.Fatalf(\"failed to read config for runtime %s: %v\", dockerutil.Runtime(), err)\n+ } else if !vfs2Used {\n+ t.Skip(\"test fails on VFS1.\")\n+ }\n+\n+ runIntegrationTest(t, nil, \"./host_fd\")\n+}\n+\nfunc runIntegrationTest(t *testing.T, capAdd []string, args ...string) {\nctx := context.Background()\nd := dockerutil.MakeContainer(ctx, t)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement ioctl(fd, FIONREAD) for host FDs
Closes #6796
PiperOrigin-RevId: 409013591 |
259,992 | 11.11.2021 11:22:03 | 28,800 | 83eb263b454882a20e4a8920ac2e082cf9d78001 | Make more cgroup controllers optional
Mark all noop cgroups as optional, after all there is no harm in skipping them.
Make pids cgroup optional because they are not present on Synology NAS.
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -57,7 +57,7 @@ var controllers = map[string]controller{\n\"devices\": &noop{},\n\"freezer\": &noop{},\n\"perf_event\": &noop{},\n- \"rdma\": &noop{isOptional: true},\n+ \"rdma\": &noop{},\n\"systemd\": &noop{},\n}\n@@ -599,12 +599,10 @@ type controller interface {\nskip(*specs.LinuxResources) error\n}\n-type noop struct {\n- isOptional bool\n-}\n+type noop struct{}\nfunc (n *noop) optional() bool {\n- return n.isOptional\n+ return true\n}\nfunc (*noop) set(*specs.LinuxResources, string) error {\n@@ -612,9 +610,6 @@ func (*noop) set(*specs.LinuxResources, string) error {\n}\nfunc (n *noop) skip(*specs.LinuxResources) error {\n- if !n.isOptional {\n- panic(\"cgroup controller is not optional\")\n- }\nreturn nil\n}\n@@ -808,8 +803,17 @@ func (*networkPrio) skip(spec *specs.LinuxResources) error {\nreturn nil\n}\n-type pids struct {\n- mandatory\n+type pids struct{}\n+\n+func (*pids) optional() bool {\n+ return true\n+}\n+\n+func (*pids) skip(spec *specs.LinuxResources) error {\n+ if spec != nil && spec.Pids != nil && spec.Pids.Limit > 0 {\n+ return fmt.Errorf(\"Pids.Limit set but pids cgroup controller not found\")\n+ }\n+ return nil\n}\nfunc (*pids) set(spec *specs.LinuxResources, path string) error {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup_test.go",
"new_path": "runsc/cgroup/cgroup_test.go",
"diff": "@@ -863,6 +863,12 @@ func TestOptional(t *testing.T) {\nspec *specs.LinuxResources\nerr string\n}{\n+ {\n+ name: \"pids\",\n+ ctrlr: &pids{},\n+ spec: &specs.LinuxResources{Pids: &specs.LinuxPids{Limit: 1}},\n+ err: \"Pids.Limit set but pids cgroup controller not found\",\n+ },\n{\nname: \"net-cls\",\nctrlr: &networkClass{},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make more cgroup controllers optional
Mark all noop cgroups as optional, after all there is no harm in skipping them.
Make pids cgroup optional because they are not present on Synology NAS.
Closes #6856
PiperOrigin-RevId: 409197613 |
259,896 | 11.11.2021 13:09:37 | 28,800 | 5202e4f1781079708414b2f2e52523d7f117c865 | Fix typo and bazel output binary path. | [
{
"change_type": "MODIFY",
"old_path": "test/iptables/README.md",
"new_path": "test/iptables/README.md",
"diff": "@@ -17,7 +17,7 @@ iptables require some extra Docker configuration to work. Enable IPv6 in\nAnd if you're running manually (i.e. not using the `make` target), you'll need\nto:\n-* Enable iptables via `modprobe iptables_filter && modprobe ip6table_filter`.\n+* Enable iptables via `modprobe iptable_filter && modprobe ip6table_filter`.\n* Enable `--net-raw` in your chosen runtime in `/etc/docker/daemon.json` (make\nsure to restart Docker if you change this file).\n@@ -61,7 +61,7 @@ Your test is now runnable with bazel!\nBuild and install `runsc`. Re-run this when you modify gVisor:\n```bash\n-$ bazel build //runsc && sudo cp bazel-bin/runsc/linux_amd64_pure_stripped/runsc $(which runsc)\n+$ bazel build //runsc && sudo cp bazel-out/k8-fastbuild-ST-4c64f0b3d5c7/bin/runsc/runsc_/runsc $(which runsc)\n```\nBuild the testing Docker container. Re-run this when you modify the test code in\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix typo and bazel output binary path.
PiperOrigin-RevId: 409224559 |
260,004 | 11.11.2021 15:54:11 | 28,800 | 6961f3ef47257e88a4b147dce4948c73397da3f3 | Handle source port conflicts
This change also updates the ConnTrack seed to be generated by the
stack's random generator instead of using the stack's seed.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"bytes\"\n\"errors\"\n\"fmt\"\n+ \"math/rand\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n@@ -58,8 +59,8 @@ var nameToID = map[string]stack.TableID{\n// DefaultLinuxTables returns the rules of stack.DefaultTables() wrapped for\n// compatibility with netfilter extensions.\n-func DefaultLinuxTables(seed uint32, clock tcpip.Clock) *stack.IPTables {\n- tables := stack.DefaultTables(seed, clock)\n+func DefaultLinuxTables(clock tcpip.Clock, rand *rand.Rand) *stack.IPTables {\n+ tables := stack.DefaultTables(clock, rand)\ntables.VisitTargets(func(oldTarget stack.Target) stack.Target {\nswitch val := oldTarget.(type) {\ncase *stack.AcceptTarget:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -17,6 +17,7 @@ package stack\nimport (\n\"encoding/binary\"\n\"fmt\"\n+ \"math/rand\"\n\"sync\"\n\"time\"\n@@ -195,6 +196,7 @@ type ConnTrack struct {\n// clock provides timing used to determine conntrack reapings.\nclock tcpip.Clock\n+ rand *rand.Rand\nmu sync.RWMutex `state:\"nosave\"`\n// mu protects the buckets slice, but not buckets' contents. Only take\n@@ -491,6 +493,9 @@ func (ct *ConnTrack) finalize(cn *conn) {\n// send packets but its responses will be mapped to some other connection.\n// This may be okay if the connection only expects to send packets without\n// any responses.\n+ //\n+ // TODO(https://gvisor.dev/issue/6850): Investigate handling this clash\n+ // better.\nreturn\n}\n@@ -522,12 +527,17 @@ func (cn *conn) finalize() {\n//\n// Generally, only the first packet of a connection reaches this method; other\n// other packets will be manipulated without needing to modify the connection.\n-func (cn *conn) performNAT(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address, dnat bool) {\n- cn.performNATIfNoop(port, address, dnat)\n+func (cn *conn) performNAT(pkt *PacketBuffer, hook Hook, r *Route, ports portRange, address tcpip.Address, dnat bool) {\n+ cn.performNATIfNoop(ports, address, dnat)\ncn.handlePacket(pkt, hook, r)\n}\n-func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool) {\n+type portRange struct {\n+ start uint16\n+ size uint16\n+}\n+\n+func (cn *conn) performNATIfNoop(ports portRange, address tcpip.Address, dnat bool) {\ncn.mu.Lock()\ndefer cn.mu.Unlock()\n@@ -535,30 +545,80 @@ func (cn *conn) performNATIfNoop(port uint16, address tcpip.Address, dnat bool)\nreturn\n}\n+ cn.reply.mu.Lock()\n+ defer cn.reply.mu.Unlock()\n+\n+ var port *uint16\nif dnat {\nif cn.destinationManip {\nreturn\n}\ncn.destinationManip = true\n+\n+ cn.reply.tupleID.srcAddr = address\n+ port = &cn.reply.tupleID.srcPort\n} else {\nif cn.sourceManip {\nreturn\n}\ncn.sourceManip = true\n+\n+ cn.reply.tupleID.dstAddr = address\n+ port = &cn.reply.tupleID.dstPort\n}\n- cn.reply.mu.Lock()\n- defer cn.reply.mu.Unlock()\n+ // Does the current port fit in the range?\n+ if end := ports.start + ports.size - 1; *port >= ports.start && *port <= end {\n+ // Yes, is the current reply tuple unique?\n+ if other := cn.ct.connForTID(cn.reply.tupleID); other == nil {\n+ // Yes! No need to change the port.\n+ return\n+ }\n+ }\n- if dnat {\n- cn.reply.tupleID.srcAddr = address\n- cn.reply.tupleID.srcPort = port\n- } else {\n- cn.reply.tupleID.dstAddr = address\n- cn.reply.tupleID.dstPort = port\n+ // Try our best to find a port that results in a unique reply tuple.\n+ //\n+ // We limit the number of attempts to find a unique tuple to not waste a lot\n+ // of time looking for a unique tuple.\n+ //\n+ // Matches linux behaviour introduced in\n+ // https://github.com/torvalds/linux/commit/a504b703bb1da526a01593da0e4be2af9d9f5fa8.\n+ const maxAttemptsForInitialRound uint16 = 128\n+ const minAttemptsToContinue = 16\n+\n+ allowedInitialAttempts := maxAttemptsForInitialRound\n+ if allowedInitialAttempts > ports.size {\n+ allowedInitialAttempts = ports.size\n+ }\n+\n+ for maxAttempts := allowedInitialAttempts; ; maxAttempts /= 2 {\n+ // Start reach round with a random initial port in the range.\n+ initial := ports.start + uint16(cn.ct.rand.Uint32())%ports.size\n+\n+ for i := uint16(0); i < maxAttempts; i++ {\n+ *port = initial + i%ports.size\n+\n+ if other := cn.ct.connForTID(cn.reply.tupleID); other == nil {\n+ // We found a unique tuple!\n+ return\n}\n}\n+ if maxAttempts == ports.size {\n+ // We already tried all the ports in the range so no need to keep trying.\n+ return\n+ }\n+\n+ if maxAttempts < minAttemptsToContinue {\n+ return\n+ }\n+ }\n+\n+ // We did not find a unique tuple, use the last used port anyways.\n+ // TODO(https://gvisor.dev/issue/6850): Handle not finding a unique tuple\n+ // better (e.g. remove the connection and drop the packet).\n+}\n+\n// handlePacket attempts to handle a packet and perform NAT if the connection\n// has had NAT performed on it.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -16,6 +16,7 @@ package stack\nimport (\n\"fmt\"\n+ \"math/rand\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -42,7 +43,7 @@ const reaperDelay = 5 * time.Second\n// DefaultTables returns a default set of tables. Each chain is set to accept\n// all packets.\n-func DefaultTables(seed uint32, clock tcpip.Clock) *IPTables {\n+func DefaultTables(clock tcpip.Clock, rand *rand.Rand) *IPTables {\nreturn &IPTables{\nv4Tables: [NumTables]Table{\nNATID: {\n@@ -182,8 +183,9 @@ func DefaultTables(seed uint32, clock tcpip.Clock) *IPTables {\nPostrouting: {MangleID, NATID},\n},\nconnections: ConnTrack{\n- seed: seed,\n+ seed: rand.Uint32(),\nclock: clock,\n+ rand: rand,\n},\nreaperDone: make(chan struct{}, 1),\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -16,6 +16,7 @@ package stack\nimport (\n\"fmt\"\n+ \"math\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -118,7 +119,7 @@ func (rt *DNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP A\npanic(fmt.Sprintf(\"%s unrecognized\", hook))\n}\n- return natAction(pkt, hook, r, rt.Port, rt.Addr, true /* dnat */)\n+ return dnatAction(pkt, hook, r, rt.Port, rt.Addr)\n}\n@@ -161,7 +162,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, address\npanic(\"redirect target is supported only on output and prerouting hooks\")\n}\n- return natAction(pkt, hook, r, rt.Port, address, true /* dnat */)\n+ return dnatAction(pkt, hook, r, rt.Port, address)\n}\n// SNATTarget modifies the source port/IP in the outgoing packets.\n@@ -174,20 +175,19 @@ type SNATTarget struct {\nNetworkProtocol tcpip.NetworkProtocolNumber\n}\n-func natAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address, dnat bool) (RuleVerdict, int) {\n- // Drop the packet if network and transport header are not set.\n- if pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n- return RuleDrop, 0\n- }\n-\n- t := pkt.tuple\n- if t == nil {\n- return RuleDrop, 0\n+func dnatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address) (RuleVerdict, int) {\n+ return natAction(pkt, hook, r, portRange{start: port, size: 1}, address, true /* dnat */)\n}\n- // TODO(https://gvisor.dev/issue/5773): If the port is in use, pick a\n- // different port.\n+func snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address) (RuleVerdict, int) {\n+ ports := portRange{start: port, size: 1}\nif port == 0 {\n+ // As per iptables(8),\n+ //\n+ // If no port range is specified, then source ports below 512 will be\n+ // mapped to other ports below 512: those between 512 and 1023 inclusive\n+ // will be mapped to ports below 1024, and other ports will be mapped to\n+ // 1024 or above.\nswitch protocol := pkt.TransportProtocolNumber; protocol {\ncase header.UDPProtocolNumber:\nport = header.UDP(pkt.TransportHeader().View()).SourcePort()\n@@ -196,12 +196,34 @@ func natAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpi\ndefault:\npanic(fmt.Sprintf(\"unsupported transport protocol = %d\", pkt.TransportProtocolNumber))\n}\n+\n+ switch {\n+ case port < 512:\n+ ports = portRange{start: 1, size: 511}\n+ case port < 1024:\n+ ports = portRange{start: 1, size: 1023}\n+ default:\n+ ports = portRange{start: 1024, size: math.MaxUint16 - 1023}\n+ }\n}\n- t.conn.performNAT(pkt, hook, r, port, address, dnat)\n+ return natAction(pkt, hook, r, ports, address, false /* dnat */)\n+}\n+\n+func natAction(pkt *PacketBuffer, hook Hook, r *Route, ports portRange, address tcpip.Address, dnat bool) (RuleVerdict, int) {\n+ // Drop the packet if network and transport header are not set.\n+ if pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n+ return RuleDrop, 0\n+ }\n+\n+ if t := pkt.tuple; t != nil {\n+ t.conn.performNAT(pkt, hook, r, ports, address, dnat)\nreturn RuleAccept, 0\n}\n+ return RuleDrop, 0\n+}\n+\n// Action implements Target.Action.\nfunc (st *SNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, _ AddressableEndpoint) (RuleVerdict, int) {\n// Sanity check.\n@@ -219,7 +241,7 @@ func (st *SNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, _ Addressab\npanic(fmt.Sprintf(\"%s unrecognized\", hook))\n}\n- return natAction(pkt, hook, r, st.Port, st.Addr, false /* dnat */)\n+ return snatAction(pkt, hook, r, st.Port, st.Addr)\n}\n// MasqueradeTarget modifies the source port/IP in the outgoing packets.\n@@ -255,7 +277,7 @@ func (mt *MasqueradeTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addre\naddress := ep.AddressWithPrefix().Address\nep.DecRef()\n- return natAction(pkt, hook, r, 0 /* port */, address, false /* dnat */)\n+ return snatAction(pkt, hook, r, 0 /* port */, address)\n}\nfunc rewritePacket(n header.Network, t header.ChecksummableTransport, updateSRCFields, fullChecksum, updatePseudoHeader bool, newPort uint16, newAddr tcpip.Address) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_test.go",
"new_path": "pkg/tcpip/stack/iptables_test.go",
"diff": "package stack\nimport (\n+ \"math/rand\"\n\"testing\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -39,7 +40,7 @@ func TestNATedConnectionReap(t *testing.T) {\n)\nclock := faketime.NewManualClock()\n- iptables := DefaultTables(0 /* seed */, clock)\n+ iptables := DefaultTables(clock, rand.New(rand.NewSource(0 /* seed */)))\ntable := Table{\nRules: []Rule{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -238,7 +238,7 @@ type Options struct {\n// DefaultIPTables is an optional iptables rules constructor that is called\n// if IPTables is nil. If both fields are nil, iptables will allow all\n// traffic.\n- DefaultIPTables func(seed uint32, clock tcpip.Clock) *IPTables\n+ DefaultIPTables func(clock tcpip.Clock, rand *rand.Rand) *IPTables\n// SecureRNG is a cryptographically secure random number generator.\nSecureRNG io.Reader\n@@ -353,12 +353,11 @@ func New(opts Options) *Stack {\n}\nrandomGenerator := rand.New(randSrc)\n- seed := randomGenerator.Uint32()\nif opts.IPTables == nil {\nif opts.DefaultIPTables == nil {\nopts.DefaultIPTables = DefaultTables\n}\n- opts.IPTables = opts.DefaultIPTables(seed, clock)\n+ opts.IPTables = opts.DefaultIPTables(clock, randomGenerator)\n}\nopts.NUDConfigs.resetInvalidFields()\n@@ -376,7 +375,7 @@ func New(opts Options) *Stack {\nhandleLocal: opts.HandleLocal,\ntables: opts.IPTables,\nicmpRateLimiter: NewICMPRateLimiter(clock),\n- seed: seed,\n+ seed: randomGenerator.Uint32(),\nnudConfigs: opts.NUDConfigs,\nuniqueIDGenerator: opts.UniqueID,\nnudDisp: opts.NUDDisp,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -16,6 +16,8 @@ package iptables_test\nimport (\n\"bytes\"\n+ \"fmt\"\n+ \"math\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -1780,27 +1782,7 @@ func TestNAT(t *testing.T) {\n}\n}\n-func TestNATICMPError(t *testing.T) {\n- const (\n- srcPort = 1234\n- dstPort = 5432\n- dataSize = 4\n- )\n-\n- type icmpTypeTest struct {\n- name string\n- val uint8\n- expectResponse bool\n- }\n-\n- type transportTypeTest struct {\n- name string\n- proto tcpip.TransportProtocolNumber\n- buf buffer.View\n- checkNATed func(*testing.T, buffer.View)\n- }\n-\n- ipHdr := func(v buffer.View, totalLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\n+func encodeIPv4Header(v buffer.View, totalLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\nip := header.IPv4(v)\nip.Encode(&header.IPv4Fields{\nTotalLength: uint16(totalLen),\n@@ -1812,7 +1794,7 @@ func TestNATICMPError(t *testing.T) {\nip.SetChecksum(^ip.CalculateChecksum())\n}\n- ip6Hdr := func(v buffer.View, payloadLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\n+func encodeIPv6Header(v buffer.View, payloadLen int, transProto tcpip.TransportProtocolNumber, srcAddr, dstAddr tcpip.Address) {\nip := header.IPv6(v)\nip.Encode(&header.IPv6Fields{\nPayloadLength: uint16(payloadLen),\n@@ -1823,6 +1805,120 @@ func TestNATICMPError(t *testing.T) {\n})\n}\n+func udpv4Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSize int) buffer.View {\n+ udpSize := header.UDPMinimumSize + dataSize\n+ hdr := buffer.NewPrependable(header.IPv4MinimumSize + udpSize)\n+ udp := header.UDP(hdr.Prepend(udpSize))\n+ udp.SetSourcePort(srcPort)\n+ udp.SetDestinationPort(dstPort)\n+ udp.SetChecksum(0)\n+ udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.UDPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ uint16(len(udp)),\n+ )))\n+ encodeIPv4Header(\n+ hdr.Prepend(header.IPv4MinimumSize),\n+ hdr.UsedLength(),\n+ header.UDPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ )\n+ return hdr.View()\n+}\n+\n+func tcpv4Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSize int) buffer.View {\n+ tcpSize := header.TCPMinimumSize + dataSize\n+ hdr := buffer.NewPrependable(header.IPv4MinimumSize + tcpSize)\n+ tcp := header.TCP(hdr.Prepend(tcpSize))\n+ tcp.SetSourcePort(srcPort)\n+ tcp.SetDestinationPort(dstPort)\n+ tcp.SetDataOffset(header.TCPMinimumSize)\n+ tcp.SetChecksum(0)\n+ tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.TCPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ uint16(len(tcp)),\n+ )))\n+ encodeIPv4Header(\n+ hdr.Prepend(header.IPv4MinimumSize),\n+ hdr.UsedLength(),\n+ header.TCPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ )\n+ return hdr.View()\n+}\n+\n+func udpv6Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSize int) buffer.View {\n+ udpSize := header.UDPMinimumSize + dataSize\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + udpSize)\n+ udp := header.UDP(hdr.Prepend(udpSize))\n+ udp.SetSourcePort(srcPort)\n+ udp.SetDestinationPort(dstPort)\n+ udp.SetChecksum(0)\n+ udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.UDPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ uint16(len(udp)),\n+ )))\n+ encodeIPv6Header(\n+ hdr.Prepend(header.IPv6MinimumSize),\n+ len(udp),\n+ header.UDPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ )\n+ return hdr.View()\n+}\n+\n+func tcpv6Packet(srcAddr, dstAddr tcpip.Address, srcPort, dstPort uint16, dataSize int) buffer.View {\n+ tcpSize := header.TCPMinimumSize + dataSize\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + tcpSize)\n+ tcp := header.TCP(hdr.Prepend(tcpSize))\n+ tcp.SetSourcePort(srcPort)\n+ tcp.SetDestinationPort(dstPort)\n+ tcp.SetDataOffset(header.TCPMinimumSize)\n+ tcp.SetChecksum(0)\n+ tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n+ header.TCPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ uint16(len(tcp)),\n+ )))\n+ encodeIPv6Header(\n+ hdr.Prepend(header.IPv6MinimumSize),\n+ len(tcp),\n+ header.TCPProtocolNumber,\n+ srcAddr,\n+ dstAddr,\n+ )\n+ return hdr.View()\n+}\n+\n+func TestNATICMPError(t *testing.T) {\n+ const (\n+ srcPort = 1234\n+ dstPort = 5432\n+ dataSize = 4\n+ )\n+\n+ type icmpTypeTest struct {\n+ name string\n+ val uint8\n+ expectResponse bool\n+ }\n+\n+ type transportTypeTest struct {\n+ name string\n+ proto tcpip.TransportProtocolNumber\n+ buf buffer.View\n+ checkNATed func(*testing.T, buffer.View)\n+ }\n+\ntests := []struct {\nname string\nnetProto tcpip.NetworkProtocolNumber\n@@ -1847,7 +1943,7 @@ func TestNATICMPError(t *testing.T) {\nicmp.SetType(header.ICMPv4Type(icmpType))\nicmp.SetChecksum(0)\nicmp.SetChecksum(header.ICMPv4Checksum(icmp, 0))\n- ipHdr(\n+ encodeIPv4Header(\nhdr.Prepend(header.IPv4MinimumSize),\nhdr.UsedLength(),\nheader.ICMPv4ProtocolNumber,\n@@ -1878,26 +1974,7 @@ func TestNATICMPError(t *testing.T) {\nname: \"UDP\",\nproto: header.UDPProtocolNumber,\nbuf: func() buffer.View {\n- udpSize := header.UDPMinimumSize + dataSize\n- hdr := buffer.NewPrependable(header.IPv4MinimumSize + udpSize)\n- udp := header.UDP(hdr.Prepend(udpSize))\n- udp.SetSourcePort(srcPort)\n- udp.SetDestinationPort(dstPort)\n- udp.SetChecksum(0)\n- udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n- header.UDPProtocolNumber,\n- utils.Host2IPv4Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n- uint16(len(udp)),\n- )))\n- ipHdr(\n- hdr.Prepend(header.IPv4MinimumSize),\n- hdr.UsedLength(),\n- header.UDPProtocolNumber,\n- utils.Host2IPv4Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n- )\n- return hdr.View()\n+ return udpv4Packet(utils.Host2IPv4Addr.AddressWithPrefix.Address, utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address, srcPort, dstPort, dataSize)\n}(),\ncheckNATed: func(t *testing.T, v buffer.View) {\nchecker.IPv4(t, v,\n@@ -1914,27 +1991,7 @@ func TestNATICMPError(t *testing.T) {\nname: \"TCP\",\nproto: header.TCPProtocolNumber,\nbuf: func() buffer.View {\n- tcpSize := header.TCPMinimumSize + dataSize\n- hdr := buffer.NewPrependable(header.IPv4MinimumSize + tcpSize)\n- tcp := header.TCP(hdr.Prepend(tcpSize))\n- tcp.SetSourcePort(srcPort)\n- tcp.SetDestinationPort(dstPort)\n- tcp.SetDataOffset(header.TCPMinimumSize)\n- tcp.SetChecksum(0)\n- tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n- header.TCPProtocolNumber,\n- utils.Host2IPv4Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n- uint16(len(tcp)),\n- )))\n- ipHdr(\n- hdr.Prepend(header.IPv4MinimumSize),\n- hdr.UsedLength(),\n- header.TCPProtocolNumber,\n- utils.Host2IPv4Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address,\n- )\n- return hdr.View()\n+ return tcpv4Packet(utils.Host2IPv4Addr.AddressWithPrefix.Address, utils.RouterNIC2IPv4Addr.AddressWithPrefix.Address, srcPort, dstPort, dataSize)\n}(),\ncheckNATed: func(t *testing.T, v buffer.View) {\nchecker.IPv4(t, v,\n@@ -1994,7 +2051,7 @@ func TestNATICMPError(t *testing.T) {\nSrc: utils.Host1IPv6Addr.AddressWithPrefix.Address,\nDst: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n}))\n- ip6Hdr(\n+ encodeIPv6Header(\nhdr.Prepend(header.IPv6MinimumSize),\npayloadLen,\nheader.ICMPv6ProtocolNumber,\n@@ -2022,26 +2079,7 @@ func TestNATICMPError(t *testing.T) {\nname: \"UDP\",\nproto: header.UDPProtocolNumber,\nbuf: func() buffer.View {\n- udpSize := header.UDPMinimumSize + dataSize\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + udpSize)\n- udp := header.UDP(hdr.Prepend(udpSize))\n- udp.SetSourcePort(srcPort)\n- udp.SetDestinationPort(dstPort)\n- udp.SetChecksum(0)\n- udp.SetChecksum(^udp.CalculateChecksum(header.PseudoHeaderChecksum(\n- header.UDPProtocolNumber,\n- utils.Host2IPv6Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n- uint16(len(udp)),\n- )))\n- ip6Hdr(\n- hdr.Prepend(header.IPv6MinimumSize),\n- len(udp),\n- header.UDPProtocolNumber,\n- utils.Host2IPv6Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n- )\n- return hdr.View()\n+ return udpv6Packet(utils.Host2IPv6Addr.AddressWithPrefix.Address, utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address, srcPort, dstPort, dataSize)\n}(),\ncheckNATed: func(t *testing.T, v buffer.View) {\nchecker.IPv6(t, v,\n@@ -2058,27 +2096,7 @@ func TestNATICMPError(t *testing.T) {\nname: \"TCP\",\nproto: header.TCPProtocolNumber,\nbuf: func() buffer.View {\n- tcpSize := header.TCPMinimumSize + dataSize\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + tcpSize)\n- tcp := header.TCP(hdr.Prepend(tcpSize))\n- tcp.SetSourcePort(srcPort)\n- tcp.SetDestinationPort(dstPort)\n- tcp.SetDataOffset(header.TCPMinimumSize)\n- tcp.SetChecksum(0)\n- tcp.SetChecksum(^tcp.CalculateChecksum(header.PseudoHeaderChecksum(\n- header.TCPProtocolNumber,\n- utils.Host2IPv6Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n- uint16(len(tcp)),\n- )))\n- ip6Hdr(\n- hdr.Prepend(header.IPv6MinimumSize),\n- len(tcp),\n- header.TCPProtocolNumber,\n- utils.Host2IPv6Addr.AddressWithPrefix.Address,\n- utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address,\n- )\n- return hdr.View()\n+ return tcpv6Packet(utils.Host2IPv6Addr.AddressWithPrefix.Address, utils.RouterNIC2IPv6Addr.AddressWithPrefix.Address, srcPort, dstPort, dataSize)\n}(),\ncheckNATed: func(t *testing.T, v buffer.View) {\nchecker.IPv6(t, v,\n@@ -2269,3 +2287,282 @@ func TestNATICMPError(t *testing.T) {\n})\n}\n}\n+\n+func TestSNATHandlePortConflicts(t *testing.T) {\n+ const dstPort = 5432\n+\n+ type portRange struct {\n+ first uint16\n+ last uint16\n+ }\n+\n+ type transportTypeTest struct {\n+ name string\n+ proto tcpip.TransportProtocolNumber\n+ buf func(tcpip.Address, uint16) buffer.View\n+ checkNATed func(*testing.T, buffer.View, uint16, bool, portRange)\n+ }\n+\n+ compareSrcPort := func(t *testing.T, gotPort uint16, originalSrcPort uint16, firstPacket bool, expectedRange portRange) {\n+ t.Helper()\n+\n+ if firstPacket {\n+ if gotPort != originalSrcPort {\n+ t.Errorf(\"got port = %d, want = %d\", gotPort, originalSrcPort)\n+ }\n+ return\n+ }\n+\n+ if gotPort < expectedRange.first || gotPort > expectedRange.last {\n+ t.Errorf(\"got port = %d, want in range [%d, %d]\", gotPort, expectedRange.first, expectedRange.last)\n+ }\n+ }\n+\n+ tests := []struct {\n+ name string\n+ netProto tcpip.NetworkProtocolNumber\n+ routerNIC1Addr tcpip.Address\n+ srcAddrs []tcpip.Address\n+ transportTypes []transportTypeTest\n+ }{\n+ {\n+ name: \"IPv4\",\n+ netProto: ipv4.ProtocolNumber,\n+ routerNIC1Addr: utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address,\n+ srcAddrs: []tcpip.Address{\n+ utils.Ipv4Addr1.AddressWithPrefix.Address,\n+ utils.Ipv4Addr2.AddressWithPrefix.Address,\n+ utils.Ipv4Addr3.AddressWithPrefix.Address,\n+ },\n+ transportTypes: []transportTypeTest{\n+ {\n+ name: \"UDP\",\n+ proto: header.UDPProtocolNumber,\n+ buf: func(srcAddr tcpip.Address, srcPort uint16) buffer.View {\n+ return udpv4Packet(srcAddr, utils.Host1IPv4Addr.AddressWithPrefix.Address, srcPort, dstPort, 0 /* dataSize */)\n+ },\n+ checkNATed: func(t *testing.T, v buffer.View, originalSrcPort uint16, firstPacket bool, expectedRange portRange) {\n+ checker.IPv4(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv4Addr.AddressWithPrefix.Address),\n+ checker.UDP(\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+\n+ if !t.Failed() {\n+ compareSrcPort(t, header.UDP(header.IPv4(v).Payload()).SourcePort(), originalSrcPort, firstPacket, expectedRange)\n+ }\n+ },\n+ },\n+ {\n+ name: \"TCP\",\n+ proto: header.TCPProtocolNumber,\n+ buf: func(srcAddr tcpip.Address, srcPort uint16) buffer.View {\n+ return tcpv4Packet(srcAddr, utils.Host1IPv4Addr.AddressWithPrefix.Address, srcPort, dstPort, 0 /* dataSize */)\n+ },\n+ checkNATed: func(t *testing.T, v buffer.View, originalSrcPort uint16, firstPacket bool, expectedRange portRange) {\n+ checker.IPv4(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv4Addr.AddressWithPrefix.Address),\n+ checker.TCP(\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+\n+ if !t.Failed() {\n+ compareSrcPort(t, header.TCP(header.IPv4(v).Payload()).SourcePort(), originalSrcPort, firstPacket, expectedRange)\n+ }\n+ },\n+ },\n+ },\n+ },\n+ {\n+ name: \"IPv6\",\n+ netProto: ipv6.ProtocolNumber,\n+ routerNIC1Addr: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n+ srcAddrs: []tcpip.Address{\n+ utils.Ipv6Addr1.AddressWithPrefix.Address,\n+ utils.Ipv6Addr2.AddressWithPrefix.Address,\n+ utils.Ipv6Addr2.AddressWithPrefix.Address,\n+ },\n+ transportTypes: []transportTypeTest{\n+ {\n+ name: \"UDP\",\n+ proto: header.UDPProtocolNumber,\n+ buf: func(srcAddr tcpip.Address, srcPort uint16) buffer.View {\n+ return udpv6Packet(srcAddr, utils.Host1IPv6Addr.AddressWithPrefix.Address, srcPort, dstPort, 0 /* dataSize */)\n+ },\n+ checkNATed: func(t *testing.T, v buffer.View, originalSrcPort uint16, firstPacket bool, expectedRange portRange) {\n+ checker.IPv6(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv6Addr.AddressWithPrefix.Address),\n+ checker.UDP(\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+\n+ if !t.Failed() {\n+ compareSrcPort(t, header.UDP(header.IPv6(v).Payload()).SourcePort(), originalSrcPort, firstPacket, expectedRange)\n+ }\n+ },\n+ },\n+ {\n+ name: \"TCP\",\n+ proto: header.TCPProtocolNumber,\n+ buf: func(srcAddr tcpip.Address, srcPort uint16) buffer.View {\n+ return tcpv6Packet(srcAddr, utils.Host1IPv6Addr.AddressWithPrefix.Address, srcPort, dstPort, 0 /* dataSize */)\n+ },\n+ checkNATed: func(t *testing.T, v buffer.View, originalSrcPort uint16, firstPacket bool, expectedRange portRange) {\n+ checker.IPv6(t, v,\n+ checker.SrcAddr(utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address),\n+ checker.DstAddr(utils.Host1IPv6Addr.AddressWithPrefix.Address),\n+ checker.TCP(\n+ checker.DstPort(dstPort),\n+ ),\n+ )\n+\n+ if !t.Failed() {\n+ compareSrcPort(t, header.TCP(header.IPv6(v).Payload()).SourcePort(), originalSrcPort, firstPacket, expectedRange)\n+ }\n+ },\n+ },\n+ },\n+ },\n+ }\n+\n+ natTypes := []struct {\n+ name string\n+ target func(tcpip.NetworkProtocolNumber, tcpip.Address) stack.Target\n+ }{\n+ {\n+ name: \"Masquerade\",\n+ target: func(netProto tcpip.NetworkProtocolNumber, _ tcpip.Address) stack.Target {\n+ return &stack.MasqueradeTarget{NetworkProtocol: netProto}\n+ },\n+ },\n+ {\n+ name: \"SNAT\",\n+ target: func(netProto tcpip.NetworkProtocolNumber, addr tcpip.Address) stack.Target {\n+ return &stack.SNATTarget{NetworkProtocol: netProto, Addr: addr}\n+ },\n+ },\n+ }\n+\n+ srcPortRanges := []struct {\n+ name string\n+ originalRange portRange\n+ targetRange portRange\n+ }{\n+ {\n+ name: \"Less than 512\",\n+ originalRange: portRange{first: 1, last: 511},\n+ targetRange: portRange{first: 1, last: 511},\n+ },\n+ {\n+ name: \"Greater than or equal to 512 but less than 1024\",\n+ originalRange: portRange{first: 512, last: 1023},\n+ targetRange: portRange{first: 1, last: 1023},\n+ },\n+ {\n+ name: \"Greater than or equal to 1024\",\n+ originalRange: portRange{first: 1024, last: math.MaxUint16},\n+ targetRange: portRange{first: 1024, last: math.MaxUint16},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ for _, transportType := range test.transportTypes {\n+ t.Run(transportType.name, func(t *testing.T) {\n+ for _, natType := range natTypes {\n+ t.Run(natType.name, func(t *testing.T) {\n+ for _, srcPortRange := range srcPortRanges {\n+ t.Run(srcPortRange.name, func(t *testing.T) {\n+ for _, srcPort := range [2]uint16{srcPortRange.originalRange.first, srcPortRange.originalRange.last} {\n+ t.Run(fmt.Sprintf(\"OriginalSrcPort=%d\", srcPort), func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, tcp.NewProtocol},\n+ })\n+\n+ ep1 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ ep2 := channel.New(1, header.IPv6MinimumMTU, \"\")\n+ utils.SetupRouterStack(t, s, ep1, ep2)\n+\n+ ipv6 := test.netProto == ipv6.ProtocolNumber\n+ ipt := s.IPTables()\n+\n+ table := stack.Table{\n+ Rules: []stack.Rule{\n+ // Prerouting\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Input\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Forward\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Output\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+\n+ // Postrouting\n+ {\n+ Filter: stack.IPHeaderFilter{\n+ Protocol: transportType.proto,\n+ CheckProtocol: true,\n+ OutputInterface: utils.RouterNIC1Name,\n+ },\n+ Target: natType.target(test.netProto, test.routerNIC1Addr),\n+ },\n+ {\n+ Target: &stack.AcceptTarget{},\n+ },\n+ },\n+ BuiltinChains: [stack.NumHooks]int{\n+ stack.Prerouting: 0,\n+ stack.Input: 1,\n+ stack.Forward: 2,\n+ stack.Output: 3,\n+ stack.Postrouting: 4,\n+ },\n+ }\n+\n+ if err := ipt.ReplaceTable(stack.NATID, table, ipv6); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n+ }\n+\n+ for i, srcAddr := range test.srcAddrs {\n+ t.Run(fmt.Sprintf(\"Packet#%d\", i), func(t *testing.T) {\n+ ep2.InjectInbound(test.netProto, stack.NewPacketBuffer(stack.PacketBufferOptions{\n+ Data: transportType.buf(srcAddr, srcPort).ToVectorisedView(),\n+ }))\n+\n+ pkt, ok := ep1.Read()\n+ if !ok {\n+ t.Fatal(\"expected to read a packet on ep1\")\n+ }\n+ pktView := stack.PayloadSince(pkt.Pkt.NetworkHeader())\n+ transportType.checkNATed(t, pktView, srcPort, i == 0, srcPortRange.targetRange)\n+ })\n+ }\n+ })\n+ }\n+ })\n+ }\n+ })\n+ }\n+ })\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle source port conflicts
This change also updates the ConnTrack seed to be generated by the
stack's random generator instead of using the stack's seed.
Fixes #5773.
PiperOrigin-RevId: 409264463 |
259,909 | 12.11.2021 12:18:18 | 28,800 | ed3ac3a84d5779cf31cb5f29e9033d951f3c7030 | Move `defer pkt.DecRef()` to outside of the dispatch loop.
This avoids unnecessary allocations. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"new_path": "pkg/tcpip/link/fdbased/packet_dispatchers.go",
"diff": "@@ -284,13 +284,16 @@ func (d *recvMMsgDispatcher) dispatch() (bool, tcpip.Error) {\nreturn false, err\n}\n// Process each of received packets.\n+ // Keep a list of packets so we can DecRef outside of the loop.\n+ var pkts stack.PacketBufferList\n+\n+ defer func() { pkts.DecRef() }()\nfor k := 0; k < nMsgs; k++ {\nn := int(d.msgHdrs[k].Len)\n-\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: d.bufs[k].pullViews(n),\n})\n- defer pkt.DecRef()\n+ pkts.PushBack(pkt)\n// Mark that this iovec has been processed.\nd.msgHdrs[k].Msg.Iovlen = 0\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move `defer pkt.DecRef()` to outside of the dispatch loop.
This avoids unnecessary allocations.
PiperOrigin-RevId: 409473262 |
260,004 | 12.11.2021 12:56:49 | 28,800 | 1dbdfd074930afc0c1a4abcd752e18bd606ffef4 | Remove unused member
missed this. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_types.go",
"new_path": "pkg/tcpip/stack/iptables_types.go",
"diff": "@@ -81,11 +81,6 @@ const (\n//\n// +stateify savable\ntype IPTables struct {\n- // priorities maps each hook to a list of table names. The order of the\n- // list is the order in which each table should be visited for that\n- // hook. It is immutable.\n- priorities [NumHooks][]TableID\n-\nconnections ConnTrack\n// reaperDone can be signaled to stop the reaper goroutine.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unused member
https://github.com/google/gvisor/commit/49e80a1440b349b24bddb1ba4fa5469645a84e27
missed this.
PiperOrigin-RevId: 409481435 |
259,891 | 12.11.2021 15:21:47 | 28,800 | 82793c5e9056547c20ddbfa1190a65585a420d1e | netstack: fix Mac build error
Stub out sighandling functions with panics on Darwin
Put Linux-specific errors into their own syserr file
Not sure how best to get automated tests running, so I'll leave that for a later
change.
Fixes
Related to | [
{
"change_type": "MODIFY",
"old_path": "pkg/sighandling/BUILD",
"new_path": "pkg/sighandling/BUILD",
"diff": "@@ -6,7 +6,8 @@ go_library(\nname = \"sighandling\",\nsrcs = [\n\"sighandling.go\",\n- \"sighandling_unsafe.go\",\n+ \"sighandling_darwin.go\",\n+ \"sighandling_linux_unsafe.go\",\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sighandling/sighandling_darwin.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+//go:build darwin\n+// +build darwin\n+\n+package sighandling\n+\n+import (\n+ \"errors\"\n+\n+ \"golang.org/x/sys/unix\"\n+)\n+\n+// IgnoreChildStop sets the SA_NOCLDSTOP flag, causing child processes to not\n+// generate SIGCHLD when they stop.\n+func IgnoreChildStop() error {\n+ return errors.New(\"IgnoreChildStop not supported on Darwin\")\n+}\n+\n+// ReplaceSignalHandler replaces the existing signal handler for the provided\n+// signal with the function pointer at `handler`. This bypasses the Go runtime\n+// signal handlers, and should only be used for low-level signal handlers where\n+// use of signal.Notify is not appropriate.\n+//\n+// It stores the value of the previously set handler in previous.\n+func ReplaceSignalHandler(sig unix.Signal, handler uintptr, previous *uintptr) error {\n+ return errors.New(\"ReplaceSignalHandler not supported on Darwin\")\n+}\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sighandling/sighandling_unsafe.go",
"new_path": "pkg/sighandling/sighandling_linux_unsafe.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+//go:build linux\n+// +build linux\n+\npackage sighandling\nimport (\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/BUILD",
"new_path": "pkg/syserr/BUILD",
"diff": "@@ -5,6 +5,7 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"syserr\",\nsrcs = [\n+ \"host_darwin.go\",\n\"host_linux.go\",\n\"syserr.go\",\n],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/syserr/host_darwin.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+//go:build darwin\n+// +build darwin\n+\n+package syserr\n+\n+import (\n+ \"fmt\"\n+\n+ \"golang.org/x/sys/unix\"\n+)\n+\n+const maxErrno = 107\n+\n+type darwinHostTranslation struct {\n+ err *Error\n+ ok bool\n+}\n+\n+var darwinHostTranslations [maxErrno]darwinHostTranslation\n+\n+// FromHost translates a unix.Errno to a corresponding Error value.\n+func FromHost(err unix.Errno) *Error {\n+ if int(err) >= len(darwinHostTranslations) || !darwinHostTranslations[err].ok {\n+ panic(fmt.Sprintf(\"unknown host errno %q (%d)\", err.Error(), err))\n+ }\n+ return darwinHostTranslations[err].err\n+}\n+\n+// TODO(gvisor.dev/issue/1270): We currently only add translations for errors\n+// that exist both on Darwin and Linux.\n+func addHostTranslation(host unix.Errno, trans *Error) {\n+ if darwinHostTranslations[host].ok {\n+ panic(fmt.Sprintf(\"duplicate translation for host errno %q (%d)\", host.Error(), host))\n+ }\n+ darwinHostTranslations[host] = darwinHostTranslation{err: trans, ok: true}\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/host_linux.go",
"new_path": "pkg/syserr/host_linux.go",
"diff": "@@ -21,6 +21,7 @@ import (\n\"fmt\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux/errno\"\n)\nconst maxErrno = 134\n@@ -40,9 +41,57 @@ func FromHost(err unix.Errno) *Error {\nreturn linuxHostTranslations[err].err\n}\n-func addLinuxHostTranslation(host unix.Errno, trans *Error) {\n+func addHostTranslation(host unix.Errno, trans *Error) {\nif linuxHostTranslations[host].ok {\npanic(fmt.Sprintf(\"duplicate translation for host errno %q (%d)\", host.Error(), host))\n}\nlinuxHostTranslations[host] = linuxHostTranslation{err: trans, ok: true}\n}\n+\n+// TODO(b/34162363): Remove or replace most of these errors.\n+//\n+// Some of the errors should be replaced with package specific errors and\n+// others should be removed entirely.\n+var (\n+ ErrDeadlock = newWithHost(\"resource deadlock would occur\", errno.EDEADLOCK, unix.EDEADLOCK)\n+ ErrChannelOutOfRange = newWithHost(\"channel number out of range\", errno.ECHRNG, unix.ECHRNG)\n+ ErrLevelTwoNotSynced = newWithHost(\"level 2 not synchronized\", errno.EL2NSYNC, unix.EL2NSYNC)\n+ ErrLevelThreeHalted = newWithHost(\"level 3 halted\", errno.EL3HLT, unix.EL3HLT)\n+ ErrLevelThreeReset = newWithHost(\"level 3 reset\", errno.EL3RST, unix.EL3RST)\n+ ErrLinkNumberOutOfRange = newWithHost(\"link number out of range\", errno.ELNRNG, unix.ELNRNG)\n+ ErrProtocolDriverNotAttached = newWithHost(\"protocol driver not attached\", errno.EUNATCH, unix.EUNATCH)\n+ ErrNoCSIAvailable = newWithHost(\"no CSI structure available\", errno.ENOCSI, unix.ENOCSI)\n+ ErrLevelTwoHalted = newWithHost(\"level 2 halted\", errno.EL2HLT, unix.EL2HLT)\n+ ErrInvalidExchange = newWithHost(\"invalid exchange\", errno.EBADE, unix.EBADE)\n+ ErrInvalidRequestDescriptor = newWithHost(\"invalid request descriptor\", errno.EBADR, unix.EBADR)\n+ ErrExchangeFull = newWithHost(\"exchange full\", errno.EXFULL, unix.EXFULL)\n+ ErrNoAnode = newWithHost(\"no anode\", errno.ENOANO, unix.ENOANO)\n+ ErrInvalidRequestCode = newWithHost(\"invalid request code\", errno.EBADRQC, unix.EBADRQC)\n+ ErrInvalidSlot = newWithHost(\"invalid slot\", errno.EBADSLT, unix.EBADSLT)\n+ ErrBadFontFile = newWithHost(\"bad font file format\", errno.EBFONT, unix.EBFONT)\n+ ErrMachineNotOnNetwork = newWithHost(\"machine is not on the network\", errno.ENONET, unix.ENONET)\n+ ErrPackageNotInstalled = newWithHost(\"package not installed\", errno.ENOPKG, unix.ENOPKG)\n+ ErrAdvertise = newWithHost(\"advertise error\", errno.EADV, unix.EADV)\n+ ErrSRMount = newWithHost(\"srmount error\", errno.ESRMNT, unix.ESRMNT)\n+ ErrSendCommunication = newWithHost(\"communication error on send\", errno.ECOMM, unix.ECOMM)\n+ ErrRFS = newWithHost(\"RFS specific error\", errno.EDOTDOT, unix.EDOTDOT)\n+ ErrNetworkNameNotUnique = newWithHost(\"name not unique on network\", errno.ENOTUNIQ, unix.ENOTUNIQ)\n+ ErrFDInBadState = newWithHost(\"file descriptor in bad state\", errno.EBADFD, unix.EBADFD)\n+ ErrRemoteAddressChanged = newWithHost(\"remote address changed\", errno.EREMCHG, unix.EREMCHG)\n+ ErrSharedLibraryInaccessible = newWithHost(\"can not access a needed shared library\", errno.ELIBACC, unix.ELIBACC)\n+ ErrCorruptedSharedLibrary = newWithHost(\"accessing a corrupted shared library\", errno.ELIBBAD, unix.ELIBBAD)\n+ ErrLibSectionCorrupted = newWithHost(\".lib section in a.out corrupted\", errno.ELIBSCN, unix.ELIBSCN)\n+ ErrTooManySharedLibraries = newWithHost(\"attempting to link in too many shared libraries\", errno.ELIBMAX, unix.ELIBMAX)\n+ ErrSharedLibraryExeced = newWithHost(\"cannot exec a shared library directly\", errno.ELIBEXEC, unix.ELIBEXEC)\n+ ErrShouldRestart = newWithHost(\"interrupted system call should be restarted\", errno.ERESTART, unix.ERESTART)\n+ ErrStreamPipe = newWithHost(\"streams pipe error\", errno.ESTRPIPE, unix.ESTRPIPE)\n+ ErrStructureNeedsCleaning = newWithHost(\"structure needs cleaning\", errno.EUCLEAN, unix.EUCLEAN)\n+ ErrIsNamedFile = newWithHost(\"is a named type file\", errno.ENOTNAM, unix.ENOTNAM)\n+ ErrRemoteIO = newWithHost(\"remote I/O error\", errno.EREMOTEIO, unix.EREMOTEIO)\n+ ErrNoMedium = newWithHost(\"no medium found\", errno.ENOMEDIUM, unix.ENOMEDIUM)\n+ ErrWrongMediumType = newWithHost(\"wrong medium type\", errno.EMEDIUMTYPE, unix.EMEDIUMTYPE)\n+ ErrNoKey = newWithHost(\"required key not available\", errno.ENOKEY, unix.ENOKEY)\n+ ErrKeyExpired = newWithHost(\"key has expired\", errno.EKEYEXPIRED, unix.EKEYEXPIRED)\n+ ErrKeyRevoked = newWithHost(\"key has been revoked\", errno.EKEYREVOKED, unix.EKEYREVOKED)\n+ ErrKeyRejected = newWithHost(\"key was rejected by service\", errno.EKEYREJECTED, unix.EKEYREJECTED)\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/syserr.go",
"new_path": "pkg/syserr/syserr.go",
"diff": "@@ -76,7 +76,7 @@ func NewDynamic(message string, linuxTranslation errno.Errno) *Error {\nfunc newWithHost(message string, linuxTranslation errno.Errno, hostErrno unix.Errno) *Error {\ne := New(message, linuxTranslation)\n- addLinuxHostTranslation(hostErrno, e)\n+ addHostTranslation(hostErrno, e)\nreturn e\n}\n@@ -129,6 +129,8 @@ func (e *Error) ToLinux() errno.Errno {\n//\n// Some of the errors should be replaced with package specific errors and\n// others should be removed entirely.\n+//\n+// Note that some errors are declared in platform-specific files.\nvar (\nErrNotPermitted = newWithHost(\"operation not permitted\", errno.EPERM, unix.EPERM)\nErrNoFileOrDir = newWithHost(\"no such file or directory\", errno.ENOENT, unix.ENOENT)\n@@ -164,7 +166,6 @@ var (\nErrBrokenPipe = newWithHost(\"broken pipe\", errno.EPIPE, unix.EPIPE)\nErrDomain = newWithHost(\"math argument out of domain of func\", errno.EDOM, unix.EDOM)\nErrRange = newWithHost(\"math result not representable\", errno.ERANGE, unix.ERANGE)\n- ErrDeadlock = newWithHost(\"resource deadlock would occur\", errno.EDEADLOCK, unix.EDEADLOCK)\nErrNameTooLong = newWithHost(\"file name too long\", errno.ENAMETOOLONG, unix.ENAMETOOLONG)\nErrNoLocksAvailable = newWithHost(\"no record locks available\", errno.ENOLCK, unix.ENOLCK)\nErrInvalidSyscall = newWithHost(\"invalid system call number\", errno.ENOSYS, unix.ENOSYS)\n@@ -172,48 +173,17 @@ var (\nErrLinkLoop = newWithHost(\"too many symbolic links encountered\", errno.ELOOP, unix.ELOOP)\nErrNoMessage = newWithHost(\"no message of desired type\", errno.ENOMSG, unix.ENOMSG)\nErrIdentifierRemoved = newWithHost(\"identifier removed\", errno.EIDRM, unix.EIDRM)\n- ErrChannelOutOfRange = newWithHost(\"channel number out of range\", errno.ECHRNG, unix.ECHRNG)\n- ErrLevelTwoNotSynced = newWithHost(\"level 2 not synchronized\", errno.EL2NSYNC, unix.EL2NSYNC)\n- ErrLevelThreeHalted = newWithHost(\"level 3 halted\", errno.EL3HLT, unix.EL3HLT)\n- ErrLevelThreeReset = newWithHost(\"level 3 reset\", errno.EL3RST, unix.EL3RST)\n- ErrLinkNumberOutOfRange = newWithHost(\"link number out of range\", errno.ELNRNG, unix.ELNRNG)\n- ErrProtocolDriverNotAttached = newWithHost(\"protocol driver not attached\", errno.EUNATCH, unix.EUNATCH)\n- ErrNoCSIAvailable = newWithHost(\"no CSI structure available\", errno.ENOCSI, unix.ENOCSI)\n- ErrLevelTwoHalted = newWithHost(\"level 2 halted\", errno.EL2HLT, unix.EL2HLT)\n- ErrInvalidExchange = newWithHost(\"invalid exchange\", errno.EBADE, unix.EBADE)\n- ErrInvalidRequestDescriptor = newWithHost(\"invalid request descriptor\", errno.EBADR, unix.EBADR)\n- ErrExchangeFull = newWithHost(\"exchange full\", errno.EXFULL, unix.EXFULL)\n- ErrNoAnode = newWithHost(\"no anode\", errno.ENOANO, unix.ENOANO)\n- ErrInvalidRequestCode = newWithHost(\"invalid request code\", errno.EBADRQC, unix.EBADRQC)\n- ErrInvalidSlot = newWithHost(\"invalid slot\", errno.EBADSLT, unix.EBADSLT)\n- ErrBadFontFile = newWithHost(\"bad font file format\", errno.EBFONT, unix.EBFONT)\nErrNotStream = newWithHost(\"device not a stream\", errno.ENOSTR, unix.ENOSTR)\nErrNoDataAvailable = newWithHost(\"no data available\", errno.ENODATA, unix.ENODATA)\nErrTimerExpired = newWithHost(\"timer expired\", errno.ETIME, unix.ETIME)\nErrStreamsResourceDepleted = newWithHost(\"out of streams resources\", errno.ENOSR, unix.ENOSR)\n- ErrMachineNotOnNetwork = newWithHost(\"machine is not on the network\", errno.ENONET, unix.ENONET)\n- ErrPackageNotInstalled = newWithHost(\"package not installed\", errno.ENOPKG, unix.ENOPKG)\nErrIsRemote = newWithHost(\"object is remote\", errno.EREMOTE, unix.EREMOTE)\nErrNoLink = newWithHost(\"link has been severed\", errno.ENOLINK, unix.ENOLINK)\n- ErrAdvertise = newWithHost(\"advertise error\", errno.EADV, unix.EADV)\n- ErrSRMount = newWithHost(\"srmount error\", errno.ESRMNT, unix.ESRMNT)\n- ErrSendCommunication = newWithHost(\"communication error on send\", errno.ECOMM, unix.ECOMM)\nErrProtocol = newWithHost(\"protocol error\", errno.EPROTO, unix.EPROTO)\nErrMultihopAttempted = newWithHost(\"multihop attempted\", errno.EMULTIHOP, unix.EMULTIHOP)\n- ErrRFS = newWithHost(\"RFS specific error\", errno.EDOTDOT, unix.EDOTDOT)\nErrInvalidDataMessage = newWithHost(\"not a data message\", errno.EBADMSG, unix.EBADMSG)\nErrOverflow = newWithHost(\"value too large for defined data type\", errno.EOVERFLOW, unix.EOVERFLOW)\n- ErrNetworkNameNotUnique = newWithHost(\"name not unique on network\", errno.ENOTUNIQ, unix.ENOTUNIQ)\n- ErrFDInBadState = newWithHost(\"file descriptor in bad state\", errno.EBADFD, unix.EBADFD)\n- ErrRemoteAddressChanged = newWithHost(\"remote address changed\", errno.EREMCHG, unix.EREMCHG)\n- ErrSharedLibraryInaccessible = newWithHost(\"can not access a needed shared library\", errno.ELIBACC, unix.ELIBACC)\n- ErrCorruptedSharedLibrary = newWithHost(\"accessing a corrupted shared library\", errno.ELIBBAD, unix.ELIBBAD)\n- ErrLibSectionCorrupted = newWithHost(\".lib section in a.out corrupted\", errno.ELIBSCN, unix.ELIBSCN)\n- ErrTooManySharedLibraries = newWithHost(\"attempting to link in too many shared libraries\", errno.ELIBMAX, unix.ELIBMAX)\n- ErrSharedLibraryExeced = newWithHost(\"cannot exec a shared library directly\", errno.ELIBEXEC, unix.ELIBEXEC)\nErrIllegalByteSequence = newWithHost(\"illegal byte sequence\", errno.EILSEQ, unix.EILSEQ)\n- ErrShouldRestart = newWithHost(\"interrupted system call should be restarted\", errno.ERESTART, unix.ERESTART)\n- ErrStreamPipe = newWithHost(\"streams pipe error\", errno.ESTRPIPE, unix.ESTRPIPE)\nErrTooManyUsers = newWithHost(\"too many users\", errno.EUSERS, unix.EUSERS)\nErrNotASocket = newWithHost(\"socket operation on non-socket\", errno.ENOTSOCK, unix.ENOTSOCK)\nErrDestinationAddressRequired = newWithHost(\"destination address required\", errno.EDESTADDRREQ, unix.EDESTADDRREQ)\n@@ -244,17 +214,8 @@ var (\nErrAlreadyInProgress = newWithHost(\"operation already in progress\", errno.EALREADY, unix.EALREADY)\nErrInProgress = newWithHost(\"operation now in progress\", errno.EINPROGRESS, unix.EINPROGRESS)\nErrStaleFileHandle = newWithHost(\"stale file handle\", errno.ESTALE, unix.ESTALE)\n- ErrStructureNeedsCleaning = newWithHost(\"structure needs cleaning\", errno.EUCLEAN, unix.EUCLEAN)\n- ErrIsNamedFile = newWithHost(\"is a named type file\", errno.ENOTNAM, unix.ENOTNAM)\n- ErrRemoteIO = newWithHost(\"remote I/O error\", errno.EREMOTEIO, unix.EREMOTEIO)\nErrQuotaExceeded = newWithHost(\"quota exceeded\", errno.EDQUOT, unix.EDQUOT)\n- ErrNoMedium = newWithHost(\"no medium found\", errno.ENOMEDIUM, unix.ENOMEDIUM)\n- ErrWrongMediumType = newWithHost(\"wrong medium type\", errno.EMEDIUMTYPE, unix.EMEDIUMTYPE)\nErrCanceled = newWithHost(\"operation canceled\", errno.ECANCELED, unix.ECANCELED)\n- ErrNoKey = newWithHost(\"required key not available\", errno.ENOKEY, unix.ENOKEY)\n- ErrKeyExpired = newWithHost(\"key has expired\", errno.EKEYEXPIRED, unix.EKEYEXPIRED)\n- ErrKeyRevoked = newWithHost(\"key has been revoked\", errno.EKEYREVOKED, unix.EKEYREVOKED)\n- ErrKeyRejected = newWithHost(\"key was rejected by service\", errno.EKEYREJECTED, unix.EKEYREJECTED)\nErrOwnerDied = newWithHost(\"owner died\", errno.EOWNERDEAD, unix.EOWNERDEAD)\nErrNotRecoverable = newWithHost(\"state not recoverable\", errno.ENOTRECOVERABLE, unix.ENOTRECOVERABLE)\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: fix Mac build error
- Stub out sighandling functions with panics on Darwin
- Put Linux-specific errors into their own syserr file
Not sure how best to get automated tests running, so I'll leave that for a later
change.
Fixes #6839.
Related to #1270.
PiperOrigin-RevId: 409516969 |
259,891 | 12.11.2021 16:21:52 | 28,800 | b490036d831ded4169784a0b8130cd033d1969ac | netstack: remove {linux,darwin}HostTranslation
It can be replaced with a simpler type. | [
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/host_darwin.go",
"new_path": "pkg/syserr/host_darwin.go",
"diff": "@@ -25,26 +25,21 @@ import (\nconst maxErrno = 107\n-type darwinHostTranslation struct {\n- err *Error\n- ok bool\n-}\n-\n-var darwinHostTranslations [maxErrno]darwinHostTranslation\n+var darwinHostTranslations [maxErrno]*Error\n// FromHost translates a unix.Errno to a corresponding Error value.\nfunc FromHost(err unix.Errno) *Error {\n- if int(err) >= len(darwinHostTranslations) || !darwinHostTranslations[err].ok {\n+ if int(err) >= len(darwinHostTranslations) || darwinHostTranslations[err] == nil {\npanic(fmt.Sprintf(\"unknown host errno %q (%d)\", err.Error(), err))\n}\n- return darwinHostTranslations[err].err\n+ return darwinHostTranslations[err]\n}\n// TODO(gvisor.dev/issue/1270): We currently only add translations for errors\n// that exist both on Darwin and Linux.\nfunc addHostTranslation(host unix.Errno, trans *Error) {\n- if darwinHostTranslations[host].ok {\n+ if darwinHostTranslations[host] != nil {\npanic(fmt.Sprintf(\"duplicate translation for host errno %q (%d)\", host.Error(), host))\n}\n- darwinHostTranslations[host] = darwinHostTranslation{err: trans, ok: true}\n+ darwinHostTranslations[host] = trans\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/host_linux.go",
"new_path": "pkg/syserr/host_linux.go",
"diff": "@@ -26,26 +26,21 @@ import (\nconst maxErrno = 134\n-type linuxHostTranslation struct {\n- err *Error\n- ok bool\n-}\n-\n-var linuxHostTranslations [maxErrno]linuxHostTranslation\n+var linuxHostTranslations [maxErrno]*Error\n// FromHost translates a unix.Errno to a corresponding Error value.\nfunc FromHost(err unix.Errno) *Error {\n- if int(err) >= len(linuxHostTranslations) || !linuxHostTranslations[err].ok {\n+ if int(err) >= len(linuxHostTranslations) || linuxHostTranslations[err] == nil {\npanic(fmt.Sprintf(\"unknown host errno %q (%d)\", err.Error(), err))\n}\n- return linuxHostTranslations[err].err\n+ return linuxHostTranslations[err]\n}\nfunc addHostTranslation(host unix.Errno, trans *Error) {\n- if linuxHostTranslations[host].ok {\n+ if linuxHostTranslations[host] != nil {\npanic(fmt.Sprintf(\"duplicate translation for host errno %q (%d)\", host.Error(), host))\n}\n- linuxHostTranslations[host] = linuxHostTranslation{err: trans, ok: true}\n+ linuxHostTranslations[host] = trans\n}\n// TODO(b/34162363): Remove or replace most of these errors.\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: remove {linux,darwin}HostTranslation
It can be replaced with a simpler type.
PiperOrigin-RevId: 409533054 |
259,853 | 12.11.2021 17:30:18 | 28,800 | ea031446515989a9d8b564b326eb26e68a755460 | Use vDSO clock_gettime
The vDSO calls are much faster.
For exeample, here are results of read_benchmark_test_tmpfs_kvm before and
after this change:
Before:
BM_Read/65536/real_time 7309 ns 7260 ns 82640 bytes_per_second=8.35016G/s
After:
BM_Read/65536/real_time 2065 ns 2080 ns 346151 bytes_per_second=29.558G/s | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/time/BUILD",
"new_path": "pkg/sentry/time/BUILD",
"diff": "@@ -27,10 +27,12 @@ go_library(\n\"sampler.go\",\n\"sampler_amd64.go\",\n\"sampler_arm64.go\",\n- \"sampler_unsafe.go\",\n\"seqatomic_parameters_unsafe.go\",\n\"tsc_amd64.s\",\n\"tsc_arm64.s\",\n+ \"vdso.go\",\n+ \"vdso_amd64.s\",\n+ \"vdso_arm64.s\",\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n@@ -49,6 +51,11 @@ go_test(\n\"calibrated_clock_test.go\",\n\"parameters_test.go\",\n\"sampler_test.go\",\n+ \"vdso_test.go\",\n],\nlibrary = \":time\",\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/time/sampler.go",
"new_path": "pkg/sentry/time/sampler.go",
"diff": "@@ -17,6 +17,7 @@ package time\nimport (\n\"errors\"\n+ \"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/log\"\n)\n@@ -216,3 +217,35 @@ func (s *sampler) Range() (sample, sample, bool) {\nreturn s.samples[0], s.samples[len(s.samples)-1], true\n}\n+\n+// syscallTSCReferenceClocks is the standard referenceClocks, collecting\n+// samples using CLOCK_GETTIME and RDTSC.\n+type syscallTSCReferenceClocks struct {\n+ tscCycleClock\n+}\n+\n+// Sample implements sampler.Sample.\n+func (syscallTSCReferenceClocks) Sample(c ClockID) (sample, error) {\n+ var s sample\n+\n+ s.before = Rdtsc()\n+\n+ // Don't call clockGettime to avoid a call which may call morestack.\n+ var ts unix.Timespec\n+\n+ vdsoClockGettime(c, &ts)\n+\n+ s.after = Rdtsc()\n+ s.ref = ReferenceNS(ts.Nano())\n+\n+ return s, nil\n+}\n+\n+// clockGettime calls SYS_CLOCK_GETTIME, returning time in nanoseconds.\n+func clockGettime(c ClockID) (ReferenceNS, error) {\n+ var ts unix.Timespec\n+\n+ vdsoClockGettime(c, &ts)\n+\n+ return ReferenceNS(ts.Nano()), nil\n+}\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/time/sampler_unsafe.go",
"new_path": null,
"diff": "-// Copyright 2018 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 time\n-\n-import (\n- \"unsafe\"\n-\n- \"golang.org/x/sys/unix\"\n-)\n-\n-// syscallTSCReferenceClocks is the standard referenceClocks, collecting\n-// samples using CLOCK_GETTIME and RDTSC.\n-type syscallTSCReferenceClocks struct {\n- tscCycleClock\n-}\n-\n-// Sample implements sampler.Sample.\n-func (syscallTSCReferenceClocks) Sample(c ClockID) (sample, error) {\n- var s sample\n-\n- s.before = Rdtsc()\n-\n- // Don't call clockGettime to avoid a call which may call morestack.\n- var ts unix.Timespec\n- _, _, e := unix.RawSyscall(unix.SYS_CLOCK_GETTIME, uintptr(c), uintptr(unsafe.Pointer(&ts)), 0)\n- if e != 0 {\n- return sample{}, e\n- }\n-\n- s.after = Rdtsc()\n- s.ref = ReferenceNS(ts.Nano())\n-\n- return s, nil\n-}\n-\n-// clockGettime calls SYS_CLOCK_GETTIME, returning time in nanoseconds.\n-func clockGettime(c ClockID) (ReferenceNS, error) {\n- var ts unix.Timespec\n- _, _, e := unix.RawSyscall(unix.SYS_CLOCK_GETTIME, uintptr(c), uintptr(unsafe.Pointer(&ts)), 0)\n- if e != 0 {\n- return 0, e\n- }\n-\n- return ReferenceNS(ts.Nano()), nil\n-}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/time/vdso.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 time\n+\n+import (\n+ \"golang.org/x/sys/unix\"\n+)\n+\n+func vdsoClockGettime(clockid ClockID, ts *unix.Timespec) int\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/time/vdso_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 time\n+\n+import (\n+ \"syscall\"\n+ \"testing\"\n+ \"unsafe\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+)\n+\n+func TestClockGetTime(t *testing.T) {\n+ ts := unix.Timespec{}\n+ if ret := vdsoClockGettime(linux.CLOCK_MONOTONIC, &ts); ret != 0 {\n+ t.Fatalf(\"Unexpected error code: %v\", ret)\n+ }\n+ sts := unix.Timespec{}\n+ if _, _, errno := unix.RawSyscall(unix.SYS_CLOCK_GETTIME,\n+ uintptr(linux.CLOCK_MONOTONIC),\n+ uintptr(unsafe.Pointer(&sts)), 0); errno != 0 {\n+ t.Fatalf(\"Unexpected error code: %v\", errno)\n+ }\n+ // Check that ts.Sec is in [sts.Sec, sts.Sec + 5].\n+ if sts.Sec < ts.Sec || sts.Sec > ts.Sec+5 {\n+ t.Fatalf(\"Unexpected delta: vdso %+v syscall %+v\", ts, sts)\n+ }\n+}\n+\n+func TestClockGetTimeEINVAL(t *testing.T) {\n+ ts := unix.Timespec{}\n+ if ret := vdsoClockGettime(-1, &ts); ret != -int(syscall.EINVAL) {\n+ t.Fatalf(\"Unexpected error code: %v\", ret)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use vDSO clock_gettime
The vDSO calls are much faster.
For exeample, here are results of read_benchmark_test_tmpfs_kvm before and
after this change:
Before:
BM_Read/65536/real_time 7309 ns 7260 ns 82640 bytes_per_second=8.35016G/s
After:
BM_Read/65536/real_time 2065 ns 2080 ns 346151 bytes_per_second=29.558G/s
PiperOrigin-RevId: 409547486 |
259,985 | 12.11.2021 17:31:23 | 28,800 | 8650614c32c4dc5e8754b7bf4c84278551cff419 | Shift buffer correctly when unmarshalling FUSE dirents. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/fuse.go",
"new_path": "pkg/abi/linux/fuse.go",
"diff": "@@ -782,21 +782,31 @@ func (r *FUSEDirent) SizeBytes() int {\nreturn (dataSize + (FUSE_DIRENT_ALIGN - 1)) & ^(FUSE_DIRENT_ALIGN - 1)\n}\n+// shiftNextDirent advances buf to the start of the next dirent, per\n+// FUSE ABI. buf should begin at the start of a dirent.\n+func (r *FUSEDirent) shiftNextDirent(buf []byte) []byte {\n+ nextOff := r.SizeBytes()\n+ if nextOff > len(buf) { // Handle overflow.\n+ return buf[len(buf):]\n+ }\n+ return buf[nextOff:]\n+}\n+\n// UnmarshalBytes deserializes FUSEDirent from the src buffer.\nfunc (r *FUSEDirent) UnmarshalBytes(src []byte) []byte {\n- src = r.Meta.UnmarshalBytes(src)\n+ srcP := r.Meta.UnmarshalBytes(src)\nif r.Meta.NameLen > FUSE_NAME_MAX {\n// The name is too long and therefore invalid. We don't\n// need to unmarshal the name since it'll be thrown away.\n- return src\n+ return r.shiftNextDirent(src)\n}\nbuf := make([]byte, r.Meta.NameLen)\nname := primitive.ByteSlice(buf)\n- name.UnmarshalBytes(src[:r.Meta.NameLen])\n+ name.UnmarshalBytes(srcP[:r.Meta.NameLen])\nr.Name = string(name)\n- return src[r.Meta.NameLen:]\n+ return r.shiftNextDirent(src)\n}\n// FATTR_* consts are the attribute flags defined in include/uapi/linux/fuse.h.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Shift buffer correctly when unmarshalling FUSE dirents.
PiperOrigin-RevId: 409547679 |
259,907 | 12.11.2021 17:37:13 | 28,800 | 66fb6859d1d0ce6aa7b9ea034a0f1ebab2a91775 | Update CPUID features. | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_x86.go",
"new_path": "pkg/cpuid/cpuid_x86.go",
"diff": "@@ -167,7 +167,7 @@ const (\nX86FeatureOSPKE\nX86FeatureWAITPKG\nX86FeatureAVX512_VBMI2\n- _ // ecx bit 7 is reserved\n+ X86FeatureCET_SS\nX86FeatureGFNI\nX86FeatureVAES\nX86FeatureVPCLMULQDQ\n@@ -236,8 +236,7 @@ const (\nX86FeaturePERFCTR_TSC\nX86FeaturePERFCTR_LLC\nX86FeatureMWAITX\n- // TODO(b/152776797): Some CPUs set this but it is not documented anywhere.\n- X86FeatureBlock5Bit30\n+ X86FeatureADMSKEXTN\n_ // ecx bit 31 is reserved.\n)\n@@ -443,7 +442,7 @@ var x86FeatureParseOnlyStrings = map[Feature]string{\nX86FeaturePREFETCHWT1: \"prefetchwt1\",\n// Block 5.\n- X86FeatureBlock5Bit30: \"block5_bit30\",\n+ X86FeatureADMSKEXTN: \"ad_msk_extn\",\n}\n// intelCacheDescriptors describe the caches and TLBs on the system. They are\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update CPUID features.
PiperOrigin-RevId: 409548753 |
259,909 | 16.11.2021 13:43:31 | 28,800 | 5117717034dae2cbaed9497e0369f8772fd6a542 | Fix PacketBuffer memory leak. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"diff": "@@ -413,13 +413,13 @@ func (e *endpoint) dispatchLoop(d stack.NetworkDispatcher) {\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\nData: buffer.View(b).ToVectorisedView(),\n})\n- defer pkt.DecRef()\nvar src, dst tcpip.LinkAddress\nvar proto tcpip.NetworkProtocolNumber\nif e.addr != \"\" {\nhdr, ok := pkt.LinkHeader().Consume(header.EthernetMinimumSize)\nif !ok {\n+ pkt.DecRef()\ncontinue\n}\neth := header.Ethernet(hdr)\n@@ -432,6 +432,7 @@ func (e *endpoint) dispatchLoop(d stack.NetworkDispatcher) {\n// IP version information is at the first octet, so pulling up 1 byte.\nh, ok := pkt.Data().PullUp(1)\nif !ok {\n+ pkt.DecRef()\ncontinue\n}\nswitch header.IPVersion(h) {\n@@ -440,12 +441,14 @@ func (e *endpoint) dispatchLoop(d stack.NetworkDispatcher) {\ncase header.IPv6Version:\nproto = header.IPv6ProtocolNumber\ndefault:\n+ pkt.DecRef()\ncontinue\n}\n}\n// Send packet up the stack.\nd.DeliverNetworkPacket(src, dst, proto, pkt)\n+ pkt.DecRef()\n}\ne.mu.Lock()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix PacketBuffer memory leak.
PiperOrigin-RevId: 410339192 |
260,004 | 16.11.2021 15:40:39 | 28,800 | 4ab52f3cfdbe2c75c6525aa6732210a6d5d64b11 | Drop connection on reply tuple conflict
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"fmt\"\n\"math/rand\"\n\"sync\"\n+ \"sync/atomic\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -108,6 +109,17 @@ const (\nmanipPerformedNoop\n)\n+type finalizeResult uint32\n+\n+const (\n+ // A finalizeResult must be explicitly set so we don't make use of the zero\n+ // value.\n+ _ finalizeResult = iota\n+\n+ finalizeResultSuccess\n+ finalizeResultConflict\n+)\n+\n// conn is a tracked connection.\n//\n// +stateify savable\n@@ -120,11 +132,13 @@ type conn struct {\n// reply is the tuple in reply direction.\nreply tuple\n- mu sync.RWMutex `state:\"nosave\"`\n- // Indicates that the connection has been finalized and may handle replies.\n+ finalizeOnce sync.Once\n+ // Holds a finalizeResult.\n//\n- // +checklocks:mu\n- finalized bool\n+ // +checkatomics\n+ finalizeResult uint32\n+\n+ mu sync.RWMutex `state:\"nosave\"`\n// sourceManip indicates the source manipulation type.\n//\n// +checklocks:mu\n@@ -505,51 +519,66 @@ func (bkt *bucket) connForTIDRLocked(tid tupleID, now tcpip.MonotonicTime) *tupl\nreturn nil\n}\n-func (ct *ConnTrack) finalize(cn *conn) {\n- tid := cn.reply.id()\n- id := ct.bucket(tid)\n-\n+func (ct *ConnTrack) finalize(cn *conn) finalizeResult {\nct.mu.RLock()\n- bkt := &ct.buckets[id]\n+ buckets := ct.buckets\nct.mu.RUnlock()\n+ {\n+ tid := cn.reply.id()\n+ id := ct.bucket(tid)\n+\n+ bkt := &buckets[id]\nbkt.mu.Lock()\n- defer bkt.mu.Unlock()\n+ if bkt.connForTIDRLocked(tid, ct.clock.NowMonotonic()) == nil {\n+ bkt.tuples.PushFront(&cn.reply)\n+ bkt.mu.Unlock()\n+ return finalizeResultSuccess\n+ }\n+ bkt.mu.Unlock()\n+ }\n- if t := bkt.connForTIDRLocked(tid, ct.clock.NowMonotonic()); t != nil {\n- // Another connection for the reply already exists. We can't do much about\n- // this so we leave the connection cn represents in a state where it can\n- // send packets but its responses will be mapped to some other connection.\n- // This may be okay if the connection only expects to send packets without\n- // any responses.\n+ // Another connection for the reply already exists. Remove the original and\n+ // let the caller know we failed.\n//\n// TODO(https://gvisor.dev/issue/6850): Investigate handling this clash\n// better.\n- return\n- }\n- bkt.tuples.PushFront(&cn.reply)\n+ tid := cn.original.id()\n+ id := ct.bucket(tid)\n+ bkt := &buckets[id]\n+ bkt.mu.Lock()\n+ defer bkt.mu.Unlock()\n+ bkt.tuples.Remove(&cn.original)\n+ return finalizeResultConflict\n}\n-func (cn *conn) finalize() {\n- {\n- cn.mu.RLock()\n- finalized := cn.finalized\n- cn.mu.RUnlock()\n- if finalized {\n- return\n- }\n+func (cn *conn) getFinalizeResult() finalizeResult {\n+ return finalizeResult(atomic.LoadUint32(&cn.finalizeResult))\n}\n- cn.mu.Lock()\n- finalized := cn.finalized\n- cn.finalized = true\n- cn.mu.Unlock()\n- if finalized {\n- return\n+// finalize attempts to finalize the connection and returns true iff the\n+// connection was successfully finalized.\n+//\n+// If the connection failed to finalize, the caller should drop the packet\n+// associated with the connection.\n+//\n+// If multiple goroutines attempt to finalize at the same time, only one\n+// goroutine will perform the work to finalize the connection, but all\n+// goroutines will block until the finalizing goroutine finishes finalizing.\n+func (cn *conn) finalize() bool {\n+ cn.finalizeOnce.Do(func() {\n+ atomic.StoreUint32(&cn.finalizeResult, uint32(cn.ct.finalize(cn)))\n+ })\n+\n+ switch res := cn.getFinalizeResult(); res {\n+ case finalizeResultSuccess:\n+ return true\n+ case finalizeResultConflict:\n+ return false\n+ default:\n+ panic(fmt.Sprintf(\"unhandled result = %d\", res))\n}\n-\n- cn.ct.finalize(cn)\n}\nfunc (cn *conn) maybePerformNoopNAT(dnat bool) {\n@@ -919,9 +948,7 @@ func (ct *ConnTrack) reapTupleLocked(reapingTuple *tuple, bktID int, bkt *bucket\n}\notherTupleBktID := ct.bucket(otherTuple.id())\n- reapingTuple.conn.mu.RLock()\n- replyTupleInserted := reapingTuple.conn.finalized\n- reapingTuple.conn.mu.RUnlock()\n+ replyTupleInserted := reapingTuple.conn.getFinalizeResult() == finalizeResultSuccess\n// To maintain lock order, we can only reap both tuples if the tuple for the\n// other direction appears later in the table.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -312,9 +312,9 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n}\nif t := pkt.tuple; t != nil {\n- t.conn.finalize()\n- }\npkt.tuple = nil\n+ return t.conn.finalize()\n+ }\nreturn true\n}\n@@ -388,9 +388,9 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP Addr\n}\nif t := pkt.tuple; t != nil {\n- t.conn.finalize()\n- }\npkt.tuple = nil\n+ return t.conn.finalize()\n+ }\nreturn true\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_test.go",
"new_path": "pkg/tcpip/stack/iptables_test.go",
"diff": "@@ -18,13 +18,14 @@ import (\n\"math/rand\"\n\"testing\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n)\nconst (\n- nattedDstPort = 1\n+ nattedPort = 1\nsrcPort = 2\ndstPort = 3\n@@ -35,12 +36,12 @@ const (\n)\nvar (\n- nattedDstAddr = testutil.MustParse6(\"a::1\")\n+ nattedAddr = testutil.MustParse6(\"a::1\")\nsrcAddr = testutil.MustParse6(\"b::2\")\ndstAddr = testutil.MustParse6(\"c::3\")\n)\n-func v6PacketBuffer() *PacketBuffer {\n+func v6PacketBufferWithSrcAddr(srcAddr tcpip.Address) *PacketBuffer {\npkt := NewPacketBuffer(PacketBufferOptions{\nReserveHeaderBytes: header.IPv6MinimumSize + header.UDPMinimumSize,\n})\n@@ -67,6 +68,10 @@ func v6PacketBuffer() *PacketBuffer {\nreturn pkt\n}\n+func v6PacketBuffer() *PacketBuffer {\n+ return v6PacketBufferWithSrcAddr(srcAddr)\n+}\n+\n// TestNATedConnectionReap tests that NATed connections are properly reaped.\nfunc TestNATedConnectionReap(t *testing.T) {\nclock := faketime.NewManualClock()\n@@ -76,7 +81,7 @@ func TestNATedConnectionReap(t *testing.T) {\nRules: []Rule{\n// Prerouting\n{\n- Target: &DNATTarget{NetworkProtocol: netProto, Addr: nattedDstAddr, Port: nattedDstPort},\n+ Target: &DNATTarget{NetworkProtocol: netProto, Addr: nattedAddr, Port: nattedPort},\n},\n{\nTarget: &AcceptTarget{},\n@@ -317,3 +322,109 @@ func TestNATAlwaysPerformed(t *testing.T) {\n})\n}\n}\n+\n+func TestNATConflict(t *testing.T) {\n+ otherSrcAddr := testutil.MustParse6(\"d::4\")\n+\n+ tests := []struct {\n+ name string\n+ checkIPTables func(*testing.T, *IPTables, *PacketBuffer, bool)\n+ }{\n+ {\n+ name: \"Prerouting and Input\",\n+ checkIPTables: func(t *testing.T, iptables *IPTables, pkt *PacketBuffer, lastHookOK bool) {\n+ t.Helper()\n+\n+ if !iptables.CheckPrerouting(pkt, nil /* addressEP */, \"\" /* inNicName */) {\n+ t.Fatal(\"got ipt.CheckPrerouting(...) = false, want = true\")\n+ }\n+ if got := iptables.CheckInput(pkt, \"\" /* inNicName */); got != lastHookOK {\n+ t.Fatalf(\"got ipt.CheckInput(...) = %t, want = %t\", got, lastHookOK)\n+ }\n+ },\n+ },\n+ {\n+ name: \"Output and Postrouting\",\n+ checkIPTables: func(t *testing.T, iptables *IPTables, pkt *PacketBuffer, lastHookOK bool) {\n+ t.Helper()\n+\n+ // Output and Postrouting hooks depends on a route but if the route is\n+ // local, we don't need anything else from it.\n+ r := Route{\n+ routeInfo: routeInfo{\n+ Loop: PacketLoop,\n+ },\n+ }\n+ if !iptables.CheckOutput(pkt, &r, \"\" /* outNicName */) {\n+ t.Fatal(\"got iptables.CheckOutput(...) = false, want = true\")\n+ }\n+ if got := iptables.CheckPostrouting(pkt, &r, nil /* addressEP */, \"\" /* outNicName */); got != lastHookOK {\n+ t.Fatalf(\"got iptables.CheckPostrouting(...) = %t, want = %t\", got, lastHookOK)\n+ }\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+\n+ clock := faketime.NewManualClock()\n+ iptables := DefaultTables(clock, rand.New(rand.NewSource(0 /* seed */)))\n+\n+ table := Table{\n+ Rules: []Rule{\n+ // Prerouting\n+ {\n+ Target: &AcceptTarget{},\n+ },\n+\n+ // Input\n+ {\n+ Target: &SNATTarget{NetworkProtocol: header.IPv6ProtocolNumber, Addr: nattedAddr, Port: nattedPort},\n+ },\n+ {\n+ Target: &AcceptTarget{},\n+ },\n+\n+ // Forward\n+ {\n+ Target: &AcceptTarget{},\n+ },\n+\n+ // Output\n+ {\n+ Target: &AcceptTarget{},\n+ },\n+\n+ // Postrouting\n+ {\n+ Target: &SNATTarget{NetworkProtocol: header.IPv6ProtocolNumber, Addr: nattedAddr, Port: nattedPort},\n+ },\n+ {\n+ Target: &AcceptTarget{},\n+ },\n+ },\n+ BuiltinChains: [NumHooks]int{\n+ Prerouting: 0,\n+ Input: 1,\n+ Forward: 3,\n+ Output: 4,\n+ Postrouting: 5,\n+ },\n+ }\n+ if err := iptables.ReplaceTable(NATID, table, ipv6); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, true): %s\", NATID, err)\n+ }\n+\n+ // Create and finalize the connection.\n+ test.checkIPTables(t, iptables, v6PacketBufferWithSrcAddr(srcAddr), true /* lastHookOK */)\n+\n+ // A packet from a different source that get NATed to the same tuple as\n+ // the connection created above should be dropped when finalizing.\n+ test.checkIPTables(t, iptables, v6PacketBufferWithSrcAddr(otherSrcAddr), false /* lastHookOK */)\n+\n+ // A packet from the original source should be NATed as normal.\n+ test.checkIPTables(t, iptables, v6PacketBufferWithSrcAddr(srcAddr), true /* lastHookOK */)\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop connection on reply tuple conflict
Updates #6850.
PiperOrigin-RevId: 410368440 |
259,891 | 18.11.2021 12:16:39 | 28,800 | 91313ede801abfe863f67f340903c01e7a6a7852 | buildkite: build Netstack on several platforms
Addresses
RELNOTES: n/a | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -20,6 +20,21 @@ _templates:\nBENCHMARKS_PROJECT: gvisor-benchmarks\nBENCHMARKS_TABLE: benchmarks\nBENCHMARKS_UPLOAD: true\n+ netstack_test: &netstack_test\n+ env:\n+ PACKAGES: >\n+ ./pkg/tcpip\n+ ./pkg/tcpip/adapters/gonet\n+ ./pkg/tcpip/buffer\n+ ./pkg/tcpip/header\n+ ./pkg/tcpip/link/channel\n+ ./pkg/tcpip/network/ipv4\n+ ./pkg/tcpip/network/ipv6\n+ ./pkg/tcpip/stack\n+ ./pkg/tcpip/transport/icmp\n+ ./pkg/tcpip/transport/tcp\n+ ./pkg/tcpip/transport/udp\n+ ./pkg/waiter\nsteps:\n# Run basic smoke tests before preceding to other tests.\n@@ -36,6 +51,43 @@ steps:\n- git checkout go && git clean -xf .\n- go build ./...\n+ # Check that commonly used netstack packages build on various platforms.\n+ - <<: *common\n+ <<: *netstack_test\n+ label: \":mac: Netstack on Mac\"\n+ commands:\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -xf .\n+ - GOOS=darwin GOARCH=arm64 go build $$PACKAGES\n+ - <<: *common\n+ <<: *netstack_test\n+ label: \":windows: Netstack on Windows\"\n+ commands:\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -xf .\n+ - GOOS=windows GOARCH=amd64 go build $$PACKAGES\n+ - <<: *common\n+ <<: *netstack_test\n+ label: \":freebsd: Netstack on FreeBSD\"\n+ commands:\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -xf .\n+ - GOOS=freebsd GOARCH=amd64 go build $$PACKAGES\n+ - <<: *common\n+ <<: *netstack_test\n+ label: \":openbsd: Netstack on OpenBSD\"\n+ commands:\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -xf .\n+ - GOOS=openbsd GOARCH=amd64 go build $$PACKAGES\n+ - <<: *common\n+ <<: *netstack_test\n+ label: \":older_man: Netstack on 32-bit Linux\"\n+ commands:\n+ - tools/go_branch.sh\n+ - git checkout go && git clean -xf .\n+ - GOOS=linux GOARCH=mips go build $$PACKAGES\n+\n# Release workflow.\n- <<: *common\nlabel: \":ship: Release tests\"\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/BUILD",
"new_path": "pkg/tcpip/BUILD",
"diff": "@@ -39,6 +39,12 @@ go_library(\ndeps_test(\nname = \"netstack_deps_test\",\n+ # NOTE: Try not to let allowed or allowed_prefixes to grow large.\n+ #\n+ # Netstack is intentionally somewhat separate from the rest of gVisor; it is\n+ # intended to be usable separately as a library. Therefore we limit its\n+ # dependencies to a small set of packages. If you're adding dependencies,\n+ # consider whether netstack should really depend on them.\nallowed = [\n# gVisor deps.\n\"//pkg/atomicbitops\",\n@@ -69,6 +75,9 @@ deps_test(\n],\ntargets = [\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/adapters/gonet\",\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/fdbased\",\n\"//pkg/tcpip/link/loopback\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | buildkite: build Netstack on several platforms
Addresses #6839.
RELNOTES: n/a
PiperOrigin-RevId: 410869145 |
259,858 | 19.11.2021 16:01:06 | 28,800 | 889190828c60e621be3c6ce4f9d6692b63911203 | Skip header install if not available. | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/hooks/pre-command",
"new_path": ".buildkite/hooks/pre-command",
"diff": "@@ -7,9 +7,13 @@ function install_pkgs() {\nfi\ndone\n}\n-install_pkgs make \"linux-headers-$(uname -r)\" linux-libc-dev \\\n- graphviz jq curl binutils gnupg gnupg-agent gcc pkg-config \\\n- apt-transport-https ca-certificates software-properties-common\n+install_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \\\n+ gcc pkg-config apt-transport-https ca-certificates software-properties-common\n+\n+# Install headers, only if available.\n+if test -n \"$(apt-cache search --names-only \"^linux-headers-$(uname -r)$\")\"; then\n+ install_pkgs \"linux-headers-$(uname -r)\"\n+fi\n# Setup for parallelization with PARTITION and TOTAL_PARTITIONS.\nexport PARTITION=${BUILDKITE_PARALLEL_JOB:-0}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip header install if not available.
PiperOrigin-RevId: 411164318 |
259,891 | 22.11.2021 14:23:18 | 28,800 | 2bedb2dc397a372ea97329e8675c87a9000ad63c | mark platforms as Linux-only
Related to | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/platforms/BUILD",
"new_path": "runsc/boot/platforms/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"select_system\")\npackage(licenses = [\"notice\"])\n+# Don't rewrite the deps attribute of :platforms.\n+# @unused\n+glaze_ignore = [\n+ \"platforms.go\",\n+ \"platforms_darwin.go\",\n+]\n+\ngo_library(\nname = \"platforms\",\n- srcs = [\"platforms.go\"],\n+ srcs = [\n+ \"platforms.go\",\n+ \"platforms_darwin.go\",\n+ ],\n+ # Nothing needs to be stateified, and stateify has trouble when select is\n+ # used to choose deps.\n+ stateify = False,\nvisibility = [\n\"//runsc:__subpackages__\",\n],\n- deps = [\n+ deps = select_system(\n+ darwin = [],\n+ linux = [\n\"//pkg/sentry/platform/kvm\",\n\"//pkg/sentry/platform/ptrace\",\n+ \"//runsc/boot/platforms/nonstandard\",\n],\n+ ),\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/platforms/nonstandard/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"nonstandard\",\n+ srcs = [\"nonstandard.go\"],\n+ visibility = [\n+ \"//runsc:__subpackages__\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/platforms/nonstandard/nonstandard.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 nonstandard provides a place for nonstandard platforms.\n+package nonstandard\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/platforms/platforms.go",
"new_path": "runsc/boot/platforms/platforms.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+//go:build linux\n+// +build linux\n+\n// Package platforms imports all available platform packages.\npackage platforms\n@@ -19,6 +22,7 @@ import (\n// Import platforms that runsc might use.\n_ \"gvisor.dev/gvisor/pkg/sentry/platform/kvm\"\n_ \"gvisor.dev/gvisor/pkg/sentry/platform/ptrace\"\n+ _ \"gvisor.dev/gvisor/runsc/boot/platforms/nonstandard\"\n)\nconst (\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/boot/platforms/platforms_darwin.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+//go:build darwin\n+// +build darwin\n+\n+package platforms\n+\n+// This file makes the platforms package buildable on Darwin.\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/defs.bzl",
"new_path": "tools/bazeldefs/defs.bzl",
"diff": "@@ -27,8 +27,11 @@ def select_arch(amd64 = \"amd64\", arm64 = \"arm64\", default = None, **kwargs):\nvalues[\"//conditions:default\"] = default\nreturn select(values, **kwargs)\n-def select_system(linux = [\"__linux__\"], **kwargs):\n- return linux # Only Linux supported.\n+def select_system(linux = [\"__linux__\"], darwin = [], **kwargs):\n+ return select({\n+ \"@bazel_tools//src/conditions:darwin\": darwin,\n+ \"//conditions:default\": linux,\n+ })\ndef default_installer():\nreturn None\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/go.bzl",
"new_path": "tools/bazeldefs/go.bzl",
"diff": "@@ -156,4 +156,7 @@ def select_goarch():\nreturn select_arch(amd64 = \"amd64\", arm64 = \"arm64\")\ndef select_goos():\n- return select_system(linux = \"linux\")\n+ return select_system(\n+ linux = \"linux\",\n+ darwin = \"darwin\",\n+ )\n"
}
] | Go | Apache License 2.0 | google/gvisor | mark platforms as Linux-only
Related to #1270.
PiperOrigin-RevId: 411648212 |
259,909 | 23.11.2021 14:27:23 | 28,800 | 2758e1123074002d7cda139e92af28b96100b8cd | Modify udpPacket to hold a PacketBuffer reference instead of a VectorizedView. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -15,6 +15,7 @@ package stack\nimport (\n\"fmt\"\n+ \"io\"\n\"gvisor.dev/gvisor/pkg/buffer\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -91,6 +92,8 @@ type PacketBufferOptions struct {\n// `consumed` value is stored for each header, and it gets incremented by the\n// consumed length. PacketBuffer adds this value to `reserved` to compute the\n// starting offset of each header in `buf`.\n+//\n+// +stateify savable\ntype PacketBuffer struct {\n_ sync.NoCopy\n@@ -432,6 +435,8 @@ func (pk *PacketBufferList) DecRef() {\n}\n// headerInfo stores metadata about a header in a packet.\n+//\n+// +stateify savable\ntype headerInfo struct {\n// offset is the offset of the header in pk.buf relative to\n// pk.buf[pk.reserved]. See the PacketBuffer struct for details.\n@@ -469,6 +474,8 @@ func (h PacketHeader) Consume(size int) (v tcpipbuffer.View, consumed bool) {\n}\n// PacketData represents the data portion of a PacketBuffer.\n+//\n+// +stateify savable\ntype PacketData struct {\npk *PacketBuffer\n}\n@@ -489,6 +496,28 @@ func (d PacketData) Consume(size int) (tcpipbuffer.View, bool) {\nreturn v, ok\n}\n+// ReadTo reads bytes from d to dst. It also removes these bytes from d\n+// unless peek is true.\n+func (d PacketData) ReadTo(dst io.Writer, peek bool) (int, error) {\n+ var err error\n+ done := 0\n+ for _, v := range d.Views() {\n+ var n int\n+ n, err = dst.Write(v)\n+ done += n\n+ if err != nil {\n+ break\n+ }\n+ if n != len(v) {\n+ panic(fmt.Sprintf(\"io.Writer.Write succeeded with incomplete write: %d != %d\", n, len(v)))\n+ }\n+ }\n+ if !peek {\n+ d.pk.buf.TrimFront(int64(done))\n+ }\n+ return done, err\n+}\n+\n// CapLength reduces d to at most length bytes.\nfunc (d PacketData) CapLength(length int) {\nif length < 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -51,6 +51,8 @@ type TransportEndpointID struct {\n}\n// NetworkPacketInfo holds information about a network layer packet.\n+//\n+// +stateify savable\ntype NetworkPacketInfo struct {\n// LocalAddressBroadcast is true if the packet's local address is a broadcast\n// address.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/route.go",
"new_path": "pkg/tcpip/stack/route.go",
"diff": "@@ -52,6 +52,7 @@ type Route struct {\nlinkRes *linkResolver\n}\n+// +stateify savable\ntype routeInfo struct {\nRemoteAddress tcpip.Address\n@@ -97,6 +98,8 @@ func (r *Route) Loop() PacketLooping {\n}\n// RouteInfo contains all of Route's exported fields.\n+//\n+// +stateify savable\ntype RouteInfo struct {\nrouteInfo\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/BUILD",
"new_path": "pkg/tcpip/transport/udp/BUILD",
"diff": "@@ -27,6 +27,7 @@ go_library(\nimports = [\"gvisor.dev/gvisor/pkg/tcpip/buffer\"],\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/buffer\",\n\"//pkg/sleep\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -37,7 +37,7 @@ type udpPacket struct {\nsenderAddress tcpip.FullAddress\ndestinationAddress tcpip.FullAddress\npacketInfo tcpip.IPPacketInfo\n- data buffer.VectorisedView `state:\".(buffer.VectorisedView)\"`\n+ pkt *stack.PacketBuffer\nreceivedAt time.Time `state:\".(int64)\"`\n// tos stores either the receiveTOS or receiveTClass value.\ntos uint8\n@@ -191,6 +191,7 @@ func (e *endpoint) Close() {\nfor !e.rcvList.Empty() {\np := e.rcvList.Front()\ne.rcvList.Remove(p)\n+ p.pkt.DecRef()\n}\ne.rcvMu.Unlock()\n@@ -226,7 +227,8 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\np := e.rcvList.Front()\nif !opts.Peek {\ne.rcvList.Remove(p)\n- e.rcvBufSize -= p.data.Size()\n+ defer p.pkt.DecRef()\n+ e.rcvBufSize -= p.pkt.Data().Size()\n}\ne.rcvMu.Unlock()\n@@ -272,14 +274,14 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\n// Read Result\nres := tcpip.ReadResult{\n- Total: p.data.Size(),\n+ Total: p.pkt.Data().Size(),\nControlMessages: cm,\n}\nif opts.NeedRemoteAddr {\nres.RemoteAddr = p.senderAddress\n}\n- n, err := p.data.ReadTo(dst, opts.Peek)\n+ n, err := p.pkt.Data().ReadTo(dst, opts.Peek)\nif n == 0 && err != nil {\nreturn res, &tcpip.ErrBadBuffer{}\n}\n@@ -513,7 +515,7 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, tcpip.Error) {\ne.rcvMu.Lock()\nif !e.rcvList.Empty() {\np := e.rcvList.Front()\n- v = p.data.Size()\n+ v = p.pkt.Data().Size()\n}\ne.rcvMu.Unlock()\nreturn v, nil\n@@ -917,10 +919,11 @@ func (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketB\nAddr: id.LocalAddress,\nPort: hdr.DestinationPort(),\n},\n- data: pkt.Data().ExtractVV(),\n+ pkt: pkt,\n}\n+ pkt.IncRef()\ne.rcvList.PushBack(packet)\n- e.rcvBufSize += packet.data.Size()\n+ e.rcvBufSize += pkt.Data().Size()\n// Save any useful information from the network header to the packet.\nswitch pkt.NetworkProtocolNumber {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/udp/endpoint_state.go",
"diff": "@@ -19,7 +19,6 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport\"\n)\n@@ -34,16 +33,6 @@ func (p *udpPacket) loadReceivedAt(nsec int64) {\np.receivedAt = time.Unix(0, nsec)\n}\n-// saveData saves udpPacket.data field.\n-func (p *udpPacket) saveData() buffer.VectorisedView {\n- return p.data.Clone(nil)\n-}\n-\n-// loadData loads udpPacket.data field.\n-func (p *udpPacket) loadData(data buffer.VectorisedView) {\n- p.data = data\n-}\n-\n// afterLoad is invoked by stateify.\nfunc (e *endpoint) afterLoad() {\nstack.StackFromEnv.RegisterRestoredEndpoint(e)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Modify udpPacket to hold a PacketBuffer reference instead of a VectorizedView.
PiperOrigin-RevId: 411896048 |
259,992 | 23.11.2021 15:23:25 | 28,800 | 82fd0523dcefb3c39e50bbd8d77928758c31f546 | Skip readonly controllers
Some system have controller directories created, but they are
read-only. Handle that case and skip optional controllers.
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"bufio\"\n\"context\"\n\"encoding/json\"\n+ \"errors\"\n\"fmt\"\n\"io\"\n\"io/ioutil\"\n@@ -445,7 +446,7 @@ func createController(c Cgroup, name string) (bool, error) {\npath := c.MakePath(name)\nlog.Debugf(\"Creating cgroup %q: %q\", name, path)\nif err := os.MkdirAll(path, 0755); err != nil {\n- return false, err\n+ return errors.Is(err, unix.EROFS), err\n}\nreturn false, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip readonly controllers
Some system have controller directories created, but they are
read-only. Handle that case and skip optional controllers.
Closes #5887
PiperOrigin-RevId: 411907208 |
259,891 | 23.11.2021 16:57:47 | 28,800 | 654af2af2e5866bd5adc1f01c2faf0663eb3ca77 | Explicitly pass TCP payload size in conntrack | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -193,14 +193,14 @@ func (cn *conn) update(pkt *PacketBuffer, reply bool) {\n// client. However, we only need to know whether the connection is\n// established or not, so the client/server distinction isn't important.\nif cn.tcb.IsEmpty() {\n- cn.tcb.Init(tcpHeader)\n+ cn.tcb.Init(tcpHeader, pkt.Data().Size())\nreturn\n}\nif reply {\n- cn.tcb.UpdateStateReply(tcpHeader)\n+ cn.tcb.UpdateStateReply(tcpHeader, pkt.Data().Size())\n} else {\n- cn.tcb.UpdateStateOriginal(tcpHeader)\n+ cn.tcb.UpdateStateOriginal(tcpHeader, pkt.Data().Size())\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"diff": "@@ -55,9 +55,10 @@ type TCB struct {\nreply stream\noriginal stream\n- // State handlers.\n- handlerReply func(*TCB, header.TCP) Result\n- handlerOriginal func(*TCB, header.TCP) Result\n+ // State handlers. hdr is not guaranteed to contain bytes beyond the TCP\n+ // header itself, i.e. it may not contain the payload.\n+ handlerReply func(tcb *TCB, hdr header.TCP, dataLen int) Result\n+ handlerOriginal func(tcb *TCB, hdr header.TCP, dataLen int) Result\n// firstFin holds a pointer to the first stream to send a FIN.\nfirstFin *stream\n@@ -67,13 +68,13 @@ type TCB struct {\n}\n// Init initializes the state of the TCB according to the initial SYN.\n-func (t *TCB) Init(initialSyn header.TCP) Result {\n+func (t *TCB) Init(initialSyn header.TCP, dataLen int) Result {\nt.handlerReply = synSentStateReply\nt.handlerOriginal = synSentStateOriginal\niss := seqnum.Value(initialSyn.SequenceNumber())\nt.original.una = iss\n- t.original.nxt = iss.Add(logicalLen(initialSyn))\n+ t.original.nxt = iss.Add(logicalLen(initialSyn, dataLen))\nt.original.end = t.original.nxt\n// Even though \"end\" is a sequence number, we don't know the initial\n@@ -88,8 +89,8 @@ func (t *TCB) Init(initialSyn header.TCP) Result {\n// UpdateStateReply updates the state of the TCB based on the supplied reply\n// segment.\n-func (t *TCB) UpdateStateReply(tcp header.TCP) Result {\n- st := t.handlerReply(t, tcp)\n+func (t *TCB) UpdateStateReply(tcp header.TCP, dataLen int) Result {\n+ st := t.handlerReply(t, tcp, dataLen)\nif st != ResultDrop {\nt.state = st\n}\n@@ -98,8 +99,8 @@ func (t *TCB) UpdateStateReply(tcp header.TCP) Result {\n// UpdateStateOriginal updates the state of the TCB based on the supplied\n// original segment.\n-func (t *TCB) UpdateStateOriginal(tcp header.TCP) Result {\n- st := t.handlerOriginal(t, tcp)\n+func (t *TCB) UpdateStateOriginal(tcp header.TCP, dataLen int) Result {\n+ st := t.handlerOriginal(t, tcp, dataLen)\nif st != ResultDrop {\nt.state = st\n}\n@@ -148,7 +149,7 @@ func (t *TCB) adaptResult(r Result) Result {\n// synSentStateReply is the state handler for reply segments when the\n// connection is in SYN-SENT state.\n-func synSentStateReply(t *TCB, tcp header.TCP) Result {\n+func synSentStateReply(t *TCB, tcp header.TCP, dataLen int) Result {\nflags := tcp.Flags()\nackPresent := flags&header.TCPFlagAck != 0\nack := seqnum.Value(tcp.AckNumber())\n@@ -177,7 +178,7 @@ func synSentStateReply(t *TCB, tcp header.TCP) Result {\n// Update state informed by this SYN.\nirs := seqnum.Value(tcp.SequenceNumber())\nt.reply.una = irs\n- t.reply.nxt = irs.Add(logicalLen(tcp))\n+ t.reply.nxt = irs.Add(logicalLen(tcp, dataLen))\nt.reply.end += irs\nt.original.end = t.original.una.Add(seqnum.Size(tcp.WindowSize()))\n@@ -204,7 +205,7 @@ func synSentStateReply(t *TCB, tcp header.TCP) Result {\n// synSentStateOriginal is the state handler for original segments when the\n// connection is in SYN-SENT state.\n-func synSentStateOriginal(t *TCB, tcp header.TCP) Result {\n+func synSentStateOriginal(t *TCB, tcp header.TCP, _ int) Result {\n// Drop original segments that aren't retransmits of the original one.\nif tcp.Flags() != header.TCPFlagSyn ||\ntcp.SequenceNumber() != uint32(t.original.una) {\n@@ -222,10 +223,10 @@ func synSentStateOriginal(t *TCB, tcp header.TCP) Result {\n// update updates the state of reply and original streams, given the supplied\n// reply segment. For original segments, this same function can be called with\n// swapped reply/original streams.\n-func update(tcp header.TCP, reply, original *stream, firstFin **stream) Result {\n+func update(tcp header.TCP, reply, original *stream, firstFin **stream, dataLen int) Result {\n// Ignore segments out of the window.\ns := seqnum.Value(tcp.SequenceNumber())\n- if !reply.acceptable(s, dataLen(tcp)) {\n+ if !reply.acceptable(s, seqnum.Size(dataLen)) {\nreturn ResultAlive\n}\n@@ -257,7 +258,7 @@ func update(tcp header.TCP, reply, original *stream, firstFin **stream) Result {\n}\n// Advance the \"nxt\" index of the reply stream.\n- end := s.Add(logicalLen(tcp))\n+ end := s.Add(logicalLen(tcp, dataLen))\nif reply.nxt.LessThan(end) {\nreply.nxt = end\n}\n@@ -278,14 +279,14 @@ func update(tcp header.TCP, reply, original *stream, firstFin **stream) Result {\n// allOtherReply is the state handler for reply segments in all states\n// except SYN-SENT.\n-func allOtherReply(t *TCB, tcp header.TCP) Result {\n- return t.adaptResult(update(tcp, &t.reply, &t.original, &t.firstFin))\n+func allOtherReply(t *TCB, tcp header.TCP, dataLen int) Result {\n+ return t.adaptResult(update(tcp, &t.reply, &t.original, &t.firstFin, dataLen))\n}\n// allOtherOriginal is the state handler for original segments in all states\n// except SYN-SENT.\n-func allOtherOriginal(t *TCB, tcp header.TCP) Result {\n- return t.adaptResult(update(tcp, &t.original, &t.reply, &t.firstFin))\n+func allOtherOriginal(t *TCB, tcp header.TCP, dataLen int) Result {\n+ return t.adaptResult(update(tcp, &t.original, &t.reply, &t.firstFin, dataLen))\n}\n// streams holds the state of a TCP unidirectional stream.\n@@ -326,22 +327,16 @@ func (s *stream) closed() bool {\nreturn s.finSeen && s.fin.LessThan(s.una)\n}\n-// dataLen returns the length of the TCP segment payload.\n-func dataLen(tcp header.TCP) seqnum.Size {\n- return seqnum.Size(len(tcp) - int(tcp.DataOffset()))\n-}\n-\n// logicalLen calculates the logical length of the TCP segment.\n-func logicalLen(tcp header.TCP) seqnum.Size {\n- l := dataLen(tcp)\n+func logicalLen(tcp header.TCP, dataLen int) seqnum.Size {\nflags := tcp.Flags()\nif flags&header.TCPFlagSyn != 0 {\n- l++\n+ dataLen++\n}\nif flags&header.TCPFlagFin != 0 {\n- l++\n+ dataLen++\n}\n- return l\n+ return seqnum.Size(dataLen)\n}\n// IsEmpty returns true if tcb is not initialized.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack_test.go",
"new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack_test.go",
"diff": "@@ -35,7 +35,7 @@ func connected(t *testing.T, iss, irs uint32, isw, irw uint16) *tcpconntrack.TCB\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive SYN-ACK.\ntcp.Encode(&header.TCPFields{\n@@ -46,7 +46,7 @@ func connected(t *testing.T, iss, irs uint32, isw, irw uint16) *tcpconntrack.TCB\nWindowSize: isw,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -59,7 +59,7 @@ func connected(t *testing.T, iss, irs uint32, isw, irw uint16) *tcpconntrack.TCB\nWindowSize: irw,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -78,7 +78,7 @@ func TestConnectionRefused(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive RST.\ntcp.Encode(&header.TCPFields{\n@@ -89,7 +89,7 @@ func TestConnectionRefused(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -106,7 +106,7 @@ func TestConnectionRefusedInSynRcvd(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive SYN.\ntcp.Encode(&header.TCPFields{\n@@ -117,7 +117,7 @@ func TestConnectionRefusedInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -130,7 +130,7 @@ func TestConnectionRefusedInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -147,7 +147,7 @@ func TestConnectionResetInSynRcvd(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive SYN.\ntcp.Encode(&header.TCPFields{\n@@ -158,7 +158,7 @@ func TestConnectionResetInSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -170,7 +170,7 @@ func TestConnectionResetInSynRcvd(t *testing.T) {\nFlags: header.TCPFlagRst,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultReset {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultReset {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultReset)\n}\n}\n@@ -187,10 +187,10 @@ func TestRetransmitOnSynSent(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Retransmit the same SYN.\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultConnecting {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultConnecting {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultConnecting)\n}\n}\n@@ -207,7 +207,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive SYN. This will cause the state to go to SYN-RCVD.\ntcp.Encode(&header.TCPFields{\n@@ -218,7 +218,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -231,7 +231,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -244,7 +244,7 @@ func TestRetransmitOnSynRcvd(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -262,7 +262,7 @@ func TestClosedByOriginator(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -275,7 +275,7 @@ func TestClosedByOriginator(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -288,7 +288,7 @@ func TestClosedByOriginator(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultClosedByOriginator {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultClosedByOriginator {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByOriginator)\n}\n}\n@@ -306,7 +306,7 @@ func TestClosedByResponder(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -319,7 +319,7 @@ func TestClosedByResponder(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -332,7 +332,7 @@ func TestClosedByResponder(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultClosedByResponder {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultClosedByResponder {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByResponder)\n}\n}\n@@ -356,9 +356,9 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nFlags: header.TCPFlagAck,\nWindowSize: 30000,\n})\n- sseq += uint32(len(tcp)) - header.TCPMinimumSize\n+ sseq += uint32(dataLen(tcp)) - header.TCPMinimumSize\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -371,7 +371,7 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp[:header.TCPMinimumSize], dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -385,9 +385,9 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nFlags: header.TCPFlagAck,\nWindowSize: 50000,\n})\n- rseq += uint32(len(tcp)) - header.TCPMinimumSize\n+ rseq += uint32(dataLen(tcp))\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -400,7 +400,7 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp[:header.TCPMinimumSize]); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp[:header.TCPMinimumSize], dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -416,7 +416,7 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\n})\nsseq++\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -430,7 +430,7 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\n})\nrseq++\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -443,7 +443,7 @@ func TestSendAndReceiveDataClosedByOriginator(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultClosedByOriginator {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultClosedByOriginator {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultClosedByOriginator)\n}\n}\n@@ -460,7 +460,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\n})\ntcb := tcpconntrack.TCB{}\n- tcb.Init(tcp)\n+ tcb.Init(tcp, dataLen(tcp))\n// Receive a RST with a bad ACK, it should not cause the connection to\n// be reset.\n@@ -476,7 +476,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultConnecting {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultConnecting {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n@@ -492,7 +492,7 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 50000,\n})\n- if r := tcb.UpdateStateReply(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateReply(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n@@ -505,7 +505,13 @@ func TestIgnoreBadResetOnSynSent(t *testing.T) {\nWindowSize: 30000,\n})\n- if r := tcb.UpdateStateOriginal(tcp); r != tcpconntrack.ResultAlive {\n+ if r := tcb.UpdateStateOriginal(tcp, dataLen(tcp)); r != tcpconntrack.ResultAlive {\nt.Fatalf(\"Bad result: got %v, want %v\", r, tcpconntrack.ResultAlive)\n}\n}\n+\n+// dataLen returns the length of the TCP payload assuming that both the header\n+// and payload are in tcp.\n+func dataLen(tcp header.TCP) int {\n+ return len(tcp) - int(tcp.DataOffset())\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Explicitly pass TCP payload size in conntrack
PiperOrigin-RevId: 411925572 |
259,891 | 23.11.2021 17:40:37 | 28,800 | 5e984d5aa2c3f98934040e199d460c74744e5799 | conntrack: account for window scaling
Conntrack was not reading the window scale TCP option and thus could reject
valid packets for being beyond the receive window.
Addresses | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -160,7 +160,9 @@ go_test(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/seqnum\",\n\"//pkg/tcpip/testutil\",\n+ \"//pkg/tcpip/transport/tcpconntrack\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n\"@com_github_google_go_cmp//cmp/cmpopts:go_default_library\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack_test.go",
"new_path": "pkg/tcpip/stack/conntrack_test.go",
"diff": "@@ -17,9 +17,13 @@ package stack\nimport (\n\"testing\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcpconntrack\"\n)\nfunc TestReap(t *testing.T) {\n@@ -31,15 +35,16 @@ func TestReap(t *testing.T) {\nct.init()\nct.checkNumTuples(t, 0)\n- // Simulate sending a SYN. This will get the connection into conntrack, but\n- // the connection won't be considered established. Thus the timeout for\n- // reaping is unestablishedTimeout.\n- pkt1 := genTCPPacket()\n- pkt1.tuple = ct.getConnAndUpdate(pkt1)\n// We set rt.routeInfo.Loop to avoid a panic when handlePacket calls\n// rt.RequiresTXTransportChecksum.\nvar rt Route\nrt.routeInfo.Loop = PacketLoop\n+\n+ // Simulate sending a SYN. This will get the connection into conntrack, but\n+ // the connection won't be considered established. Thus the timeout for\n+ // reaping is unestablishedTimeout.\n+ pkt1 := genTCPPacket(genTCPOpts{})\n+ pkt1.tuple = ct.getConnAndUpdate(pkt1)\nif pkt1.tuple.conn.handlePacket(pkt1, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n}\n@@ -48,7 +53,7 @@ func TestReap(t *testing.T) {\n// Travel a little into the future and send the same SYN. This should update\n// lastUsed, but per #6748 didn't.\nclock.Advance(unestablishedTimeout / 2)\n- pkt2 := genTCPPacket()\n+ pkt2 := genTCPPacket(genTCPOpts{})\npkt2.tuple = ct.getConnAndUpdate(pkt2)\nif pkt2.tuple.conn.handlePacket(pkt2, Output, &rt) {\nt.Fatal(\"handlePacket() shouldn't perform any NAT\")\n@@ -68,31 +73,286 @@ func TestReap(t *testing.T) {\nct.checkNumTuples(t, 0)\n}\n+func TestWindowScaling(t *testing.T) {\n+ tcs := []struct {\n+ name string\n+ windowSize uint16\n+ synScale uint8\n+ synAckScale uint8\n+ dataLen int\n+ finalSeq uint32\n+ }{\n+ {\n+ name: \"no scale, full overlap\",\n+ windowSize: 4,\n+ dataLen: 2,\n+ finalSeq: 2,\n+ },\n+ {\n+ name: \"no scale, partial overlap\",\n+ windowSize: 4,\n+ dataLen: 8,\n+ finalSeq: 4,\n+ },\n+ {\n+ name: \"scale, full overlap\",\n+ windowSize: 4,\n+ synScale: 1,\n+ synAckScale: 1,\n+ dataLen: 6,\n+ finalSeq: 6,\n+ },\n+ {\n+ name: \"scale, partial overlap\",\n+ windowSize: 4,\n+ synScale: 1,\n+ synAckScale: 1,\n+ dataLen: 10,\n+ finalSeq: 8,\n+ },\n+ {\n+ name: \"SYN scale larger\",\n+ windowSize: 4,\n+ synScale: 2,\n+ synAckScale: 1,\n+ dataLen: 10,\n+ finalSeq: 8,\n+ },\n+ {\n+ name: \"SYN/ACK scale larger\",\n+ windowSize: 4,\n+ synScale: 1,\n+ synAckScale: 2,\n+ dataLen: 10,\n+ finalSeq: 10,\n+ },\n+ }\n+\n+ for _, tc := range tcs {\n+ t.Run(tc.name, func(t *testing.T) {\n+ testWindowScaling(t, tc.windowSize, tc.synScale, tc.synAckScale, tc.dataLen, tc.finalSeq)\n+ })\n+ }\n+}\n+\n+// testWindowScaling performs a TCP handshake with the given parameters,\n+// attaching dataLen bytes as the payload to the final ACK.\n+func testWindowScaling(t *testing.T, windowSize uint16, synScale, synAckScale uint8, dataLen int, finalSeq uint32) {\n+ // Initialize conntrack.\n+ clock := faketime.NewManualClock()\n+ ct := ConnTrack{\n+ clock: clock,\n+ }\n+ ct.init()\n+ ct.checkNumTuples(t, 0)\n+\n+ // We set rt.routeInfo.Loop to avoid a panic when handlePacket calls\n+ // rt.RequiresTXTransportChecksum.\n+ var rt Route\n+ rt.routeInfo.Loop = PacketLoop\n+\n+ var (\n+ rwnd = windowSize\n+ seqOrig = uint32(10)\n+ seqRepl = uint32(20)\n+ flags = header.TCPFlags(header.TCPFlagSyn)\n+ originatorAddr = testutil.MustParse4(\"1.0.0.1\")\n+ responderAddr = testutil.MustParse4(\"1.0.0.2\")\n+ originatorPort = uint16(5555)\n+ responderPort = uint16(6666)\n+ )\n+\n+ // Send SYN outbound through conntrack, simulating the Output hook.\n+ synPkt := genTCPPacket(genTCPOpts{\n+ windowSize: &rwnd,\n+ windowScale: synScale,\n+ seqNum: &seqOrig,\n+ flags: &flags,\n+ srcAddr: &originatorAddr,\n+ dstAddr: &responderAddr,\n+ srcPort: &originatorPort,\n+ dstPort: &responderPort,\n+ })\n+ synPkt.tuple = ct.getConnAndUpdate(synPkt)\n+ if synPkt.tuple.conn.handlePacket(synPkt, Output, &rt) {\n+ t.Fatal(\"handlePacket() shouldn't perform any NAT\")\n+ }\n+ ct.checkNumTuples(t, 1)\n+\n+ // Simulate the Postrouting hook.\n+ synPkt.tuple.conn.finalize()\n+ conn := synPkt.tuple.conn\n+ synPkt.tuple = nil\n+ ct.checkNumTuples(t, 2)\n+ conn.stateMu.Lock()\n+ if got, want := conn.tcb.State(), tcpconntrack.ResultConnecting; got != want {\n+ t.Fatalf(\"connection in state %v, but wanted %v\", got, want)\n+ }\n+ conn.stateMu.Unlock()\n+ conn.checkOriginalSeq(t, seqOrig+1)\n+\n+ // Send SYN/ACK, simulating the Prerouting hook.\n+ seqOrig++\n+ flags |= header.TCPFlagAck\n+ synAckPkt := genTCPPacket(genTCPOpts{\n+ windowSize: &windowSize,\n+ windowScale: synAckScale,\n+ seqNum: &seqRepl,\n+ ackNum: &seqOrig,\n+ flags: &flags,\n+ srcAddr: &responderAddr,\n+ dstAddr: &originatorAddr,\n+ srcPort: &responderPort,\n+ dstPort: &originatorPort,\n+ })\n+ synAckPkt.tuple = ct.getConnAndUpdate(synAckPkt)\n+ if synAckPkt.tuple.conn.handlePacket(synAckPkt, Prerouting, &rt) {\n+ t.Fatal(\"handlePacket() shouldn't perform any NAT\")\n+ }\n+ ct.checkNumTuples(t, 2)\n+\n+ // Simulate the Input hook.\n+ synAckPkt.tuple.conn.finalize()\n+ synAckPkt.tuple = nil\n+ ct.checkNumTuples(t, 2)\n+ conn.stateMu.Lock()\n+ if got, want := conn.tcb.State(), tcpconntrack.ResultAlive; got != want {\n+ t.Fatalf(\"connection in state %v, but wanted %v\", got, want)\n+ }\n+ conn.stateMu.Unlock()\n+ conn.checkReplySeq(t, seqRepl+1)\n+\n+ // Send ACK with a payload, simulating the Output hook.\n+ seqRepl++\n+ flags = header.TCPFlagAck\n+ ackPkt := genTCPPacket(genTCPOpts{\n+ windowSize: &windowSize,\n+ seqNum: &seqOrig,\n+ ackNum: &seqRepl,\n+ flags: &flags,\n+ data: make([]byte, dataLen),\n+ srcAddr: &originatorAddr,\n+ dstAddr: &responderAddr,\n+ srcPort: &originatorPort,\n+ dstPort: &responderPort,\n+ })\n+ ackPkt.tuple = ct.getConnAndUpdate(ackPkt)\n+ if ackPkt.tuple.conn.handlePacket(ackPkt, Output, &rt) {\n+ t.Fatal(\"handlePacket() shouldn't perform any NAT\")\n+ }\n+ ct.checkNumTuples(t, 2)\n+\n+ // Simulate the Postrouting hook.\n+ ackPkt.tuple.conn.finalize()\n+ ackPkt.tuple = nil\n+ ct.checkNumTuples(t, 2)\n+ conn.stateMu.Lock()\n+ if got, want := conn.tcb.State(), tcpconntrack.ResultAlive; got != want {\n+ t.Fatalf(\"connection in state %v, but wanted %v\", got, want)\n+ }\n+ conn.stateMu.Unlock()\n+ // Depending on the test, all or a fraction of dataLen will go towards\n+ // advancing the sequence number.\n+ conn.checkOriginalSeq(t, finalSeq+seqOrig)\n+\n+ // Go into the future to make sure we don't reap active connections quickly.\n+ clock.Advance(unestablishedTimeout * 2)\n+ ct.reapEverything()\n+ ct.checkNumTuples(t, 2)\n+\n+ // Go way into the future to make sure we eventually reap active connections.\n+ clock.Advance(establishedTimeout)\n+ ct.reapEverything()\n+ ct.checkNumTuples(t, 0)\n+}\n+\n+type genTCPOpts struct {\n+ windowSize *uint16\n+ windowScale uint8\n+ seqNum *uint32\n+ ackNum *uint32\n+ flags *header.TCPFlags\n+ data []byte\n+ srcAddr *tcpip.Address\n+ dstAddr *tcpip.Address\n+ srcPort *uint16\n+ dstPort *uint16\n+}\n+\n// genTCPPacket returns an initialized IPv4 TCP packet.\n-func genTCPPacket() *PacketBuffer {\n- const packetLen = header.IPv4MinimumSize + header.TCPMinimumSize\n+func genTCPPacket(opts genTCPOpts) *PacketBuffer {\n+ // Get values from opts.\n+ windowSize := uint16(50000)\n+ if opts.windowSize != nil {\n+ windowSize = *opts.windowSize\n+ }\n+ tcpHdrSize := uint8(header.TCPMinimumSize)\n+ if opts.windowScale != 0 {\n+ tcpHdrSize += 4 // 3 bytes of window scale plus 1 of padding.\n+ }\n+ seqNum := uint32(7777)\n+ if opts.seqNum != nil {\n+ seqNum = *opts.seqNum\n+ }\n+ ackNum := uint32(8888)\n+ if opts.ackNum != nil {\n+ ackNum = *opts.ackNum\n+ }\n+ flags := header.TCPFlagSyn\n+ if opts.flags != nil {\n+ flags = *opts.flags\n+ }\n+ srcAddr := testutil.MustParse4(\"1.0.0.1\")\n+ if opts.srcAddr != nil {\n+ srcAddr = *opts.srcAddr\n+ }\n+ dstAddr := testutil.MustParse4(\"1.0.0.2\")\n+ if opts.dstAddr != nil {\n+ dstAddr = *opts.dstAddr\n+ }\n+ srcPort := uint16(5555)\n+ if opts.srcPort != nil {\n+ srcPort = *opts.srcPort\n+ }\n+ dstPort := uint16(6666)\n+ if opts.dstPort != nil {\n+ dstPort = *opts.dstPort\n+ }\n+\n+ // Initialize the PacketBuffer.\n+ packetLen := header.IPv4MinimumSize + uint16(tcpHdrSize)\npkt := NewPacketBuffer(PacketBufferOptions{\n- ReserveHeaderBytes: packetLen,\n+ ReserveHeaderBytes: int(packetLen),\n+ Data: buffer.NewVectorisedView(len(opts.data), []buffer.View{opts.data}),\n})\npkt.NetworkProtocolNumber = header.IPv4ProtocolNumber\npkt.TransportProtocolNumber = header.TCPProtocolNumber\n- tcpHdr := header.TCP(pkt.TransportHeader().Push(header.TCPMinimumSize))\n- tcpHdr.Encode(&header.TCPFields{\n- SrcPort: 5555,\n- DstPort: 6666,\n- SeqNum: 7777,\n- AckNum: 8888,\n- DataOffset: header.TCPMinimumSize,\n- Flags: header.TCPFlagSyn,\n- WindowSize: 50000,\n+\n+ // Craft the TCP header, including the window scale option if necessary.\n+ tcpHdr := header.TCP(pkt.TransportHeader().Push(int(tcpHdrSize)))\n+ tcpHdr[:header.TCPMinimumSize].Encode(&header.TCPFields{\n+ SrcPort: srcPort,\n+ DstPort: dstPort,\n+ SeqNum: seqNum,\n+ AckNum: ackNum,\n+ DataOffset: tcpHdrSize,\n+ Flags: flags,\n+ WindowSize: windowSize,\nChecksum: 0, // Conntrack doesn't verify the checksum.\n})\n+ if opts.windowScale != 0 {\n+ // Set the window scale option, which is 3 bytes long. The option is\n+ // properly padded because the final remaining byte is already zeroed.\n+ _ = header.EncodeWSOption(int(opts.windowScale), tcpHdr[header.TCPMinimumSize:])\n+ }\n+\n+ // Craft an IPv4 header.\nipHdr := header.IPv4(pkt.NetworkHeader().Push(header.IPv4MinimumSize))\nipHdr.Encode(&header.IPv4Fields{\nTotalLength: packetLen,\nProtocol: uint8(header.TCPProtocolNumber),\n- SrcAddr: testutil.MustParse4(\"1.0.0.1\"),\n- DstAddr: testutil.MustParse4(\"1.0.0.2\"),\n+ SrcAddr: srcAddr,\n+ DstAddr: dstAddr,\nChecksum: 0, // Conntrack doesn't verify the checksum.\n})\n@@ -130,3 +390,23 @@ func (ct *ConnTrack) reapEverything() {\nbucket = newBucket\n}\n}\n+\n+func (cn *conn) checkOriginalSeq(t *testing.T, seq uint32) {\n+ t.Helper()\n+ cn.stateMu.Lock()\n+ defer cn.stateMu.Unlock()\n+\n+ if got, want := cn.tcb.OriginalSendSequenceNumber(), seqnum.Value(seq); got != want {\n+ t.Fatalf(\"checkOriginalSeq: got %d, wanted %d\", got, want)\n+ }\n+}\n+\n+func (cn *conn) checkReplySeq(t *testing.T, seq uint32) {\n+ t.Helper()\n+ cn.stateMu.Lock()\n+ defer cn.stateMu.Unlock()\n+\n+ if got, want := cn.tcb.ReplySendSequenceNumber(), seqnum.Value(seq); got != want {\n+ t.Fatalf(\"checkReplySeq: got %d, wanted %d\", got, want)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"new_path": "pkg/tcpip/transport/tcpconntrack/tcp_conntrack.go",
"diff": "@@ -49,6 +49,10 @@ const (\nResultClosedByOriginator\n)\n+// maxWindowShift is the maximum shift value of the per the windows scale\n+// option defined by RFC 1323.\n+const maxWindowShift = 14\n+\n// TCB is a TCP Control Block. It holds state necessary to keep track of a TCP\n// connection and inform the caller when the connection has been closed.\ntype TCB struct {\n@@ -74,8 +78,12 @@ func (t *TCB) Init(initialSyn header.TCP, dataLen int) Result {\niss := seqnum.Value(initialSyn.SequenceNumber())\nt.original.una = iss\n- t.original.nxt = iss.Add(logicalLen(initialSyn, dataLen))\n+ t.original.nxt = iss.Add(logicalLenSyn(initialSyn, dataLen))\nt.original.end = t.original.nxt\n+ // TODO(gvisor.dev/issue/6734): Cache TCP options instead of re-parsing them.\n+ // Because original and reply are streams, scale applies to the reply; it is\n+ // the receive window in the reply direction.\n+ t.reply.shiftCnt = header.ParseSynOptions(initialSyn.Options(), false /* isAck */).WS\n// Even though \"end\" is a sequence number, we don't know the initial\n// receive sequence number yet, so we store the window size until we get\n@@ -175,13 +183,37 @@ func synSentStateReply(t *TCB, tcp header.TCP, dataLen int) Result {\nreturn ResultConnecting\n}\n+ // TODO(gvisor.dev/issue/6734): Cache TCP options instead of re-parsing them.\n+ // Because original and reply are streams, scale applies to the reply; it is\n+ // the receive window in the original direction.\n+ t.original.shiftCnt = header.ParseSynOptions(tcp.Options(), ackPresent).WS\n+\n+ // Window scaling works only when both ends use the scale option.\n+ if t.original.shiftCnt != -1 && t.reply.shiftCnt != -1 {\n+ // Per RFC 1323 section 2.3:\n+ //\n+ // \"If a Window Scale option is received with a shift.cnt value exceeding\n+ // 14, the TCP should log the error but use 14 instead of the specified\n+ // value.\"\n+ if t.original.shiftCnt > maxWindowShift {\n+ t.original.shiftCnt = maxWindowShift\n+ }\n+ if t.reply.shiftCnt > maxWindowShift {\n+ t.original.shiftCnt = maxWindowShift\n+ }\n+ } else {\n+ t.original.shiftCnt = 0\n+ t.reply.shiftCnt = 0\n+ }\n// Update state informed by this SYN.\nirs := seqnum.Value(tcp.SequenceNumber())\nt.reply.una = irs\n- t.reply.nxt = irs.Add(logicalLen(tcp, dataLen))\n- t.reply.end += irs\n+ t.reply.nxt = irs.Add(logicalLen(tcp, dataLen, seqnum.Size(t.reply.end) /* end currently holds the receive window size */))\n+ t.reply.end <<= t.reply.shiftCnt\n+ t.reply.end.UpdateForward(seqnum.Size(irs))\n- t.original.end = t.original.una.Add(seqnum.Size(tcp.WindowSize()))\n+ windowSize := t.original.windowSize(tcp)\n+ t.original.end = t.original.una.Add(windowSize)\n// If the ACK was set (it is acceptable), update our unacknowledgement\n// tracking.\n@@ -191,7 +223,7 @@ func synSentStateReply(t *TCB, tcp header.TCP, dataLen int) Result {\nt.original.una = ack\n}\n- if end := ack.Add(seqnum.Size(tcp.WindowSize())); t.original.end.LessThan(end) {\n+ if end := ack.Add(seqnum.Size(windowSize)); t.original.end.LessThan(end) {\nt.original.end = end\n}\n}\n@@ -207,8 +239,7 @@ func synSentStateReply(t *TCB, tcp header.TCP, dataLen int) Result {\n// connection is in SYN-SENT state.\nfunc synSentStateOriginal(t *TCB, tcp header.TCP, _ int) Result {\n// Drop original segments that aren't retransmits of the original one.\n- if tcp.Flags() != header.TCPFlagSyn ||\n- tcp.SequenceNumber() != uint32(t.original.una) {\n+ if tcp.Flags() != header.TCPFlagSyn || tcp.SequenceNumber() != uint32(t.original.una) {\nreturn ResultDrop\n}\n@@ -253,12 +284,12 @@ func update(tcp header.TCP, reply, original *stream, firstFin **stream, dataLen\noriginal.una = ack\n}\n- if end := ack.Add(seqnum.Size(tcp.WindowSize())); original.end.LessThan(end) {\n+ if end := ack.Add(original.windowSize(tcp)); original.end.LessThan(end) {\noriginal.end = end\n}\n// Advance the \"nxt\" index of the reply stream.\n- end := s.Add(logicalLen(tcp, dataLen))\n+ end := s.Add(logicalLen(tcp, dataLen, reply.rwndSize()))\nif reply.nxt.LessThan(end) {\nreply.nxt = end\n}\n@@ -311,6 +342,11 @@ type stream struct {\n// rstSeen indicates if a RST has already been sent on this stream.\nrstSeen bool\n+\n+ // shiftCnt is the shift of the window scale of the receiver of the stream,\n+ // i.e. in a stream from A to B it is B's receive window scale. It cannot be\n+ // greater than maxWindowScale.\n+ shiftCnt int\n}\n// acceptable determines if the segment with the given sequence number and data\n@@ -327,16 +363,39 @@ func (s *stream) closed() bool {\nreturn s.finSeen && s.fin.LessThan(s.una)\n}\n-// logicalLen calculates the logical length of the TCP segment.\n-func logicalLen(tcp header.TCP, dataLen int) seqnum.Size {\n+// rwndSize returns the stream's receive window size.\n+func (s *stream) rwndSize() seqnum.Size {\n+ return s.una.Size(s.end)\n+}\n+\n+// windowSize returns the stream's window size accounting for scale.\n+func (s *stream) windowSize(tcp header.TCP) seqnum.Size {\n+ return seqnum.Size(tcp.WindowSize()) << s.shiftCnt\n+}\n+\n+// logicalLenSyn calculates the logical length of a SYN (without ACK) segment.\n+// It is similar to logicalLen, but does not impose a window size requirement\n+// because of the SYN.\n+func logicalLenSyn(tcp header.TCP, dataLen int) seqnum.Size {\n+ length := seqnum.Size(dataLen)\nflags := tcp.Flags()\nif flags&header.TCPFlagSyn != 0 {\n- dataLen++\n+ length++\n}\nif flags&header.TCPFlagFin != 0 {\n- dataLen++\n+ length++\n+ }\n+ return length\n+}\n+\n+// logicalLen calculates the logical length of the TCP segment.\n+func logicalLen(tcp header.TCP, dataLen int, windowSize seqnum.Size) seqnum.Size {\n+ // If the segment is too large, TCP trims the payload per RFC 793 page 70.\n+ length := logicalLenSyn(tcp, dataLen)\n+ if length > windowSize {\n+ length = windowSize\n}\n- return seqnum.Size(dataLen)\n+ return length\n}\n// IsEmpty returns true if tcb is not initialized.\n"
}
] | Go | Apache License 2.0 | google/gvisor | conntrack: account for window scaling
Conntrack was not reading the window scale TCP option and thus could reject
valid packets for being beyond the receive window.
Addresses #6734.
PiperOrigin-RevId: 411932393 |
259,907 | 29.11.2021 19:24:41 | 28,800 | 91d4826f5be789d67a02857f177160e94d1ba0e9 | Add support for flexible filename limits for tmpfs. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -117,9 +117,9 @@ func (fs *filesystem) Sync(ctx context.Context) error {\nreturn retErr\n}\n-// maxFilenameLen is the maximum length of a filename. This is dictated by 9P's\n+// MaxFilenameLen is the maximum length of a filename. This is dictated by 9P's\n// encoding of strings, which uses 2 bytes for the length prefix.\n-const maxFilenameLen = (1 << 16) - 1\n+const MaxFilenameLen = (1 << 16) - 1\n// dentrySlicePool is a pool of *[]*dentry used to store dentries for which\n// dentry.checkCachingLocked() must be called. The pool holds pointers to\n@@ -275,7 +275,7 @@ func (fs *filesystem) getChildAndWalkPathLocked(ctx context.Context, parent *den\n// Note that pit is a copy of the iterator that does not affect rp.\npit := rp.Pit()\nfirst := pit.String()\n- if len(first) > maxFilenameLen {\n+ if len(first) > MaxFilenameLen {\nreturn nil, linuxerr.ENAMETOOLONG\n}\nif child, ok := parent.children[first]; ok || parent.isSynthetic() {\n@@ -368,7 +368,7 @@ func (fs *filesystem) getChildAndWalkPathLocked(ctx context.Context, parent *den\n// * name is not \".\" or \"..\".\n// * parent and the dentry at name have been revalidated.\nfunc (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name string, ds **[]*dentry) (*dentry, error) {\n- if len(name) > maxFilenameLen {\n+ if len(name) > MaxFilenameLen {\nreturn nil, linuxerr.ENAMETOOLONG\n}\nif child, ok := parent.children[name]; ok || parent.isSynthetic() {\n@@ -511,7 +511,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nparent.dirMu.Lock()\ndefer parent.dirMu.Unlock()\n- if len(name) > maxFilenameLen {\n+ if len(name) > MaxFilenameLen {\nreturn linuxerr.ENAMETOOLONG\n}\n// Check for existence only if caching information is available. Otherwise,\n@@ -1696,8 +1696,8 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nif err := d.controlFDLisa.StatFSTo(ctx, &statFS); err != nil {\nreturn linux.Statfs{}, err\n}\n- if statFS.NameLength == 0 || statFS.NameLength > maxFilenameLen {\n- statFS.NameLength = maxFilenameLen\n+ if statFS.NameLength == 0 || statFS.NameLength > MaxFilenameLen {\n+ statFS.NameLength = MaxFilenameLen\n}\nreturn linux.Statfs{\n// This is primarily for distinguishing a gofer file system in\n@@ -1719,8 +1719,8 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\nreturn linux.Statfs{}, err\n}\nnameLen := uint64(fsstat.NameLength)\n- if nameLen == 0 || nameLen > maxFilenameLen {\n- nameLen = maxFilenameLen\n+ if nameLen == 0 || nameLen > MaxFilenameLen {\n+ nameLen = MaxFilenameLen\n}\nreturn linux.Statfs{\n// This is primarily for distinguishing a gofer file system in\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -69,7 +69,7 @@ afterSymlink:\nrp.Advance()\nreturn d.parent, nil\n}\n- if len(name) > linux.NAME_MAX {\n+ if len(name) > d.inode.fs.maxFilenameLen {\nreturn nil, linuxerr.ENAMETOOLONG\n}\nchild, ok := dir.childMap[name]\n@@ -163,7 +163,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nif name == \".\" || name == \"..\" {\nreturn linuxerr.EEXIST\n}\n- if len(name) > linux.NAME_MAX {\n+ if len(name) > fs.maxFilenameLen {\nreturn linuxerr.ENAMETOOLONG\n}\nif _, ok := parentDir.childMap[name]; ok {\n@@ -371,7 +371,7 @@ afterTrailingSymlink:\nif name == \".\" || name == \"..\" {\nreturn nil, linuxerr.EISDIR\n}\n- if len(name) > linux.NAME_MAX {\n+ if len(name) > fs.maxFilenameLen {\nreturn nil, linuxerr.ENAMETOOLONG\n}\n// Determine whether or not we need to create a file.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go",
"diff": "@@ -85,6 +85,8 @@ type filesystem struct {\nnextInoMinusOne uint64 // accessed using atomic memory operations\nroot *dentry\n+\n+ maxFilenameLen int\n}\n// Name implements vfs.FilesystemType.Name.\n@@ -115,6 +117,9 @@ type FilesystemOpts struct {\n// Usage is the memory accounting category under which pages backing files in\n// the filesystem are accounted.\nUsage *usage.MemoryKind\n+\n+ // MaxFilenameLen is the maximum filename length allowed by the tmpfs.\n+ MaxFilenameLen int\n}\n// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\n@@ -126,8 +131,8 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nrootFileType := uint16(linux.S_IFDIR)\nnewFSType := vfs.FilesystemType(&fstype)\n- tmpfsOpts, ok := opts.InternalData.(FilesystemOpts)\n- if ok {\n+ tmpfsOpts, tmpfsOptsOk := opts.InternalData.(FilesystemOpts)\n+ if tmpfsOptsOk {\nif tmpfsOpts.RootFileType != 0 {\nrootFileType = tmpfsOpts.RootFileType\n}\n@@ -203,8 +208,12 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndevMinor: devMinor,\nmopts: opts.Data,\nusage: memUsage,\n+ maxFilenameLen: linux.NAME_MAX,\n}\nfs.vfsfs.Init(vfsObj, newFSType, &fs)\n+ if tmpfsOptsOk && tmpfsOpts.MaxFilenameLen > 0 {\n+ fs.maxFilenameLen = tmpfsOpts.MaxFilenameLen\n+ }\nvar root *dentry\nswitch rootFileType {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for flexible filename limits for tmpfs.
PiperOrigin-RevId: 413038601 |
259,884 | 29.11.2021 21:24:21 | 28,800 | afd549d79c503129a052f6fa24a9313af6b856b0 | Check for support for xgetbv
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/ring0/kernel_amd64.go",
"new_path": "pkg/ring0/kernel_amd64.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"reflect\"\n\"sync\"\n+ \"gvisor.dev/gvisor/pkg/cpuid\"\n\"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n)\n@@ -268,13 +269,19 @@ func doSwitchToUser(\nvar (\nsentryXCR0 uintptr\n+ xgetbvIsSupported bool\nsentryXCR0Once sync.Once\n)\n// initSentryXCR0 saves a value of XCR0 in the host mode. It is used to\n// initialize XCR0 of guest vCPU-s.\nfunc initSentryXCR0() {\n- sentryXCR0Once.Do(func() { sentryXCR0 = xgetbv(0) })\n+ sentryXCR0Once.Do(func() {\n+ if cpuid.HostFeatureSet().HasFeature(cpuid.X86FeatureXSAVE) {\n+ sentryXCR0 = xgetbv(0)\n+ xgetbvIsSupported = true\n+ }\n+ })\n}\n// startGo is the CPU entrypoint.\n@@ -303,7 +310,9 @@ func startGo(c *CPU) {\nfninit()\n// Need to sync XCR0 with the host, because xsave and xrstor can be\n// called from different contexts.\n+ if xgetbvIsSupported {\nxsetbv(0, sentryXCR0)\n+ }\n// Set the syscall target.\nwrmsr(_MSR_LSTAR, kernelFunc(addrOfSysenter()))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Check for support for xgetbv
Fixes #5738
PiperOrigin-RevId: 413054140 |
259,883 | 26.11.2020 19:55:57 | -28,800 | 576c9e28748c8525da7d985f2daa81c189bc08d6 | blog: Running gVisor in Production at Scale in Ant
A blog about how Ant Group run gVisor in production at scale. | [
{
"change_type": "MODIFY",
"old_path": "website/_config.yml",
"new_path": "website/_config.yml",
"diff": "@@ -47,3 +47,9 @@ authors:\nnybidari:\nname: Nayana Bidari\nemail: [email protected]\n+ jianfengt:\n+ name: Jianfeng Tan\n+ email: [email protected]\n+ yonghe:\n+ name: Yong He\n+ email: [email protected]\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/images/2021-11-11-flamegraph-figure2.png",
"new_path": "website/assets/images/2021-11-11-flamegraph-figure2.png",
"diff": "Binary files /dev/null and b/website/assets/images/2021-11-11-flamegraph-figure2.png differ\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/images/2021-11-11-syscall-figure1.png",
"new_path": "website/assets/images/2021-11-11-syscall-figure1.png",
"diff": "Binary files /dev/null and b/website/assets/images/2021-11-11-syscall-figure1.png differ\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "website/blog/2021-11-11-running-gvisor-in-production-at-scale-in-ant.md",
"diff": "+# Running gVisor in Production at Scale in Ant\n+\n+>This post was contributed by [Ant Group](https://www.antgroup.com/), a\n+>large-scale digital payment platform. Jianfeng and Yong are engineers at Ant\n+>Group working on infrastructure systems, and contributors to gVisor.\n+\n+At Ant Group, we are committed to keep online transactions safe and efficient.\n+Continuously improving security for potential system-level attacks is one of\n+many measures. As a container runtime, gVisor provides container-native security\n+without sacrificing resource efficiency. Therefore, it has been on our radar\n+since it was released.\n+\n+However, there have been performance concerns raised by members of\n+[academia](https://www.usenix.org/system/files/hotcloud19-paper-young.pdf)\n+and [industry](https://news.ycombinator.com/item?id=19924036). Users of gVisor\n+tend to bear the extra overhead as the tax of security. But we tend to agree\n+that [security is no excuse for poor performance (See Chapter 6!)](https://sel4.systems/About/seL4-whitepaper.pdf).\n+\n+In this article, we will present how we identified bottlenecks in gVisor and\n+unblocked large-scale production adoption. Our main focus are the CPU\n+utilization and latency overhead it brings. Small memory footprint is also a\n+valued goal, but not discussed in this blog. As a result of these efforts and\n+community improvements, 70% of our applications running on runsc have <1%\n+overhead; another 25% have <3% overhead. Some of our most valued application\n+are the focus of our optimization, and get even better performance compared with\n+runc.\n+\n+The rest of this blog is organized as follows:\n+- First, we analyze the cost of different syscall paths in gVisor.\n+- Then, a way to profile a whole picture of a instance is proposed to find out\n+ if some slow syscall paths are encountered.\n+- Some invisible overhead in Go runtime is discussed.\n+- At last, a short summary on performance optimization with some other factors\n+ on production adoption.\n+\n+For convenience of discussion, we are targeting KVM-based, or hypervisor-based\n+platforms, unless explicitly stated.\n+\n+## Cost of different syscall paths\n+\n+[Defense-in-depth](../../../../2019/11/18/gvisor-security-basics-part-1/#defense-in-depth)\n+is the key design principle of gVisor. In gVisor, different syscalls have\n+different paths, further leading to different cost (orders of magnitude) on\n+latency and CPU consumption. Here are the syscall paths in gVisor.\n+\n+\n+\n+### Path 1: User-space vDSO\n+\n+Sentry provides a [vDSO library](https://github.com/google/gvisor/tree/master/vdso)\n+for its sandboxed processes. Several syscalls are short circuited and\n+implemented in user space. These syscalls cost almost as much as native Linux.\n+But note that the vDSO library is partially implemented. We once noticed some\n+[syscalls](https://github.com/google/gvisor/issues/3101) in our environment are\n+not properly terminated in user space. We create some additional implementations\n+to the vDSO, and aim to push these improvements upstream when possible.\n+\n+### Path 2: Sentry contained\n+\n+Most syscalls, e.g., <code>clone(2)</code>, are implemented in Sentry. They are\n+some basic abstractions of a operating system, such as process/thread lifecycle,\n+scheduling, IPC, memory management, etc. These syscalls and all below suffer\n+from a structural cost of syscall interception. The overhead is about 800ns\n+while that of the native syscalls is about 70ns. We'll dig it further below.\n+Syscalls of this kind spend takes about several microseconds, which is\n+competitive to the corresponding native Linux syscalls.\n+\n+### Path 3: Host-kernel involved\n+\n+Some syscalls, resource related, e.g., read/write, are redirected into the host\n+kernel. Note that gVisor never passes through application syscalls directly into\n+host kernel for functional and security reasons. So comparing to native Linux,\n+time spent in Sentry seems an extra overhead. Another overhead is the way\n+to call a host kernel syscall. Let's use kvm platform of x86_64 as an example.\n+After Sentry issues the syscall instruction, if it is in GR0, it first goes\n+to the syscall entrypoint defined in LSTAR, and then halts to HR3 (a vmexit\n+happens here), and exits from a signal handler, and executes syscall instruction\n+again. We can save the \"Halt to HR3\" by introducing vmcall here, but there's\n+still a syscall trampoline there and the vmexit/vmentry overhead is not trivial.\n+Nevertheless, these overhead is not that significant.\n+\n+For some sentry-contained syscalls in Path 2, although the syscall semantic is\n+terminated in Sentry, it may further introduces one or many unexpected exits to\n+host kernel. It could be a page fault when Sentry runs, and more likely, a\n+schedule event in Go runtime, e.g., M idle/wakeup. An example in hand is that\n+<code>futex(FUETX_WAIT)</code> and <code>epoll_wait(2)</code> could lead to M\n+idle and a further futex call into host kernel if it does not find any runnable\n+Gs. (See the comments in https://go.dev/src/runtime/proc.go for further\n+explanation about the GMP scheduler).\n+\n+### Path 4: Gofer involved\n+\n+Other IO-related syscalls, especially security sensitive, go through another\n+layer of protection - Gofer. For such a syscall, it usually involves one or\n+more Sentry/Gofer inter-process communications. Even with the recent\n+optimization that using lisafs to supersede P9, it's still the slowest path\n+which we shall try best to avoid.\n+\n+As shown above, some syscall paths are by-design slow, and should be identified\n+and reduced as much as possible. Let's hold it to the next section, and dig\n+into the details of the structural and implementation-specific cost of syscalls\n+firstly, because the performance of some Sentry-contained syscalls are not good\n+enough.\n+\n+### The structural cost\n+\n+The first kind of cost is the comparatively stable, introduced by syscall\n+interception. It is platform-specific depending on the way to intercept syscalls.\n+And whether this cost matters also depends on the syscall rate of sandboxed\n+applications.\n+\n+Here's the benchmark result on the structural cost of syscall. We got the data\n+on a Intel(R) Xeon(R) CPU E5-2650 v2 platform, using\n+[getpid benchmark](https://github.com/google/gvisor/blob/master/test/perf/linux/getpid_benchmark.cc).\n+As we can see, for KVM platform, the syscall interception costs more than 10x\n+than a native Linux syscall.\n+\n+| |getpid benchmark (ns)|\n+|------------|---------------------|\n+|Native |62 |\n+|Native-KPTI |236 |\n+|runsc-KVM |830 |\n+|runsc-ptrace|6249 |\n+\n+* \"Native\" stands for using vanilla linux kernel.\n+\n+To understand the structural cost of syscall interception,\n+we did a [quantitative analysis](https://github.com/google/gvisor/issues/2354)\n+on kvm platform. According to the analysis, the overhead mainly comes from:\n+\n+1. KPTI-like CR3 switches: to maintain the address equation of Sentry running\n+in HR3 and GR0, it has to switch CR3 register twice, on each user/kernel switch;\n+\n+2. Platform's Switch(): Linux is very efficient by just switching to a\n+per-thread kernel stack and calling the corresponding syscall entry function.\n+But in Sentry, each task is represented by a goroutine; before calling into\n+syscall entry functions, it needs to pop the stack to recover the big while\n+loop, i.e., kernel.(*Task).run.\n+\n+Can we save the structural cost of syscall interception? This cost is actually\n+by-design. We can optimize it, for example, avoid allocation and map operations\n+in switch process, but it can not be eliminated.\n+\n+Does the structural cost of syscall interception really matter? It depends on\n+the syscall rate. Most applications in our case have a syscall rate < 200K/sec,\n+and according to flame graphs (which will be described later in this blog), we\n+see 2~3% of samples are in the switch Secondly, most syscalls, except those\n+as simple as <code>getpid(2)</code>, take several microseconds. In proportion,\n+it's not a significant overhead. However, if you have an elephant RPC (which\n+involves many times of DB access), or a service served by a long-snake RPC\n+chain, this brings nontrivial overhead on latency.\n+\n+### The implementation-specific cost\n+\n+The other kind of cost is implementation-specific. For example, it involves\n+some heavy malloc operations; or defer is used in some frequent syscall paths\n+(defer is optimized in Go 1.14); what's worse, the application process may\n+trigger a long-path syscall with host kernel or Gofer involved.\n+\n+When we try to do optimization on the gVisor runtime, we need information\n+on the sandboxed applications, POD configurations, and runsc internals. But\n+most people only play either as platform engineer or application engineer.\n+So we need an easier way to understand the whole picture.\n+\n+## Performance profile of a running instance\n+\n+To quickly understand the whole picture of performance, we need some ways to\n+profile a running gVisor instance. As gVisor sandbox process is essentially a\n+Go process, Go pprof is an existing way:\n+\n+* [Go pprof](https://golang.org/pkg/runtime/pprof/) - provides CPU and heap\n+ profile through [runsc debug subcommands](https://gvisor.dev/docs/user_guide/debugging/#profiling).\n+* [Go trace](https://golang.org/pkg/runtime/trace/) - provides more\n+ internal profile types like synchronization blocking and scheduler latency.\n+\n+Unfortunately, above tools only provide hot-spots in Sentry, instead of the\n+whole picture (how much time spent in GR3 and HR0). And CPU profile relies on\n+the [SIGPROF signal](https://golang.org/pkg/runtime/pprof/), which may not\n+accurate enough.\n+\n+[perf-kvm](https://www.linux-kvm.org/page/Perf_events) cannot provide what we\n+need either. It may help to top/record/stat some information in guest with the\n+help of option [--guestkallsyms], but it cannot analyze the call chain (which\n+is not supported in the host kernel, see Linux's perf_callchain_kernel).\n+\n+### Perf sandbox process like a normal process\n+\n+Then we turn to a nice virtual address equation in Sentry: [(GR0 VA) = (HR3 VA)].\n+This is to make sure any pointers in HR3 can be directly used in GR0.\n+\n+The equation is helpful to solve this problem in the way that we can profile\n+Sentry just as a normal HR3 process with a little hack on kvm.\n+\n+- First, as said above, Linux does not support to analyze the call chain of\n+guest. So Change [is_in_guest] to pretend that it runs in host mode even it's\n+in guest mode. This can be done in\n+[kvm_is_in_guest](https://github.com/torvalds/linux/blob/v4.19/arch/x86/kvm/x86.c#L6560)\n+\n+```\n+int kvm_is_in_guest(void)\n+ {\n+- return __this_cpu_read(current_vcpu) != NULL;\n++ return 0;\n+ }\n+```\n+\n+- Secondly, change the process of guest profile. Previously, after PMU counter\n+overflows and triggers a NMI interrupt, vCPU is forced to exit to host, and\n+calls [int $2] immediately for later recording. Now instead of calling [int $2],\n+we shall call **do_nmi** directly with correct registers (i.e., pt_regs):\n+\n+```\n++void (*fn_do_nmi)(struct pt_regs *, long);\n++\n++#define HIGHER_HALF_CANONICAL_ADDR 0xFFFF800000000000\n++\n++void make_pt_regs(struct kvm_vcpu *vcpu, struct pt_regs *regs)\n++{\n++ /* In Sentry GR0, we will use address among\n++ * [HIGHER_HALF_CANONICAL_ADDR, 2^64-1)\n++ * when syscall just happens. To avoid conflicting with HR0,\n++ * we correct these addresses into HR3 addresses.\n++ */\n++ regs->bp = vcpu->arch.regs[VCPU_REGS_RBP] & ~HIGHER_HALF_CANONICAL_ADDR;\n++ regs->ip = vmcs_readl(GUEST_RIP) & ~HIGHER_HALF_CANONICAL_ADDR;\n++ regs->sp = vmcs_readl(GUEST_RSP) & ~HIGHER_HALF_CANONICAL_ADDR;\n++\n++ regs->flags = (vmcs_readl(GUEST_RFLAGS) & 0xFF) |\n++ X86_EFLAGS_IF | 0x2;\n++ regs->cs = __USER_CS;\n++ regs->ss = __USER_DS;\n++}\n++\n+ static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)\n+ {\n+ u32 exit_intr_info;\n+@@ -8943,7 +8965,14 @@ static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx)\n+ /* We need to handle NMIs before interrupts are enabled */\n+ if (is_nmi(exit_intr_info)) {\n+ kvm_before_handle_nmi(&vmx->vcpu);\n+- asm(\"int $2\");\n++ if (vmcs_readl(GUEST_RFLAGS) & X86_EFLAGS_IF)\n++ asm(\"int $2\");\n++ else {\n++ struct pt_regs regs;\n++ memset((void *)®s, 0, sizeof(regs));\n++ make_pt_regs(&vmx->vcpu, ®s);\n++ fn_do_nmi(®s, 0);\n++ }\n+ kvm_after_handle_nmi(&vmx->vcpu);\n+ }\n+ }\n+@@ -11881,6 +11927,10 @@ static int __init vmx_init(void)\n+ }\n+ }\n+\n++ fn_do_nmi = (void *) kallsyms_lookup_name(\"do_nmi\");\n++ if (!fn_do_nmi)\n++ printk(KERN_ERR \"kvm: lookup do_nmi fail\\n\");\n++\n+```\n+\n+As shown above, we properly handle samples in GR3 and GR0 trampoline.\n+\n+### An example of profile\n+\n+Firstly, make sure we compile the runsc with symbols not stripped:\n+```\n+bazel build runsc --strip=never\n+```\n+\n+As an example, run below script inside the gVisor container to make it busy:\n+```\n+stress -i 1 -c 1 -m 1\n+```\n+\n+Perf the instance with command:\n+```\n+perf kvm --host --guest record -a -g -e cycles -G <path/to/cgroup> -- sleep 10 >/dev/null\n+```\n+\n+Note we still need to perf the instance with 'perf kvm' and '--guest', because\n+kvm-intel requires this to keep the PMU hardware event enabled in guest mode.\n+\n+Then generate a flame graph using\n+[Brendan's tool](https://github.com/brendangregg/FlameGraph), and we got this\n+[flame graph](https://raw.githubusercontent.com/zhuangel/gvisor/zhuangel_blog/website/blog/blog-kvm-stress.svg).\n+\n+Let's roughly divide it to differentiate GR3 and GR0 like this:\n+\n+\n+\n+### Optimize based on flame graphs\n+\n+Now we can get clear information like:\n+\n+1. The bottleneck syscall(s): the above flame graph shows\n+<code>sync(2)</code> is a relatively large block of samples. If we cannot avoid\n+them in user space, they are worth time for optimization. Some real cases we\n+found and optimized are: supersede CopyIn/CopyOut with CopyInBytes/CopyOutBytes\n+to avoid reflection; avoid use defer in some frequent syscalls in which case you\n+can say <code>deferreturn()</code> in the flame graph (not needed if you already\n+upgrade to newer Go version). Another optimization is: after we find that append\n+write of shared volume spends a lot of time querying gofer for current file\n+length in the flame graph, we propose to add\n+[an handle only for append write](https://github.com/google/gvisor/issues/1792).\n+\n+2. If GC is a real problem: we can barely see sample related to GC in this\n+case. But if we do, we can further search <code>mallocgc()</code> to see where\n+the heap allocation is frequent. We can perform a heap profile to see allocated\n+objects. And we can consider adjust [GC percent](https://golang.org/pkg/runtime/debug/#SetGCPercent),\n+100% by default, to sacrifice memory for less CPU utilization. We once found\n+that allocating a object > 32 KB also triggers GC, referring to\n+[this](https://github.com/google/gvisor/commit/f697d1a33e4e7cefb4164ec977c38ccc2a228099).\n+\n+3. Percentage of time spent in GR3 app and Sentry: We can determine if it worths\n+to continue the optimization. If most of the samples are in GR3, then we better\n+turn to optimizing the application code instead.\n+\n+4. Rather large chunk of samples lie in ept violation and\n+<code>fallocate(2)</code> (into HR0). This is caused by frequent memory\n+allocation and free. We can either optimize the application to avoid this, or\n+add a memory buffer layer in memfile management to relieve it.\n+\n+As a short summary, now we have a tool to get a visible graph of what's going\n+on in a running gVisor instance. Unfortunately, we cannot get the details of\n+the application processes in the above flame graph because of the semantic gap.\n+To get a flame graph of the application processes, we have prototyped a way in\n+Sentry. Hopefully, we'll discuss it in later blogs.\n+\n+A visible way is very helpful when we try to optimize a new application on\n+gVisor. However, there's another kind of overhead, invisible like \"Dark matter\".\n+\n+## Invisible overhead in Go runtime\n+\n+Sentry inherits timer, scheduler, channel, and heap allocator in Go runtime.\n+While it saves a lot of code to build a kernel, it also introduces some\n+unpleasant overhead. The Go runtime, after all, is designed and massively used\n+for general purpose Go applications. While it's used as a part or the basis of a\n+kernel, we shall be very careful with the implementation and overhead of these\n+syntactic sugar.\n+\n+Unfortunately, we did not find an universal method to identify this kind of\n+overhead. The only way seems to get your hands dirty with Go runtime. We'll show\n+some examples in our use case.\n+\n+### Timer\n+\n+It's known that Go (before 1.14) timer suffers from\n+[lock contention and context switches](https://github.com/golang/go/issues/27707).\n+What's worse, statistics of Sentry syscalls shows that a lot of\n+<code>futex()</code> is introduced by timers (64 timer buckets), and that Sentry\n+syscalls walks a much longer path (redpill), makes it worse.\n+\n+We have two optimizations here: 1. decrease the number of timer buckets, from 64\n+to 4; 2. decrease the timer precision from ns to ms. You may worry about the\n+decrease of timer precision, but as we see, most of the applications are\n+event-based, and not affected by a coarse grained timer.\n+\n+However, Go changes the implementation of timer in v1.14; how to port this\n+optimization remains an open question.\n+\n+### Scheduler\n+\n+gVisor introduces an extra level of schedule along with the host linux\n+scheduler (usually CFS). A L2 scheduler sometimes brings positive impact as it\n+saves the heavy context switch in the L1 scheduler. We can find many two-level\n+scheduler cases, for example, coroutines, virtual machines, etc.\n+\n+gVisor reuses Go's work-stealing scheduler, which is originally designed for\n+coroutines, as the L2 scheduler. They share the same goal:\n+\n+\"We need to balance between keeping enough running worker threads to utilize\n+available hardware parallelism and parking excessive running worker threads\n+to conserve CPU resources and power.\" -- From\n+[Go scheduler code](https://golang.org/src/runtime/proc.go).\n+\n+If not properly tuned, the L2 scheduler may leak the schedule pressure to the\n+L1 scheduler. According to G-P-M model of Go, the parallelism is close related to\n+the GOMAXPROCS limit. The upstream gVisor by default uses # of host cores,\n+which leads to a lot of wasted M wake/stop(s). By properly configuring the\n+GOMAXPROCS of a POD of 4/8/16 cores, we find it can save some CPU cycles\n+without worsening the workload latency.\n+\n+To further restrict extra M wake/stop(s), before wakep(), we calculate the # of\n+running Gs and # of running Ps to decide if necessary to wake a M. And we find\n+it's better to firstly steal from the longest local run queue, comparing to\n+previously random-sequential way. Another related optimization is that we find\n+most applications will get back to Sentry very soon, and it's not necessary to\n+handle off its P when it leaves into user space and find an idle P when it gets\n+back.\n+\n+Some optimizations in Go are put [here](https://github.com/zhuangel/go/tree/go1.13.4.blog).\n+What we learned from the optimization process of gVisor is that digging into\n+Go runtime to understand what's going on there. And it's normal that some ideas\n+work, but some fail.\n+\n+## Summary\n+\n+We introduced how we profiled gVisor for production-ready performance. Using\n+this methodology, along with some other aggressive measures, we finally got to\n+run gVisor with an acceptable overhead, and even better than runc in some\n+workloads. We also absorbed a lot of optimization progress in the community,\n+e.g., VFS2.\n+\n+So far, we have deployed more than 100K gVisor instances in the production\n+environment. And it very well supported transactions of\n+[Singles Day Global Shopping Festivals](https://en.wikipedia.org/wiki/Singles%27_Day).\n+\n+Along with performance, there are also some other important aspects for\n+production adoption. For example, generating a core after a sentry panic is\n+helpful for debugging; a coverage tool is necessary to make sure new changes are\n+properly covered by test cases. We'll leave these topics to later discussions.\n"
},
{
"change_type": "MODIFY",
"old_path": "website/blog/BUILD",
"new_path": "website/blog/BUILD",
"diff": "@@ -59,6 +59,17 @@ doc(\npermalink = \"/blog/2021/08/31/gvisor-rack/\",\n)\n+doc(\n+ name = \"tune_gvisor_for_production_adoption\",\n+ src = \"2021-11-11-running-gvisor-in-production-at-scale-in-ant.md\",\n+ authors = [\n+ \"jianfengt\",\n+ \"yonghe\",\n+ ],\n+ layout = \"post\",\n+ permalink = \"/blog/2021/11/11/running-gvisor-in-production-at-scale-in-ant/\",\n+)\n+\ndocs(\nname = \"posts\",\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "website/index.md",
"new_path": "website/index.md",
"diff": "having to rearchitect your infrastructure.</p>\n<a class=\"button\" href=\"/docs/architecture_guide/platforms/\">Read More »</a>\n</div>\n+\n+ <div class=\"col-md-5\">\n+ <h4 id=\"platform-portability\">Tune gVisor for Production Adoption <sup>☁</sup>☁</h4>\n+ <p>TODO: introduction</p>\n+ <a class=\"button\" href=\"/docs/architecture_guide/platforms/\">Read More »</a>\n+ </div>\n+\n</div>\n</div> <!-- container -->\n"
}
] | Go | Apache License 2.0 | google/gvisor | blog: Running gVisor in Production at Scale in Ant
A blog about how Ant Group run gVisor in production at scale.
Signed-off-by: Jianfeng Tan <[email protected]>
Signed-off-by: Yong He <[email protected]> |
259,884 | 30.11.2021 22:14:58 | 28,800 | 72e222cd661477de4a9d15b01fe84e3fc4046dac | Handle empty values for XDG_RUNTIME_DIR properly.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -126,7 +126,8 @@ func NewFromFlags() (*Config, error) {\nif len(conf.RootDir) == 0 {\n// If not set, set default root dir to something (hopefully) user-writeable.\nconf.RootDir = \"/var/run/runsc\"\n- if runtimeDir, ok := os.LookupEnv(\"XDG_RUNTIME_DIR\"); ok {\n+ // NOTE: empty values for XDG_RUNTIME_DIR should be ignored.\n+ if runtimeDir := os.Getenv(\"XDG_RUNTIME_DIR\"); runtimeDir != \"\" {\nconf.RootDir = filepath.Join(runtimeDir, \"runsc\")\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle empty values for XDG_RUNTIME_DIR properly.
Fixes #6849
PiperOrigin-RevId: 413322019 |
260,004 | 01.12.2021 13:47:45 | 28,800 | 4aec33aac600635aad736d18de4df3f71de3aadd | Explicitly allow new connections to be created
This change is to prepare for later changes which may determine if a
packet is sent in response to an original packet so that the reply
packet does not create a new connection. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -357,66 +357,76 @@ func getTupleIDForPacketInICMPError(pkt *PacketBuffer, getNetAndTransHdr netAndT\nreturn tupleID{}, false\n}\n-func getTupleID(pkt *PacketBuffer) (tid tupleID, isICMPError bool, ok bool) {\n+type getTupleIDDisposition int\n+\n+const (\n+ getTupleIDNotOK getTupleIDDisposition = iota\n+ getTupleIDOKAndAllowNewConn\n+ getTupleIDOKAndDontAllowNewConn\n+)\n+\n+func getTupleID(pkt *PacketBuffer) (tupleID, getTupleIDDisposition) {\nswitch pkt.TransportProtocolNumber {\ncase header.TCPProtocolNumber:\nif transHeader := header.TCP(pkt.TransportHeader().View()); len(transHeader) >= header.TCPMinimumSize {\n- return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), false, true\n+ return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), getTupleIDOKAndAllowNewConn\n}\ncase header.UDPProtocolNumber:\nif transHeader := header.UDP(pkt.TransportHeader().View()); len(transHeader) >= header.UDPMinimumSize {\n- return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), false, true\n+ return getTupleIDForRegularPacket(pkt.Network(), pkt.NetworkProtocolNumber, transHeader, pkt.TransportProtocolNumber), getTupleIDOKAndAllowNewConn\n}\ncase header.ICMPv4ProtocolNumber:\nicmp := header.ICMPv4(pkt.TransportHeader().View())\nif len(icmp) < header.ICMPv4MinimumSize {\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nswitch icmp.Type() {\ncase header.ICMPv4DstUnreachable, header.ICMPv4TimeExceeded, header.ICMPv4ParamProblem:\ndefault:\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nh, ok := pkt.Data().PullUp(header.IPv4MinimumSize)\nif !ok {\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nipv4 := header.IPv4(h)\nif ipv4.HeaderLength() > header.IPv4MinimumSize {\n// TODO(https://gvisor.dev/issue/6765): Handle IPv4 options.\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nif tid, ok := getTupleIDForPacketInICMPError(pkt, v4NetAndTransHdr, header.IPv4ProtocolNumber, header.IPv4MinimumSize, ipv4.TransportProtocol()); ok {\n- return tid, true, true\n+ // Do not create a new connection in response to an ICMP error.\n+ return tid, getTupleIDOKAndDontAllowNewConn\n}\ncase header.ICMPv6ProtocolNumber:\nicmp := header.ICMPv6(pkt.TransportHeader().View())\nif len(icmp) < header.ICMPv6MinimumSize {\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nswitch icmp.Type() {\ncase header.ICMPv6DstUnreachable, header.ICMPv6PacketTooBig, header.ICMPv6TimeExceeded, header.ICMPv6ParamProblem:\ndefault:\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nh, ok := pkt.Data().PullUp(header.IPv6MinimumSize)\nif !ok {\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\n// TODO(https://gvisor.dev/issue/6789): Handle extension headers.\nif tid, ok := getTupleIDForPacketInICMPError(pkt, v6NetAndTransHdr, header.IPv6ProtocolNumber, header.IPv6MinimumSize, header.IPv6(h).TransportProtocol()); ok {\n- return tid, true, true\n+ // Do not create a new connection in response to an ICMP error.\n+ return tid, getTupleIDOKAndDontAllowNewConn\n}\n}\n- return tupleID{}, false, false\n+ return tupleID{}, getTupleIDNotOK\n}\nfunc (ct *ConnTrack) init() {\n@@ -433,9 +443,17 @@ func (ct *ConnTrack) init() {\nfunc (ct *ConnTrack) getConnAndUpdate(pkt *PacketBuffer) *tuple {\n// Get or (maybe) create a connection.\nt := func() *tuple {\n- tid, isICMPError, ok := getTupleID(pkt)\n- if !ok {\n+ var allowNewConn bool\n+ tid, res := getTupleID(pkt)\n+ switch res {\n+ case getTupleIDNotOK:\nreturn nil\n+ case getTupleIDOKAndAllowNewConn:\n+ allowNewConn = true\n+ case getTupleIDOKAndDontAllowNewConn:\n+ allowNewConn = false\n+ default:\n+ panic(fmt.Sprintf(\"unhandled %[1]T = %[1]d\", res))\n}\nbktID := ct.bucket(tid)\n@@ -449,8 +467,7 @@ func (ct *ConnTrack) getConnAndUpdate(pkt *PacketBuffer) *tuple {\nreturn t\n}\n- if isICMPError {\n- // Do not create a noop entry in response to an ICMP error.\n+ if !allowNewConn {\nreturn nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_test.go",
"new_path": "pkg/tcpip/stack/iptables_test.go",
"diff": "@@ -125,9 +125,9 @@ func TestNATedConnectionReap(t *testing.T) {\npkt := v6PacketBuffer()\n- originalTID, _, ok := getTupleID(pkt)\n- if !ok {\n- t.Fatal(\"failed to get original tuple ID\")\n+ originalTID, res := getTupleID(pkt)\n+ if res != getTupleIDOKAndAllowNewConn {\n+ t.Fatalf(\"got getTupleID(...) = (%#v, %d), want = (_, %d)\", originalTID, res, getTupleIDOKAndAllowNewConn)\n}\nif !iptables.CheckPrerouting(pkt, nil /* addressEP */, \"\" /* inNicName */) {\n@@ -137,9 +137,9 @@ func TestNATedConnectionReap(t *testing.T) {\nt.Fatal(\"got ipt.CheckInput(...) = false, want = true\")\n}\n- invertedReplyTID, _, ok := getTupleID(pkt)\n- if !ok {\n- t.Fatal(\"failed to get NATed packet's tuple ID\")\n+ invertedReplyTID, res := getTupleID(pkt)\n+ if res != getTupleIDOKAndAllowNewConn {\n+ t.Fatalf(\"got getTupleID(...) = (%#v, %d), want = (_, %d)\", invertedReplyTID, res, getTupleIDOKAndAllowNewConn)\n}\nif invertedReplyTID == originalTID {\nt.Fatalf(\"NAT not performed; got invertedReplyTID = %#v\", invertedReplyTID)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Explicitly allow new connections to be created
This change is to prepare for later changes which may determine if a
packet is sent in response to an original packet so that the reply
packet does not create a new connection.
PiperOrigin-RevId: 413501477 |
259,896 | 01.12.2021 13:57:43 | 28,800 | 8777a4f8c6912d0e6f953afe05a7c14ebdf00a3a | Increment spurious recovery metric only for RTO. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -273,6 +273,7 @@ var Metrics = tcpip.Stats{\nFailedPortReservations: mustCreateMetric(\"/netstack/tcp/failed_port_reservations\", \"Number of time TCP failed to reserve a port.\"),\nSegmentsAckedWithDSACK: mustCreateMetric(\"/netstack/tcp/segments_acked_with_dsack\", \"Number of segments for which DSACK was received.\"),\nSpuriousRecovery: mustCreateMetric(\"/netstack/tcp/spurious_recovery\", \"Number of times the connection entered loss recovery spuriously.\"),\n+ SpuriousRTORecovery: mustCreateMetric(\"/netstack/tcp/spurious_rto_recovery\", \"Number of times the connection entered RTO spuriously.\"),\n},\nUDP: tcpip.UDPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/udp/packets_received\", \"Number of UDP datagrams received via HandlePacket.\"),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -1870,6 +1870,9 @@ type TCPStats struct {\n// SpuriousRecovery is the number of times the connection entered loss\n// recovery spuriously.\nSpuriousRecovery *StatCounter\n+\n+ // SpuriousRTORecovery is the number of spurious RTOs.\n+ SpuriousRTORecovery *StatCounter\n}\n// UDPStats collects UDP-specific stats.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -1344,6 +1344,13 @@ func (s *sender) detectSpuriousRecovery(hasDSACK bool, tsEchoReply uint32) {\n// between fast, SACK or RTO recovery.\ns.spuriousRecovery = true\ns.ep.stack.Stats().TCP.SpuriousRecovery.Increment()\n+\n+ // RFC 3522 will detect all kinds of spurious recoveries (fast, SACK and\n+ // timeout). Increment the metric for RTO only as we want to track the\n+ // number of timeout recoveries.\n+ if s.state == tcpip.RTORecovery {\n+ s.ep.stack.Stats().TCP.SpuriousRTORecovery.Increment()\n+ }\n}\n// Check if the sender is in RTORecovery, FastRecovery or SACKRecovery state.\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": "@@ -704,7 +704,7 @@ func TestRecoveryEntry(t *testing.T) {\n}\n}\n-func verifySpuriousRecoveryMetric(t *testing.T, c *context.Context, numSpuriousRecovery uint64) {\n+func verifySpuriousRecoveryMetric(t *testing.T, c *context.Context, numSpuriousRecovery, numSpuriousRTO uint64) {\nt.Helper()\nmetricPollFn := func() error {\n@@ -715,6 +715,7 @@ func verifySpuriousRecoveryMetric(t *testing.T, c *context.Context, numSpuriousR\nwant uint64\n}{\n{tcpStats.SpuriousRecovery, \"stats.TCP.SpuriousRecovery\", numSpuriousRecovery},\n+ {tcpStats.SpuriousRTORecovery, \"stats.TCP.SpuriousRTORecovery\", numSpuriousRTO},\n}\nfor _, s := range stats {\nif got, want := s.stat.Value(), s.want; got != want {\n@@ -829,7 +830,7 @@ func TestDetectSpuriousRecoveryWithRTO(t *testing.T) {\n// ACK before the test completes.\n<-probeDone\n- verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */)\n+ verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */, 1 /* numSpuriousRTO */)\n}\nfunc TestSACKDetectSpuriousRecoveryWithDupACK(t *testing.T) {\n@@ -923,7 +924,7 @@ func TestSACKDetectSpuriousRecoveryWithDupACK(t *testing.T) {\n// ACK before the test completes.\n<-probeDone\n- verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */)\n+ verifySpuriousRecoveryMetric(t, c, 1 /* numSpuriousRecovery */, 0 /* numSpuriousRTO */)\n}\nfunc TestNoSpuriousRecoveryWithDSACK(t *testing.T) {\n@@ -955,5 +956,5 @@ func TestNoSpuriousRecoveryWithDSACK(t *testing.T) {\nseq = seqnum.Value(context.TestInitialSequenceNumber).Add(1)\nc.SendAckWithSACK(seq, 6*maxPayload, []header.SACKBlock{{start, end}})\n- verifySpuriousRecoveryMetric(t, c, 0 /* numSpuriousRecovery */)\n+ verifySpuriousRecoveryMetric(t, c, 0 /* numSpuriousRecovery */, 0 /* numSpuriousRTO */)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Increment spurious recovery metric only for RTO.
PiperOrigin-RevId: 413504208 |
260,004 | 01.12.2021 17:43:08 | 28,800 | 054229a46bb6f6f2e56fdec8d9a74a2d4fa62a2b | Extract NAT types
...to be shared across tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "@@ -1164,40 +1164,7 @@ func TestInputHookWithLocalForwarding(t *testing.T) {\n}\n}\n-func TestNAT(t *testing.T) {\n- const listenPort uint16 = 8080\n-\n- type endpointAndAddresses struct {\n- serverEP tcpip.Endpoint\n- serverAddr tcpip.FullAddress\n- serverReadableCH chan struct{}\n- serverConnectAddr tcpip.Address\n-\n- clientEP tcpip.Endpoint\n- clientAddr tcpip.Address\n- clientReadableCH chan struct{}\n- clientConnectAddr tcpip.FullAddress\n- }\n-\n- newEP := func(t *testing.T, s *stack.Stack, transProto tcpip.TransportProtocolNumber, netProto tcpip.NetworkProtocolNumber) (tcpip.Endpoint, chan struct{}) {\n- t.Helper()\n- var wq waiter.Queue\n- we, ch := waiter.NewChannelEntry(waiter.ReadableEvents)\n- wq.EventRegister(&we)\n- t.Cleanup(func() {\n- wq.EventUnregister(&we)\n- })\n-\n- ep, err := s.NewEndpoint(transProto, netProto, &wq)\n- if err != nil {\n- t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", transProto, netProto, err)\n- }\n- t.Cleanup(ep.Close)\n-\n- return ep, ch\n- }\n-\n- setupNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, hook stack.Hook, filter stack.IPHeaderFilter, target stack.Target) {\n+func setupNAT(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, hook stack.Hook, filter stack.IPHeaderFilter, target stack.Target) {\nt.Helper()\nipv6 := netProto == ipv6.ProtocolNumber\n@@ -1213,7 +1180,7 @@ func TestNAT(t *testing.T) {\n}\n}\n- setupDNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\n+func setupDNAT(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\nt.Helper()\nsetupNAT(\n@@ -1229,7 +1196,7 @@ func TestNAT(t *testing.T) {\ntarget)\n}\n- setupSNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\n+func setupSNAT(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, target stack.Target) {\nt.Helper()\nsetupNAT(\n@@ -1245,49 +1212,7 @@ func TestNAT(t *testing.T) {\ntarget)\n}\n- type natType struct {\n- name string\n- setupNAT func(_ *testing.T, _ *stack.Stack, _ tcpip.NetworkProtocolNumber, _ tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address)\n- }\n-\n- snatTypes := []natType{\n- {\n- name: \"SNAT\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, _ tcpip.Address) {\n- t.Helper()\n-\n- setupSNAT(t, s, netProto, transProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n- },\n- },\n- {\n- name: \"Masquerade\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address) {\n- t.Helper()\n-\n- setupSNAT(t, s, netProto, transProto, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n- },\n- },\n- }\n- dnatTypes := []natType{\n- {\n- name: \"Redirect\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address) {\n- t.Helper()\n-\n- setupDNAT(t, s, netProto, transProto, &stack.RedirectTarget{NetworkProtocol: netProto, Port: listenPort})\n- },\n- },\n- {\n- name: \"DNAT\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, dnatAddr tcpip.Address) {\n- t.Helper()\n-\n- setupDNAT(t, s, netProto, transProto, &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: listenPort})\n- },\n- },\n- }\n-\n- setupTwiceNAT := func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, dnatAddr tcpip.Address, snatTarget stack.Target) {\n+func setupTwiceNAT(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, dnatAddr tcpip.Address, dnatTarget, snatTarget stack.Target) {\nt.Helper()\nipv6 := netProto == ipv6.ProtocolNumber\n@@ -1302,7 +1227,7 @@ func TestNAT(t *testing.T) {\nCheckProtocol: true,\nInputInterface: utils.RouterNIC2Name,\n},\n- Target: &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: listenPort},\n+ Target: dnatTarget,\n},\n{\nTarget: &stack.AcceptTarget{},\n@@ -1349,24 +1274,103 @@ func TestNAT(t *testing.T) {\nt.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, ipv6, err)\n}\n}\n- twiceNATTypes := []natType{\n+\n+type natType struct {\n+ name string\n+ setupNAT func(_ *testing.T, _ *stack.Stack, _ tcpip.NetworkProtocolNumber, _ tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address, dnatPort uint16)\n+}\n+\n+var (\n+ snatTypes = []natType{\n+ {\n+ name: \"SNAT\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, _ tcpip.Address, _ uint16) {\n+ t.Helper()\n+\n+ setupSNAT(t, s, netProto, transProto, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n+ },\n+ },\n+ {\n+ name: \"Masquerade\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address, _ uint16) {\n+ t.Helper()\n+\n+ setupSNAT(t, s, netProto, transProto, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n+ },\n+ },\n+ }\n+\n+ dnatTypes = []natType{\n+ {\n+ name: \"Redirect\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, _ tcpip.Address, dnatPort uint16) {\n+ t.Helper()\n+\n+ setupDNAT(t, s, netProto, transProto, &stack.RedirectTarget{NetworkProtocol: netProto, Port: dnatPort})\n+ },\n+ },\n+ {\n+ name: \"DNAT\",\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, _, dnatAddr tcpip.Address, dnatPort uint16) {\n+ t.Helper()\n+\n+ setupDNAT(t, s, netProto, transProto, &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: dnatPort})\n+ },\n+ },\n+ }\n+\n+ twiceNATTypes = []natType{\n{\nname: \"DNAT-Masquerade\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address) {\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address, dnatPort uint16) {\nt.Helper()\n- setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n+ setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: dnatPort}, &stack.MasqueradeTarget{NetworkProtocol: netProto})\n},\n},\n{\nname: \"DNAT-SNAT\",\n- setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address) {\n+ setupNAT: func(t *testing.T, s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, snatAddr, dnatAddr tcpip.Address, dnatPort uint16) {\nt.Helper()\n- setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n+ setupTwiceNAT(t, s, netProto, transProto, dnatAddr, &stack.DNATTarget{NetworkProtocol: netProto, Addr: dnatAddr, Port: dnatPort}, &stack.SNATTarget{NetworkProtocol: netProto, Addr: snatAddr})\n},\n},\n}\n+)\n+\n+func TestNAT(t *testing.T) {\n+ const listenPort uint16 = 8080\n+\n+ type endpointAndAddresses struct {\n+ serverEP tcpip.Endpoint\n+ serverAddr tcpip.FullAddress\n+ serverReadableCH chan struct{}\n+ serverConnectAddr tcpip.Address\n+\n+ clientEP tcpip.Endpoint\n+ clientAddr tcpip.Address\n+ clientReadableCH chan struct{}\n+ clientConnectAddr tcpip.FullAddress\n+ }\n+\n+ newEP := func(t *testing.T, s *stack.Stack, transProto tcpip.TransportProtocolNumber, netProto tcpip.NetworkProtocolNumber) (tcpip.Endpoint, chan struct{}) {\n+ t.Helper()\n+ var wq waiter.Queue\n+ we, ch := waiter.NewChannelEntry(waiter.ReadableEvents)\n+ wq.EventRegister(&we)\n+ t.Cleanup(func() {\n+ wq.EventUnregister(&we)\n+ })\n+\n+ ep, err := s.NewEndpoint(transProto, netProto, &wq)\n+ if err != nil {\n+ t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", transProto, netProto, err)\n+ }\n+ t.Cleanup(ep.Close)\n+\n+ return ep, ch\n+ }\ntests := []struct {\nname string\n@@ -1673,7 +1677,7 @@ func TestNAT(t *testing.T) {\nutils.SetupRoutedStacks(t, host1Stack, routerStack, host2Stack)\nepsAndAddrs := test.epAndAddrs(t, host1Stack, routerStack, host2Stack, subTest.proto)\n- natType.setupNAT(t, routerStack, test.netProto, subTest.proto, epsAndAddrs.serverConnectAddr, epsAndAddrs.serverAddr.Addr)\n+ natType.setupNAT(t, routerStack, test.netProto, subTest.proto, epsAndAddrs.serverConnectAddr, epsAndAddrs.serverAddr.Addr, listenPort)\nif err := epsAndAddrs.serverEP.Bind(epsAndAddrs.serverAddr); err != nil {\nt.Fatalf(\"epsAndAddrs.serverEP.Bind(%#v): %s\", epsAndAddrs.serverAddr, err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Extract NAT types
...to be shared across tests.
PiperOrigin-RevId: 413552100 |
259,853 | 01.12.2021 17:53:47 | 28,800 | b2f8b495ad73edb34d47154eba9535a14bd32d61 | cgroup/cpuset: handle the offset argument of write methods properly
offset is an offset in a file, so here is no sense to
drop first "offset" number of bytes from a buffer.
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -234,11 +234,10 @@ func (d *tasksData) Write(ctx context.Context, src usermem.IOSequence, offset in\n// parseInt64FromString interprets src as string encoding a int64 value, and\n// returns the parsed value.\n-func parseInt64FromString(ctx context.Context, src usermem.IOSequence, offset int64) (val, len int64, err error) {\n+func parseInt64FromString(ctx context.Context, src usermem.IOSequence) (val, len int64, err error) {\nconst maxInt64StrLen = 20 // i.e. len(fmt.Sprintf(\"%d\", math.MinInt64)) == 20\nt := kernel.TaskFromContext(ctx)\n- src = src.DropFirst64(offset)\nbuf := t.CopyScratchBuffer(maxInt64StrLen)\nn, err := src.CopyIn(ctx, buf)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cpuset.go",
"diff": "@@ -82,7 +82,6 @@ func (d *cpusData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Write implements vfs.WritableDynamicBytesSource.Write.\nfunc (d *cpusData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n- src = src.DropFirst64(offset)\nif src.NumBytes() > hostarch.PageSize {\nreturn 0, linuxerr.EINVAL\n}\n@@ -127,7 +126,6 @@ func (d *memsData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Write implements vfs.WritableDynamicBytesSource.Write.\nfunc (d *memsData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n- src = src.DropFirst64(offset)\nif src.NumBytes() > hostarch.PageSize {\nreturn 0, linuxerr.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/job.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/job.go",
"diff": "@@ -55,7 +55,7 @@ func (d *jobIDData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Write implements vfs.WritableDynamicBytesSource.Write.\nfunc (d *jobIDData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n- val, n, err := parseInt64FromString(ctx, src, offset)\n+ val, n, err := parseInt64FromString(ctx, src)\nif err != nil {\nreturn n, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | cgroup/cpuset: handle the offset argument of write methods properly
offset is an offset in a file, so here is no sense to
drop first "offset" number of bytes from a buffer.
Reported-by: [email protected]
PiperOrigin-RevId: 413553935 |
259,898 | 02.12.2021 14:32:09 | 28,800 | 40355372f94dad60248767e2c09a199dacf1265a | Allow DUT binaries to define their own flags
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/BUILD",
"new_path": "test/packetimpact/dut/BUILD",
"diff": "@@ -33,6 +33,10 @@ go_library(\nname = \"dut\",\ntestonly = True,\nsrcs = [\"dut.go\"],\n+ visibility = [\n+ \"//test/packetimpact:__subpackages__\",\n+ \"//turquoise/connectivity/netstack/gvisor_tests/packetimpact:__subpackages__\",\n+ ],\ndeps = [\n\"//test/packetimpact/testbench\",\n\"@org_golang_x_sync//errgroup:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/dut.go",
"new_path": "test/packetimpact/dut/dut.go",
"diff": "@@ -39,6 +39,10 @@ const (\ncompleteFd = 3\n// PosixServerPort is the port the posix server should listen on.\nPosixServerPort = 54321\n+ // CtrlIface is the command switch name for passing name of the control interface.\n+ CtrlIface = \"ctrl_iface\"\n+ // TestIface is the command switch name for passing name of the test interface.\n+ TestIface = \"test_iface\"\n)\n// Ifaces describe the names of the interfaces on DUT.\n@@ -51,18 +55,15 @@ type Ifaces struct {\n// Init puts the current process into the target network namespace, the user of\n// this library should call this function in the beginning.\n-func Init() (Ifaces, error) {\n+func Init(fs *flag.FlagSet) (Ifaces, error) {\n// The DUT might create child processes, we don't want this fd to leak into\n// those processes as it keeps the pipe open and the testbench will hang\n// waiting for an EOF on the pipe.\nunix.CloseOnExec(completeFd)\nvar ifaces Ifaces\n- // Parse command line flags. It is effectively the same as using top-level\n- // functions in flag package, but more explicit that we exit if the parsing\n- // failed.\n- fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\n- fs.StringVar(&ifaces.Ctrl, \"ctrl_iface\", \"\", \"the name of the control interface\")\n- fs.StringVar(&ifaces.Test, \"test_iface\", \"\", \"the name of the test interface\")\n+ // Parse command line flags that is defined by the caller and us.\n+ fs.StringVar(&ifaces.Ctrl, CtrlIface, \"\", \"the name of the control interface\")\n+ fs.StringVar(&ifaces.Test, TestIface, \"\", \"the name of the test interface\")\nif err := fs.Parse(os.Args[1:]); err != nil {\nreturn Ifaces{}, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/native/main.go",
"new_path": "test/packetimpact/dut/native/main.go",
"diff": "@@ -20,6 +20,7 @@ package main\nimport (\n\"context\"\n+ \"flag\"\n\"fmt\"\n\"log\"\n\"os\"\n@@ -40,7 +41,7 @@ type native struct {\n}\nfunc main() {\n- ifaces, err := dut.Init()\n+ ifaces, err := dut.Init(flag.CommandLine)\nif err != nil {\nlog.Fatal(err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/runsc/main.go",
"new_path": "test/packetimpact/dut/runsc/main.go",
"diff": "@@ -20,6 +20,7 @@ package main\nimport (\n\"context\"\n+ \"flag\"\n\"fmt\"\n\"log\"\n\"os\"\n@@ -49,7 +50,7 @@ type runsc struct {\nvar _ dut.DUT = (*runsc)(nil)\nfunc main() {\n- ifaces, err := dut.Init()\n+ ifaces, err := dut.Init(flag.CommandLine)\nif err != nil {\nlog.Fatal(err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/internal/testing/BUILD",
"new_path": "test/packetimpact/internal/testing/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\")\npackage(\n- default_visibility = [\"//test/packetimpact:__subpackages__\"],\nlicenses = [\"notice\"],\n)\n@@ -9,4 +8,8 @@ go_library(\nname = \"testing\",\ntestonly = True,\nsrcs = [\"testing.go\"],\n+ visibility = [\n+ \"//test/packetimpact:__subpackages__\",\n+ \"//turquoise/connectivity/netstack/gvisor_tests/packetimpact:__subpackages__\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/BUILD",
"new_path": "test/packetimpact/runner/BUILD",
"diff": "@@ -41,7 +41,12 @@ go_binary(\nname = \"main\",\ntestonly = True,\nsrcs = [\"main.go\"],\n+ visibility = [\n+ \"//test/packetimpact:__subpackages__\",\n+ \"//turquoise/connectivity/netstack/gvisor_tests/packetimpact:__subpackages__\",\n+ ],\ndeps = [\n+ \"//test/packetimpact/dut\",\n\"//test/packetimpact/internal/testing\",\n\"//test/packetimpact/netdevs/netlink\",\n\"//test/packetimpact/testbench\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/main.go",
"new_path": "test/packetimpact/runner/main.go",
"diff": "@@ -30,6 +30,7 @@ import (\n\"os/exec\"\n\"path/filepath\"\n\"runtime\"\n+ \"strings\"\n\"syscall\"\n\"github.com/google/gopacket\"\n@@ -38,11 +39,25 @@ import (\n\"github.com/vishvananda/netlink\"\n\"golang.org/x/sync/errgroup\"\n\"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/test/packetimpact/dut\"\n\"gvisor.dev/gvisor/test/packetimpact/internal/testing\"\nnetdevs \"gvisor.dev/gvisor/test/packetimpact/netdevs/netlink\"\n\"gvisor.dev/gvisor/test/packetimpact/testbench\"\n)\n+type dutArgList []string\n+\n+// String implements flag.Value.\n+func (l *dutArgList) String() string {\n+ return strings.Join(*l, \" \")\n+}\n+\n+// Set implements flag.Value.\n+func (l *dutArgList) Set(value string) error {\n+ *l = append(*l, value)\n+ return nil\n+}\n+\nfunc main() {\nconst procSelfExe = \"/proc/self/exe\"\nif os.Args[0] != procSelfExe {\n@@ -88,6 +103,7 @@ func main() {\nruntime string\npartition int\ntotalPartitions int\n+ dutArgs dutArgList\n)\nfs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\nfs.StringVar(&dutBinary, \"dut_binary\", \"\", \"path to the DUT binary\")\n@@ -95,6 +111,7 @@ func main() {\nfs.BoolVar(&expectFailure, \"expect_failure\", false, \"whether the test is expected to fail\")\nfs.IntVar(&numDUTs, \"num_duts\", 1, \"number of DUTs to create\")\nfs.StringVar(&variant, \"variant\", \"\", \"test variant could be native, gvisor or fuchsia\")\n+ fs.Var(&dutArgs, \"dut_arg\", \"argument to the DUT binary\")\n// The following args are passed by CI environment which are not used by us.\nfs.StringVar(&runtime, \"runtime\", \"\", \"docker runtime to use (unused)\")\nfs.IntVar(&partition, \"partition\", 1, \"1-indexed partition (unused)\")\n@@ -107,9 +124,9 @@ func main() {\n// Create all the DUTs.\ninfoCh := make(chan testbench.DUTInfo, numDUTs)\n- var duts []*dut\n+ var duts []*dutProcess\nfor i := 0; i < numDUTs; i++ {\n- d, err := newDUT(ctx, i, dutBinary)\n+ d, err := newDUT(ctx, i, dutBinary, dutArgs)\nif err != nil {\nlog.Fatal(err)\n}\n@@ -194,15 +211,18 @@ func main() {\n}\n}\n-type dut struct {\n+type dutProcess struct {\ncmd *exec.Cmd\nid int\ncompleteR *os.File\ndutNetNS netNS\n}\n-func newDUT(ctx context.Context, id int, dutBinary string) (*dut, error) {\n- cmd := exec.CommandContext(ctx, dutBinary, \"--ctrl_iface\", dutSide.ifaceName(ctrlLink, id), \"--test_iface\", dutSide.ifaceName(testLink, id))\n+func newDUT(ctx context.Context, id int, dutBinary string, dutArgs dutArgList) (*dutProcess, error) {\n+ cmd := exec.CommandContext(ctx, dutBinary, append([]string{\n+ \"--\" + dut.CtrlIface, dutSide.ifaceName(ctrlLink, id),\n+ \"--\" + dut.TestIface, dutSide.ifaceName(testLink, id),\n+ }, dutArgs...)...)\n// Create the pipe for completion signal\ncompleteR, completeW, err := os.Pipe()\n@@ -297,10 +317,10 @@ func newDUT(ctx context.Context, id int, dutBinary string) (*dut, error) {\n}\n}\n- return &dut{cmd: cmd, id: id, completeR: completeR, dutNetNS: dutNetNS}, nil\n+ return &dutProcess{cmd: cmd, id: id, completeR: completeR, dutNetNS: dutNetNS}, nil\n}\n-func (d *dut) bootstrap(ctx context.Context) (testbench.DUTInfo, func() error, error) {\n+func (d *dutProcess) bootstrap(ctx context.Context) (testbench.DUTInfo, func() error, error) {\nif err := d.dutNetNS.Do(func() error {\nreturn d.cmd.Start()\n}); err != nil {\n@@ -335,16 +355,16 @@ func (d *dut) bootstrap(ctx context.Context) (testbench.DUTInfo, func() error, e\nreturn dutInfo, d.cmd.Wait, nil\n}\n-func (d *dut) name() string {\n+func (d *dutProcess) name() string {\nreturn fmt.Sprintf(\"dut-%d\", d.id)\n}\n-func (d *dut) peerIface() string {\n+func (d *dutProcess) peerIface() string {\nreturn tbSide.ifaceName(testLink, d.id)\n}\n// writePcap creates the packet capture while the test is running.\n-func (d *dut) writePcap(ctx context.Context, testName string) error {\n+func (d *dutProcess) writePcap(ctx context.Context, testName string) error {\niface := d.peerIface()\n// Create the pcap file.\nfileName, err := testing.UndeclaredOutput(fmt.Sprintf(\"%s_%s.pcap\", testName, iface))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow DUT binaries to define their own flags
Updates #6835
PiperOrigin-RevId: 413772074 |
259,975 | 02.12.2021 23:56:25 | 28,800 | 74536aba2cf9ee885df5be2a763921439391e10e | [benchmarks] Don't run vfs1 benchmarks anymore. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -394,7 +394,6 @@ benchmark-platforms: load-benchmarks $(RUNTIME_BIN) ## Runs benchmarks for runc\n@set -xe; for PLATFORM in $$($(RUNTIME_BIN) help platforms); do \\\nexport PLATFORM; \\\n$(call run_benchmark,$${PLATFORM},--platform=$${PLATFORM} $(BENCH_RUNTIME_ARGS) --vfs2); \\\n- $(call run_benchmark,$${PLATFORM}_vfs1,--platform=$${PLATFORM} $(BENCH_RUNTIME_ARGS)); \\\ndone\n@$(call run_benchmark,runc)\n.PHONY: benchmark-platforms\n"
}
] | Go | Apache License 2.0 | google/gvisor | [benchmarks] Don't run vfs1 benchmarks anymore.
PiperOrigin-RevId: 413860206 |
259,898 | 03.12.2021 08:28:37 | 28,800 | 791b9428a6de0b2b41806ff1f7ea6bdc6716ed15 | Use net.InterfaceByName to retrieve runsc DUT's device ID. | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/runsc/BUILD",
"new_path": "test/packetimpact/dut/runsc/BUILD",
"diff": "@@ -29,5 +29,4 @@ go_binary(\nname = \"devid\",\ntestonly = True,\nsrcs = [\"devid.go\"],\n- deps = [\"@com_github_vishvananda_netlink//:go_default_library\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/runsc/devid.go",
"new_path": "test/packetimpact/dut/runsc/devid.go",
"diff": "@@ -21,15 +21,14 @@ package main\nimport (\n\"fmt\"\n\"log\"\n+ \"net\"\n\"os\"\n-\n- \"github.com/vishvananda/netlink\"\n)\nfunc main() {\n- link, err := netlink.LinkByName(os.Args[1])\n+ iface, err := net.InterfaceByName(os.Args[1])\nif err != nil {\n- log.Fatalf(\"could not find the link: %s\", err)\n+ log.Fatalf(\"could not find link %s: %s\", os.Args[1], err)\n}\n- fmt.Printf(\"%d\", link.Attrs().Index)\n+ fmt.Printf(\"%d\", iface.Index)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use net.InterfaceByName to retrieve runsc DUT's device ID.
PiperOrigin-RevId: 413941742 |
259,898 | 03.12.2021 18:24:53 | 28,800 | 969fb6fb8469618adf6888c9319300ff64b02ae8 | Update expectations for generic_dgram_socket_send_recv_test
prepare for removing the docker packetimpact runner entirely
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/runner/defs.bzl",
"new_path": "test/packetimpact/runner/defs.bzl",
"diff": "@@ -334,10 +334,6 @@ ALL_TESTS = [\nPacketimpactTestInfo(\nname = \"generic_dgram_socket_send_recv\",\ntimeout = \"long\",\n- # This test has assumed the presense of the default interface and the\n- # default route installed by docker, using the docker until the test\n- # is migrated.\n- legacy_runner = True,\n),\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/generic_dgram_socket_send_recv_test.go",
"new_path": "test/packetimpact/tests/generic_dgram_socket_send_recv_test.go",
"diff": "@@ -203,19 +203,33 @@ func (test *icmpV4Test) Send(t *testing.T, dut testbench.DUT, bindTo, sendTo net\nt.Skip(\"TODO(gvisor.dev/issue/5681): Allow sending to broadcast and multicast addresses with ICMP sockets.\")\n}\n- expectPacket := isV4 && !sendTo.Equal(dut.Net.RemoteIPv4)\n- switch {\n- case bindTo.Equal(dut.Net.RemoteIPv4):\n- // If we're explicitly bound to an interface's unicast address,\n- // packets are always sent on that interface.\n- case bindToDevice:\n- // If we're explicitly bound to an interface, packets are always\n- // sent on that interface.\n- case !sendTo.Equal(net.IPv4bcast) && !sendTo.IsMulticast():\n- // If we're not sending to limited broadcast or multicast, the route\n- // table will be consulted and packets will be sent on the correct\n- // interface.\n- default:\n+ expectNetworkUnreachable := true\n+ // We don't expect ENETUNREACH if any of the follwing is true:\n+ // 1. bindTo is specfied.\n+ if !bindTo.Equal(net.IPv4zero) {\n+ expectNetworkUnreachable = false\n+ }\n+ // 2. We are binding to a device.\n+ if bindToDevice {\n+ expectNetworkUnreachable = false\n+ }\n+ // 3. sendTo is neither 224.0.0.1 nor 255.255.255.255.\n+ if !sendTo.Equal(net.IPv4bcast) && !sendTo.Equal(net.IPv4allsys) {\n+ expectNetworkUnreachable = false\n+ }\n+\n+ expectPacket := true\n+ // We don't expect an incoming packet if any of the following is true:\n+ // 1. sendTo is not an ipv4 address.\n+ if !isV4 {\n+ expectPacket = false\n+ }\n+ // 2. sendTo is the dut itself.\n+ if sendTo.Equal(dut.Net.RemoteIPv4) {\n+ expectPacket = false\n+ }\n+ // 3. we are expecting ENETUNREACH.\n+ if expectNetworkUnreachable {\nexpectPacket = false\n}\n@@ -239,8 +253,15 @@ func (test *icmpV4Test) Send(t *testing.T, dut testbench.DUT, bindTo, sendTo net\ncopy(destSockaddr.Addr[:], sendTo.To4())\n// Tell the DUT to send a packet out the ICMP socket.\n- if got, want := dut.SendTo(t, env.socketFD, bytes, 0, &destSockaddr), len(bytes); int(got) != want {\n- t.Fatalf(\"got dut.SendTo = %d, want %d\", got, want)\n+ ret, err := dut.SendToWithErrno(context.Background(), t, env.socketFD, bytes, 0, &destSockaddr)\n+ if expectNetworkUnreachable {\n+ if !(ret == -1 && err == unix.ENETUNREACH) {\n+ t.Fatalf(\"got dut.SendToWithErrno = (%d, %s), want (-1, %s)\", ret, err, unix.ENETUNREACH)\n+ }\n+ } else {\n+ if !(int(ret) == len(bytes) && err == unix.Errno(0)) {\n+ t.Fatalf(\"got dut.SendToWithErrno = (%d, %s), want (%d, 0)\", ret, err, len(bytes))\n+ }\n}\n// Verify the test runner received an ICMP packet with the correctly\n@@ -401,18 +422,16 @@ func (test *icmpV6Test) Send(t *testing.T, dut testbench.DUT, bindTo, sendTo net\nif sendTo.To4() != nil {\nwantErrno = unix.EINVAL\n- }\n// TODO(gvisor.dev/issue/5966): Remove this if statement once ICMPv6 sockets\n// return EINVAL after calling sendto with an IPv4 address.\n- if (dut.Uname.IsGvisor() || dut.Uname.IsFuchsia()) && sendTo.To4() != nil {\n- switch {\n- case bindTo.Equal(dut.Net.RemoteIPv6):\n+ if dut.Uname.IsGvisor() || dut.Uname.IsFuchsia() {\nwantErrno = unix.ENETUNREACH\n- case bindTo.Equal(net.IPv6zero) || bindTo == nil:\n+ if !bindTo.Equal(dut.Net.RemoteIPv6) && (bindToDevice || isInTestSubnetV4(dut, sendTo)) {\nwantErrno = unix.Errno(0)\n}\n}\n+ }\nenv := test.setup(t, dut, bindTo, sendTo, bindToDevice)\n@@ -618,36 +637,44 @@ var _ protocolTest = (*udpTest)(nil)\nfunc (*udpTest) Name() string { return \"udp\" }\nfunc (test *udpTest) Send(t *testing.T, dut testbench.DUT, bindTo, sendTo net.IP, bindToDevice bool) {\n- canSend := bindTo == nil || bindTo.Equal(net.IPv6zero) || sameIPVersion(sendTo, bindTo)\n- expectPacket := canSend && !isRemoteAddr(dut, sendTo)\n- switch {\n- case bindTo.Equal(dut.Net.RemoteIPv4):\n- // If we're explicitly bound to an interface's unicast address,\n- // packets are always sent on that interface.\n- case bindToDevice:\n- // If we're explicitly bound to an interface, packets are always\n- // sent on that interface.\n- case !sendTo.Equal(net.IPv4bcast) && !sendTo.IsMulticast():\n- // If we're not sending to limited broadcast, multicast, or local, the\n- // route table will be consulted and packets will be sent on the correct\n- // interface.\n- default:\n- expectPacket = false\n- }\n-\nwantErrno := unix.Errno(0)\n- switch {\n- case !canSend && bindTo.To4() != nil:\n+\n+ if sendTo.To4() == nil {\n+ // If sendTo is an IPv6 address.\n+ if bindTo.To4() != nil {\n+ // But bindTo is an IPv4 address, we expect EAFNOSUPPORT.\nwantErrno = unix.EAFNOSUPPORT\n- case !canSend && bindTo.To4() == nil:\n- wantErrno = unix.ENETUNREACH\n- }\n// TODO(gvisor.dev/issue/5967): Remove this if statement once UDPv4 sockets\n// returns EAFNOSUPPORT after calling sendto with an IPv6 address.\n- if dut.Uname.IsGvisor() && !canSend && bindTo.To4() != nil {\n+ if dut.Uname.IsGvisor() {\nwantErrno = unix.EINVAL\n}\n+ }\n+ } else {\n+ // If sendTo is an IPv4 address.\n+ if bindTo.Equal(dut.Net.RemoteIPv6) {\n+ // if bindTo is dut's IPv6 address, we expect ENETUNREACH.\n+ wantErrno = unix.ENETUNREACH\n+ }\n+\n+ if !bindToDevice && !bindTo.Equal(dut.Net.RemoteIPv4) && (sendTo.Equal(net.IPv4bcast) || sendTo.Equal(net.IPv4allsys)) {\n+ // if not binding to a device, bindTo is not dut's IPv4 addression and sendTo is\n+ // 255.255.255.255 or 224.0.0.1, we expect ENETUNERACH.\n+ wantErrno = unix.ENETUNREACH\n+ }\n+ }\n+\n+ expectPacket := true\n+ // We don't expect an incoming packet if:\n+ // 1. sendTo is dut itself.\n+ if isRemoteAddr(dut, sendTo) {\n+ expectPacket = false\n+ }\n+ // 2. we expect an error when sending the packet.\n+ if wantErrno != unix.Errno(0) {\n+ expectPacket = false\n+ }\nenv := test.setup(t, dut, bindTo, sendTo, bindToDevice)\n@@ -779,3 +806,11 @@ func sameIPVersion(a, b net.IP) bool {\nfunc isRemoteAddr(dut testbench.DUT, ip net.IP) bool {\nreturn ip.Equal(dut.Net.RemoteIPv4) || ip.Equal(dut.Net.RemoteIPv6)\n}\n+\n+func isInTestSubnetV4(dut testbench.DUT, ip net.IP) bool {\n+ network := net.IPNet{\n+ IP: dut.Net.LocalIPv4,\n+ Mask: net.CIDRMask(dut.Net.IPv4PrefixLength, net.IPv4len*8),\n+ }\n+ return network.Contains(ip)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update expectations for generic_dgram_socket_send_recv_test
prepare for removing the docker packetimpact runner entirely
Updates #6835
PiperOrigin-RevId: 414065450 |
259,858 | 06.12.2021 10:09:28 | 28,800 | 3f2ffc9f0c62c9e41e2b58519d472da9c9a5ccb2 | Allow reading for mixed atomic semantics.
This relaxes constraints on mixed atomic / lock protected fields. We
explicitly allow reads in this case, since this should be safe. | [
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/analysis.go",
"new_path": "tools/checklocks/analysis.go",
"diff": "@@ -83,21 +83,24 @@ func (pc *passContext) checkTypeAlignment(pkg *types.Package, typ *types.Named)\n_ = pc.typeAlignment(pkg, typ.Obj())\n}\n+// atomicRules specify read constraints.\n+type atomicRules int\n+\n+const (\n+ nonAtomic atomicRules = iota\n+ readWriteAtomic\n+ readOnlyAtomic\n+ mixedAtomic\n+)\n+\n// checkAtomicCall checks for an atomic access.\n//\n// inst is the instruction analyzed, obj is used only for maybeFail.\n-//\n-// If mustBeAtomic is true, then we assert that the instruction *is* an atomic\n-// fucnction call. If it is false, then we assert that it is *not* an atomic\n-// dispatch.\n-//\n-// If readOnly is true, then only atomic read access are allowed. Note that\n-// readOnly is only meaningful if mustBeAtomic is set.\n-func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, mustBeAtomic, readOnly bool) {\n+func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, ar atomicRules) {\nswitch x := inst.(type) {\ncase *ssa.Call:\nif x.Common().IsInvoke() {\n- if mustBeAtomic {\n+ if ar != nonAtomic {\n// This is an illegal interface dispatch.\npc.maybeFail(inst.Pos(), \"dynamic dispatch with atomic-only field\")\n}\n@@ -105,7 +108,7 @@ func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, m\n}\nfn, ok := x.Common().Value.(*ssa.Function)\nif !ok {\n- if mustBeAtomic {\n+ if ar != nonAtomic {\n// This is an illegal call to a non-static function.\npc.maybeFail(inst.Pos(), \"dispatch to non-static function with atomic-only field\")\n}\n@@ -113,7 +116,7 @@ func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, m\n}\npkg := fn.Package()\nif pkg == nil {\n- if mustBeAtomic {\n+ if ar != nonAtomic {\n// This is a call to some shared wrapper function.\npc.maybeFail(inst.Pos(), \"dispatch to shared function or wrapper\")\n}\n@@ -124,27 +127,39 @@ func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, m\nreturn\n}\nif name := pkg.Pkg.Name(); name != \"atomic\" && name != \"atomicbitops\" {\n- if mustBeAtomic {\n+ if ar != nonAtomic {\n// This is an illegal call to a non-atomic package function.\npc.maybeFail(inst.Pos(), \"dispatch to non-atomic function with atomic-only field\")\n}\nreturn\n}\n- if !mustBeAtomic {\n+ if ar == nonAtomic {\n// We are *not* expecting an atomic dispatch.\nif _, ok := pc.forced[pc.positionKey(inst.Pos())]; !ok {\npc.maybeFail(inst.Pos(), \"unexpected call to atomic function\")\n}\n}\n- if !strings.HasPrefix(fn.Name(), \"Load\") && readOnly {\n+ if !strings.HasPrefix(fn.Name(), \"Load\") && ar == readOnlyAtomic {\n// We are not allowing any reads in this context.\nif _, ok := pc.forced[pc.positionKey(inst.Pos())]; !ok {\npc.maybeFail(inst.Pos(), \"unexpected call to atomic write function, is a lock missing?\")\n}\nreturn\n}\n- default:\n- if mustBeAtomic {\n+ return // Don't hit common case.\n+ case *ssa.ChangeType:\n+ // Allow casts for atomic values, but nothing else.\n+ if refs := x.Referrers(); refs != nil && len(*refs) == 1 {\n+ pc.checkAtomicCall((*refs)[0], obj, ar)\n+ return\n+ }\n+ case *ssa.UnOp:\n+ if x.Op == token.MUL && ar == mixedAtomic {\n+ // This is allowed; this is a strict reading.\n+ return\n+ }\n+ }\n+ if ar != nonAtomic {\n// This is something else entirely.\nif _, ok := pc.forced[pc.positionKey(inst.Pos())]; !ok {\npc.maybeFail(inst.Pos(), \"illegal use of atomic-only field by %T instruction\", inst)\n@@ -152,7 +167,6 @@ func (pc *passContext) checkAtomicCall(inst ssa.Instruction, obj types.Object, m\nreturn\n}\n}\n-}\nfunc resolveStruct(typ types.Type) (*types.Struct, bool) {\nstructType, ok := typ.Underlying().(*types.Struct)\n@@ -235,10 +249,17 @@ func (pc *passContext) checkGuards(inst almostInst, from ssa.Value, accessObj ty\nswitch lgf.AtomicDisposition {\ncase atomicRequired:\n// Check that this is used safely as an input.\n- readOnly := len(guardsHeld) < guardsFound\n+ ar := readWriteAtomic\n+ if guardsFound > 0 {\n+ if len(guardsHeld) < guardsFound {\n+ ar = readOnlyAtomic\n+ } else {\n+ ar = mixedAtomic\n+ }\n+ }\nif refs := inst.Referrers(); refs != nil {\nfor _, otherInst := range *refs {\n- pc.checkAtomicCall(otherInst, accessObj, true, readOnly)\n+ pc.checkAtomicCall(otherInst, accessObj, ar)\n}\n}\n// Check that this is not otherwise written non-atomically,\n@@ -250,7 +271,7 @@ func (pc *passContext) checkGuards(inst almostInst, from ssa.Value, accessObj ty\n// Check that this is *not* used atomically.\nif refs := inst.Referrers(); refs != nil {\nfor _, otherInst := range *refs {\n- pc.checkAtomicCall(otherInst, accessObj, false, false)\n+ pc.checkAtomicCall(otherInst, accessObj, nonAtomic)\n}\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow reading for mixed atomic semantics.
This relaxes constraints on mixed atomic / lock protected fields. We
explicitly allow reads in this case, since this should be safe.
PiperOrigin-RevId: 414476414 |
259,907 | 06.12.2021 10:33:02 | 28,800 | d62190f8b521fa1b4cc7fc26b24b3f821f198bf7 | Fix lisafs bug which tramples dentry UID on remote revalidation. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -1173,7 +1173,7 @@ func (d *dentry) updateFromLisaStatLocked(stat *linux.Statx) {\natomic.StoreUint32(&d.uid, dentryUIDFromLisaUID(lisafs.UID(stat.UID)))\n}\nif stat.Mask&linux.STATX_GID != 0 {\n- atomic.StoreUint32(&d.uid, dentryGIDFromLisaGID(lisafs.GID(stat.GID)))\n+ atomic.StoreUint32(&d.gid, dentryGIDFromLisaGID(lisafs.GID(stat.GID)))\n}\nif stat.Blksize != 0 {\natomic.StoreUint32(&d.blockSize, stat.Blksize)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/lisafs.go",
"new_path": "runsc/fsgofer/lisafs.go",
"diff": "@@ -476,14 +476,12 @@ func (fd *controlFDLisa) OpenCreate(c *lisafs.Connection, comm lisafs.Communicat\n// Set the owners as requested by the client.\nif err := unix.Fchownat(childFD.hostFD, \"\", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {\n- log.Infof(\"ayush: Fchownat %v\", err)\nreturn err\n}\n// Do not use the stat result from tryOpen because the owners might have\n// changed. initInode() will stat the FD again and use fresh results.\nif err := childFD.initInode(&resp.Child); err != nil {\n- log.Infof(\"ayush: initInode %v\", err)\nreturn err\n}\n@@ -491,7 +489,6 @@ func (fd *controlFDLisa) OpenCreate(c *lisafs.Connection, comm lisafs.Communicat\nflags |= openFlags\nnewHostFD, err := unix.Openat(int(procSelfFD.FD()), strconv.Itoa(childFD.hostFD), int(flags)&^unix.O_NOFOLLOW, 0)\nif err != nil {\n- log.Infof(\"ayush: Openat %v\", err)\nreturn err\n}\ncu.Release()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix lisafs bug which tramples dentry UID on remote revalidation.
PiperOrigin-RevId: 414483232 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.