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,891
27.01.2020 12:27:04
28,800
29316e66adfc49c158425554761e34c12338f1d9
Cleanup for GH review.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -198,6 +198,8 @@ type XTEntryMatch struct {\n// SizeOfXTEntryMatch is the size of an XTEntryMatch.\nconst SizeOfXTEntryMatch = 32\n+// KernelXTEntryMatch is identical to XTEntryMatch, but contains\n+// variable-length Data field.\ntype KernelXTEntryMatch struct {\nXTEntryMatch\nData []byte\n@@ -349,19 +351,19 @@ func goString(cstring []byte) string {\n// XTUDP holds data for matching UDP packets. It corresponds to struct xt_udp\n// in include/uapi/linux/netfilter/xt_tcpudp.h.\ntype XTUDP struct {\n- // SourcePortStart specifies the inclusive start of the range of source\n- // ports to which the matcher applies.\n+ // SourcePortStart is the inclusive start of the range of source ports\n+ // to which the matcher applies.\nSourcePortStart uint16\n- // SourcePortEnd specifies the inclusive end of the range of source ports\n- // to which the matcher applies.\n+ // SourcePortEnd is the inclusive end of the range of source ports to\n+ // which the matcher applies.\nSourcePortEnd uint16\n- // DestinationPortStart specifies the start of the destination port\n+ // DestinationPortStart is the inclusive start of the destination port\n// range to which the matcher applies.\nDestinationPortStart uint16\n- // DestinationPortEnd specifies the start of the destination port\n+ // DestinationPortEnd is the inclusive end of the destination port\n// range to which the matcher applies.\nDestinationPortEnd uint16\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -34,9 +34,16 @@ import (\n// shouldn't be reached - an error has occurred if we fall through to one.\nconst errorTargetName = \"ERROR\"\n-// metadata is opaque to netstack. It holds data that we need to translate\n-// between Linux's and netstack's iptables representations.\n-// TODO(gvisor.dev/issue/170): Use metadata to check correctness.\n+const (\n+ matcherNameUDP = \"udp\"\n+)\n+\n+// Metadata is used to verify that we are correctly serializing and\n+// deserializing iptables into structs consumable by the iptables tool. We save\n+// a metadata struct when the tables are written, and when they are read out we\n+// verify that certain fields are the same.\n+//\n+// metadata is opaque to netstack.\ntype metadata struct {\nHookEntry [linux.NF_INET_NUMHOOKS]uint32\nUnderflow [linux.NF_INET_NUMHOOKS]uint32\n@@ -44,10 +51,12 @@ type metadata struct {\nSize uint32\n}\n-const enableDebugLog = true\n+const enableDebug = false\n+// nflog logs messages related to the writing and reading of iptables, but only\n+// when enableDebug is true.\nfunc nflog(format string, args ...interface{}) {\n- if enableDebugLog {\n+ if enableDebug {\nlog.Infof(\"netfilter: \"+format, args...)\n}\n}\n@@ -80,7 +89,7 @@ func GetInfo(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr) (linux.IPT\ninfo.NumEntries = metadata.NumEntries\ninfo.Size = metadata.Size\n- nflog(\"GetInfo returning info: %+v\", info)\n+ nflog(\"returning info: %+v\", info)\nreturn info, nil\n}\n@@ -163,19 +172,19 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\ncopy(entries.Name[:], tablename)\nfor ruleIdx, rule := range table.Rules {\n- nflog(\"Current offset: %d\", entries.Size)\n+ nflog(\"convert to binary: current offset: %d\", entries.Size)\n// Is this a chain entry point?\nfor hook, hookRuleIdx := range table.BuiltinChains {\nif hookRuleIdx == ruleIdx {\n- nflog(\"Found hook %d at offset %d\", hook, entries.Size)\n+ nflog(\"convert to binary: found hook %d at offset %d\", hook, entries.Size)\nmeta.HookEntry[hook] = entries.Size\n}\n}\n// Is this a chain underflow point?\nfor underflow, underflowRuleIdx := range table.Underflows {\nif underflowRuleIdx == ruleIdx {\n- nflog(\"Found underflow %d at offset %d\", underflow, entries.Size)\n+ nflog(\"convert to binary: found underflow %d at offset %d\", underflow, entries.Size)\nmeta.Underflow[underflow] = entries.Size\n}\n}\n@@ -195,7 +204,7 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\n// Serialize the matcher and add it to the\n// entry.\nserialized := marshalMatcher(matcher)\n- nflog(\"matcher serialized as: %v\", serialized)\n+ nflog(\"convert to binary: matcher serialized as: %v\", serialized)\nif len(serialized)%8 != 0 {\npanic(fmt.Sprintf(\"matcher %T is not 64-bit aligned\", matcher))\n}\n@@ -212,14 +221,14 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\nentry.Elems = append(entry.Elems, serialized...)\nentry.NextOffset += uint16(len(serialized))\n- nflog(\"Adding entry: %+v\", entry)\n+ nflog(\"convert to binary: adding entry: %+v\", entry)\nentries.Size += uint32(entry.NextOffset)\nentries.Entrytable = append(entries.Entrytable, entry)\nmeta.NumEntries++\n}\n- nflog(\"Finished with an marshalled size of %d\", meta.Size)\n+ nflog(\"convert to binary: finished with an marshalled size of %d\", meta.Size)\nmeta.Size = entries.Size\nreturn entries, meta, nil\n}\n@@ -237,16 +246,18 @@ func marshalMatcher(matcher iptables.Matcher) []byte {\n}\nfunc marshalUDPMatcher(matcher *iptables.UDPMatcher) []byte {\n- nflog(\"Marshalling UDP matcher: %+v\", matcher)\n+ nflog(\"convert to binary: marshalling UDP matcher: %+v\", matcher)\n+\n+ // We have to pad this struct size to a multiple of 8 bytes.\n+ const size = linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP + 6\nlinuxMatcher := linux.KernelXTEntryMatch{\nXTEntryMatch: linux.XTEntryMatch{\n- MatchSize: linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP + 6,\n- // Name: \"udp\",\n+ MatchSize: size,\n},\nData: make([]byte, 0, linux.SizeOfXTUDP),\n}\n- copy(linuxMatcher.Name[:], \"udp\")\n+ copy(linuxMatcher.Name[:], matcherNameUDP)\nxtudp := linux.XTUDP{\nSourcePortStart: matcher.Data.SourcePortStart,\n@@ -255,17 +266,12 @@ func marshalUDPMatcher(matcher *iptables.UDPMatcher) []byte {\nDestinationPortEnd: matcher.Data.DestinationPortEnd,\nInverseFlags: matcher.Data.InverseFlags,\n}\n- nflog(\"marshalUDPMatcher: xtudp: %+v\", xtudp)\nlinuxMatcher.Data = binary.Marshal(linuxMatcher.Data, usermem.ByteOrder, xtudp)\n- nflog(\"marshalUDPMatcher: linuxMatcher: %+v\", linuxMatcher)\n- // We have to pad this struct size to a multiple of 8 bytes, so we make\n- // this a little longer than it needs to be.\n- buf := make([]byte, 0, linux.SizeOfXTEntryMatch+linux.SizeOfXTUDP+6)\n+ buf := make([]byte, 0, size)\nbuf = binary.Marshal(buf, usermem.ByteOrder, linuxMatcher)\nbuf = append(buf, []byte{0, 0, 0, 0, 0, 0}...)\n- nflog(\"Marshalled into matcher of size %d\", len(buf))\n- nflog(\"marshalUDPMatcher: buf is: %v\", buf)\n+ nflog(\"convert to binary: marshalled UDP matcher into %v\", buf)\nreturn buf[:]\n}\n@@ -283,9 +289,8 @@ func marshalTarget(target iptables.Target) []byte {\n}\nfunc marshalStandardTarget(verdict iptables.Verdict) []byte {\n- nflog(\"Marshalling standard target with size %d\", linux.SizeOfXTStandardTarget)\n+ nflog(\"convert to binary: marshalling standard target with size %d\", linux.SizeOfXTStandardTarget)\n- // TODO: Must be aligned.\n// The target's name will be the empty string.\ntarget := linux.XTStandardTarget{\nTarget: linux.XTEntryTarget{\n@@ -353,8 +358,6 @@ func translateToStandardVerdict(val int32) (iptables.Verdict, *syserr.Error) {\n// SetEntries sets iptables rules for a single table. See\n// net/ipv4/netfilter/ip_tables.c:translate_table for reference.\nfunc SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n- // printReplace(optVal)\n-\n// Get the basic rules data (struct ipt_replace).\nif len(optVal) < linux.SizeOfIPTReplace {\nlog.Warningf(\"netfilter.SetEntries: optVal has insufficient size for replace %d\", len(optVal))\n@@ -375,13 +378,13 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nreturn syserr.ErrInvalidArgument\n}\n- nflog(\"Setting entries in table %q\", replace.Name.String())\n+ nflog(\"set entries: setting entries in table %q\", replace.Name.String())\n// Convert input into a list of rules and their offsets.\nvar offset uint32\nvar offsets []uint32\nfor entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\n- nflog(\"Processing entry at offset %d\", offset)\n+ nflog(\"set entries: processing entry at offset %d\", offset)\n// Get the struct ipt_entry.\nif len(optVal) < linux.SizeOfIPTEntry {\n@@ -406,11 +409,13 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nreturn err\n}\n- // TODO: Matchers (and maybe targets) can specify that they only work for certiain protocols, hooks, tables.\n+ // TODO(gvisor.dev/issue/170): Matchers and targets can specify\n+ // that they only work for certiain protocols, hooks, tables.\n// Get matchers.\nmatchersSize := entry.TargetOffset - linux.SizeOfIPTEntry\nif len(optVal) < int(matchersSize) {\nlog.Warningf(\"netfilter: entry doesn't have enough room for its matchers (only %d bytes remain)\", len(optVal))\n+ return syserr.ErrInvalidArgument\n}\nmatchers, err := parseMatchers(filter, optVal[:matchersSize])\nif err != nil {\n@@ -423,6 +428,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\ntargetSize := entry.NextOffset - entry.TargetOffset\nif len(optVal) < int(targetSize) {\nlog.Warningf(\"netfilter: entry doesn't have enough room for its target (only %d bytes remain)\", len(optVal))\n+ return syserr.ErrInvalidArgument\n}\ntarget, err := parseTarget(optVal[:targetSize])\nif err != nil {\n@@ -500,10 +506,11 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// parseMatchers parses 0 or more matchers from optVal. optVal should contain\n// only the matchers.\nfunc parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Matcher, *syserr.Error) {\n- nflog(\"Parsing matchers of size %d\", len(optVal))\n+ nflog(\"set entries: parsing matchers of size %d\", len(optVal))\nvar matchers []iptables.Matcher\nfor len(optVal) > 0 {\n- nflog(\"parseMatchers: optVal has len %d\", len(optVal))\n+ nflog(\"set entries: optVal has len %d\", len(optVal))\n+\n// Get the XTEntryMatch.\nif len(optVal) < linux.SizeOfXTEntryMatch {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry match: %d\", len(optVal))\n@@ -512,7 +519,7 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\nvar match linux.XTEntryMatch\nbuf := optVal[:linux.SizeOfXTEntryMatch]\nbinary.Unmarshal(buf, usermem.ByteOrder, &match)\n- nflog(\"parseMatchers: parsed entry match %q: %+v\", match.Name.String(), match)\n+ nflog(\"set entries: parsed entry match %q: %+v\", match.Name.String(), match)\n// Check some invariants.\nif match.MatchSize < linux.SizeOfXTEntryMatch {\n@@ -528,17 +535,17 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\nvar matcher iptables.Matcher\nvar err error\nswitch match.Name.String() {\n- case \"udp\":\n+ case matcherNameUDP:\nif len(buf) < linux.SizeOfXTUDP {\nlog.Warningf(\"netfilter: optVal has insufficient size for UDP match: %d\", len(optVal))\nreturn nil, syserr.ErrInvalidArgument\n}\n+ // For alignment reasons, the match's total size may\n+ // exceed what's strictly necessary to hold matchData.\nvar matchData linux.XTUDP\n- // For alignment reasons, the match's total size may exceed what's\n- // strictly necessary to hold matchData.\nbinary.Unmarshal(buf[:linux.SizeOfXTUDP], usermem.ByteOrder, &matchData)\nlog.Infof(\"parseMatchers: parsed XTUDP: %+v\", matchData)\n- matcher, err = iptables.NewUDPMatcher(filter, iptables.UDPMatcherData{\n+ matcher, err = iptables.NewUDPMatcher(filter, iptables.UDPMatcherParams{\nSourcePortStart: matchData.SourcePortStart,\nSourcePortEnd: matchData.SourcePortEnd,\nDestinationPortStart: matchData.DestinationPortStart,\n@@ -557,19 +564,22 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\nmatchers = append(matchers, matcher)\n- // TODO: Support revision.\n- // TODO: Support proto -- matchers usually specify which proto(s) they work with.\n+ // TODO(gvisor.dev/issue/170): Check the revision field.\noptVal = optVal[match.MatchSize:]\n}\n- // TODO: Check that optVal is exhausted.\n+ if len(optVal) != 0 {\n+ log.Warningf(\"netfilter: optVal should be exhausted after parsing matchers\")\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\nreturn matchers, nil\n}\n// parseTarget parses a target from optVal. optVal should contain only the\n// target.\nfunc parseTarget(optVal []byte) (iptables.Target, *syserr.Error) {\n- nflog(\"Parsing target of size %d\", len(optVal))\n+ nflog(\"set entries: parsing target of size %d\", len(optVal))\nif len(optVal) < linux.SizeOfXTEntryTarget {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\nreturn nil, syserr.ErrInvalidArgument\n@@ -598,7 +608,8 @@ func parseTarget(optVal []byte) (iptables.Target, *syserr.Error) {\ncase iptables.Drop:\nreturn iptables.UnconditionalDropTarget{}, nil\ndefault:\n- panic(fmt.Sprintf(\"Unknown verdict: %v\", verdict))\n+ log.Warningf(\"Unknown verdict: %v\", verdict)\n+ return nil, syserr.ErrInvalidArgument\n}\ncase errorTargetName:\n@@ -673,52 +684,3 @@ func hookFromLinux(hook int) iptables.Hook {\n}\npanic(fmt.Sprintf(\"Unknown hook %d does not correspond to a builtin chain\", hook))\n}\n-\n-// printReplace prints information about the struct ipt_replace in optVal. It\n-// is only for debugging.\n-func printReplace(optVal []byte) {\n- // Basic replace info.\n- var replace linux.IPTReplace\n- replaceBuf := optVal[:linux.SizeOfIPTReplace]\n- optVal = optVal[linux.SizeOfIPTReplace:]\n- binary.Unmarshal(replaceBuf, usermem.ByteOrder, &replace)\n- log.Infof(\"Replacing table %q: %+v\", replace.Name.String(), replace)\n-\n- // Read in the list of entries at the end of replace.\n- var totalOffset uint16\n- for entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\n- var entry linux.IPTEntry\n- entryBuf := optVal[:linux.SizeOfIPTEntry]\n- binary.Unmarshal(entryBuf, usermem.ByteOrder, &entry)\n- log.Infof(\"Entry %d (total offset %d): %+v\", entryIdx, totalOffset, entry)\n-\n- totalOffset += entry.NextOffset\n- if entry.TargetOffset == linux.SizeOfIPTEntry {\n- log.Infof(\"Entry has no matches.\")\n- } else {\n- log.Infof(\"Entry has matches.\")\n- }\n-\n- var target linux.XTEntryTarget\n- targetBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTEntryTarget]\n- binary.Unmarshal(targetBuf, usermem.ByteOrder, &target)\n- log.Infof(\"Target named %q: %+v\", target.Name.String(), target)\n-\n- switch target.Name.String() {\n- case \"\":\n- var standardTarget linux.XTStandardTarget\n- stBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTStandardTarget]\n- binary.Unmarshal(stBuf, usermem.ByteOrder, &standardTarget)\n- log.Infof(\"Standard target with verdict %q (%d).\", linux.VerdictStrings[standardTarget.Verdict], standardTarget.Verdict)\n- case errorTargetName:\n- var errorTarget linux.XTErrorTarget\n- etBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTErrorTarget]\n- binary.Unmarshal(etBuf, usermem.ByteOrder, &errorTarget)\n- log.Infof(\"Error target with name %q.\", errorTarget.Name.String())\n- default:\n- log.Infof(\"Unknown target type.\")\n- }\n-\n- optVal = optVal[entry.NextOffset:]\n- }\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -169,8 +169,6 @@ type IPHeaderFilter struct {\nProtocol tcpip.TransportProtocolNumber\n}\n-// TODO: Should these be able to marshal/unmarshal themselves?\n-// TODO: Something has to map the name to the matcher.\n// A Matcher is the interface for matching packets.\ntype Matcher interface {\n// Match returns whether the packet matches and whether the packet\n@@ -179,19 +177,6 @@ type Matcher interface {\n//\n// Precondition: packet.NetworkHeader is set.\nMatch(hook Hook, packet tcpip.PacketBuffer, interfaceName string) (matches bool, hotdrop bool)\n-\n- // TODO: Make this typesafe by having each Matcher have their own, typed CheckEntry?\n- // CheckEntry(params MatchCheckEntryParams) bool\n-}\n-\n-// TODO: Unused?\n-type MatchCheckEntryParams struct {\n- Table string // TODO: Tables should be an enum...\n- Filter IPHeaderFilter\n- Info interface{} // TODO: Type unsafe.\n- // HookMask uint8\n- // Family uint8\n- // NFTCompat bool\n}\n// A Target is the interface for taking an action for a packet.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/udp_matcher.go", "new_path": "pkg/tcpip/iptables/udp_matcher.go", "diff": "@@ -16,33 +16,28 @@ package iptables\nimport (\n\"fmt\"\n- \"runtime/debug\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n+// TODO(gvisor.dev/issue/170): The following per-matcher params should be\n+// supported:\n+// - Table name\n+// - Match size\n+// - User size\n+// - Hooks\n+// - Proto\n+// - Family\n+\n+// UDPMatcher matches UDP packets and their headers. It implements Matcher.\ntype UDPMatcher struct {\n- Data UDPMatcherData\n-\n- // tablename string\n- // unsigned int matchsize;\n- // unsigned int usersize;\n- // #ifdef CONFIG_COMPAT\n- // unsigned int compatsize;\n- // #endif\n- // unsigned int hooks;\n- // unsigned short proto;\n- // unsigned short family;\n+ Data UDPMatcherParams\n}\n-// TODO: Delete?\n-// MatchCheckEntryParams\n-\n-type UDPMatcherData struct {\n- // Filter IPHeaderFilter\n-\n+// UDPMatcherParams are the parameters used to create a UDPMatcher.\n+type UDPMatcherParams struct {\nSourcePortStart uint16\nSourcePortEnd uint16\nDestinationPortStart uint16\n@@ -50,12 +45,12 @@ type UDPMatcherData struct {\nInverseFlags uint8\n}\n-func NewUDPMatcher(filter IPHeaderFilter, data UDPMatcherData) (Matcher, error) {\n- // TODO: We currently only support source port and destination port.\n- log.Infof(\"Adding rule with UDPMatcherData: %+v\", data)\n+// NewUDPMatcher returns a new instance of UDPMatcher.\n+func NewUDPMatcher(filter IPHeaderFilter, data UDPMatcherParams) (Matcher, error) {\n+ log.Infof(\"Adding rule with UDPMatcherParams: %+v\", data)\nif data.InverseFlags != 0 {\n- return nil, fmt.Errorf(\"unsupported UDP matcher flags set\")\n+ return nil, fmt.Errorf(\"unsupported UDP matcher inverse flags set\")\n}\nif filter.Protocol != header.UDPProtocolNumber {\n@@ -65,21 +60,18 @@ func NewUDPMatcher(filter IPHeaderFilter, data UDPMatcherData) (Matcher, error)\nreturn &UDPMatcher{Data: data}, nil\n}\n-// TODO: Check xt_tcpudp.c. Need to check for same things (e.g. fragments).\n+// Match implements Matcher.Match.\nfunc (um *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\n- log.Infof(\"UDPMatcher called from: %s\", string(debug.Stack()))\nnetHeader := header.IPv4(pkt.NetworkHeader)\n- // TODO: Do we check proto here or elsewhere? I think elsewhere (check\n- // codesearch).\n+ // TODO(gvisor.dev/issue/170): Proto checks should ultimately be moved\n+ // into the iptables.Check codepath as matchers are added.\nif netHeader.TransportProtocol() != header.UDPProtocolNumber {\n- log.Infof(\"UDPMatcher: wrong protocol number\")\nreturn false, false\n}\n// We dont't match fragments.\nif frag := netHeader.FragmentOffset(); frag != 0 {\n- log.Infof(\"UDPMatcher: it's a fragment\")\nif frag == 1 {\nreturn false, true\n}\n@@ -89,20 +81,18 @@ func (um *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName str\n// Now we need the transport header. However, this may not have been set\n// yet.\n- // TODO\n+ // TODO(gvisor.dev/issue/170): Parsing the transport header should\n+ // ultimately be moved into the iptables.Check codepath as matchers are\n+ // added.\nvar udpHeader header.UDP\nif pkt.TransportHeader != nil {\n- log.Infof(\"UDPMatcher: transport header is not nil\")\nudpHeader = header.UDP(pkt.TransportHeader)\n} else {\n- log.Infof(\"UDPMatcher: transport header is nil\")\n- log.Infof(\"UDPMatcher: is network header nil: %t\", pkt.NetworkHeader == nil)\n// The UDP header hasn't been parsed yet. We have to do it here.\nif len(pkt.Data.First()) < header.UDPMinimumSize {\n// There's no valid UDP header here, so we hotdrop the\n// packet.\n- // TODO: Stats.\n- log.Warningf(\"Dropping UDP packet: size to small.\")\n+ log.Warningf(\"Dropping UDP packet: size too small.\")\nreturn false, true\n}\nudpHeader = header.UDP(pkt.Data.First())\n@@ -112,10 +102,6 @@ func (um *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName str\n// matching range.\nsourcePort := udpHeader.SourcePort()\ndestinationPort := udpHeader.DestinationPort()\n- log.Infof(\"UDPMatcher: sport and dport are %d and %d. sports and dport start and end are (%d, %d) and (%d, %d)\",\n- udpHeader.SourcePort(), udpHeader.DestinationPort(),\n- um.Data.SourcePortStart, um.Data.SourcePortEnd,\n- um.Data.DestinationPortStart, um.Data.DestinationPortEnd)\nif sourcePort < um.Data.SourcePortStart || um.Data.SourcePortEnd < sourcePort {\nreturn false, false\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -264,9 +264,9 @@ func (FilterInputMultiUDPRules) ContainerAction(ip net.IP) error {\nif err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\nreturn err\n}\n- // if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", acceptPort), \"-j\", \"ACCEPT\"); err != nil {\n- // return err\n- // }\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", acceptPort), \"-j\", \"ACCEPT\"); err != nil {\n+ return err\n+ }\nreturn filterTable(\"-L\")\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Cleanup for GH review.
260,003
27.01.2020 10:08:18
28,800
6b14be4246e8ed3779bf69dbd59e669caf3f5704
Refactor to hide C from channel.Endpoint. This is to aid later implementation for /dev/net/tun device.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/channel/channel.go", "new_path": "pkg/tcpip/link/channel/channel.go", "diff": "package channel\nimport (\n+ \"context\"\n+\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -38,25 +40,52 @@ type Endpoint struct {\nlinkAddr tcpip.LinkAddress\nGSO bool\n- // C is where outbound packets are queued.\n- C chan PacketInfo\n+ // c is where outbound packets are queued.\n+ c chan PacketInfo\n}\n// New creates a new channel endpoint.\nfunc New(size int, mtu uint32, linkAddr tcpip.LinkAddress) *Endpoint {\nreturn &Endpoint{\n- C: make(chan PacketInfo, size),\n+ c: make(chan PacketInfo, size),\nmtu: mtu,\nlinkAddr: linkAddr,\n}\n}\n+// Close closes e. Further packet injections will panic. Reads continue to\n+// succeed until all packets are read.\n+func (e *Endpoint) Close() {\n+ close(e.c)\n+}\n+\n+// Read does non-blocking read for one packet from the outbound packet queue.\n+func (e *Endpoint) Read() (PacketInfo, bool) {\n+ select {\n+ case pkt := <-e.c:\n+ return pkt, true\n+ default:\n+ return PacketInfo{}, false\n+ }\n+}\n+\n+// ReadContext does blocking read for one packet from the outbound packet queue.\n+// It can be cancelled by ctx, and in this case, it returns false.\n+func (e *Endpoint) ReadContext(ctx context.Context) (PacketInfo, bool) {\n+ select {\n+ case pkt := <-e.c:\n+ return pkt, true\n+ case <-ctx.Done():\n+ return PacketInfo{}, false\n+ }\n+}\n+\n// Drain removes all outbound packets from the channel and counts them.\nfunc (e *Endpoint) Drain() int {\nc := 0\nfor {\nselect {\n- case <-e.C:\n+ case <-e.c:\nc++\ndefault:\nreturn c\n@@ -125,7 +154,7 @@ func (e *Endpoint) WritePacket(_ *stack.Route, gso *stack.GSO, protocol tcpip.Ne\n}\nselect {\n- case e.C <- p:\n+ case e.c <- p:\ndefault:\n}\n@@ -150,7 +179,7 @@ packetLoop:\n}\nselect {\n- case e.C <- p:\n+ case e.c <- p:\nn++\ndefault:\nbreak packetLoop\n@@ -169,7 +198,7 @@ func (e *Endpoint) WriteRawPacket(vv buffer.VectorisedView) *tcpip.Error {\n}\nselect {\n- case e.C <- p:\n+ case e.c <- p:\ndefault:\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp_test.go", "new_path": "pkg/tcpip/network/arp/arp_test.go", "diff": "package arp_test\nimport (\n+ \"context\"\n\"strconv\"\n\"testing\"\n\"time\"\n@@ -83,7 +84,7 @@ func newTestContext(t *testing.T) *testContext {\n}\nfunc (c *testContext) cleanup() {\n- close(c.linkEP.C)\n+ c.linkEP.Close()\n}\nfunc TestDirectRequest(t *testing.T) {\n@@ -110,7 +111,7 @@ func TestDirectRequest(t *testing.T) {\nfor i, address := range []tcpip.Address{stackAddr1, stackAddr2} {\nt.Run(strconv.Itoa(i), func(t *testing.T) {\ninject(address)\n- pi := <-c.linkEP.C\n+ pi, _ := c.linkEP.ReadContext(context.Background())\nif pi.Proto != arp.ProtocolNumber {\nt.Fatalf(\"expected ARP response, got network protocol number %d\", pi.Proto)\n}\n@@ -134,12 +135,11 @@ func TestDirectRequest(t *testing.T) {\n}\ninject(stackAddrBad)\n- select {\n- case pkt := <-c.linkEP.C:\n- t.Errorf(\"stackAddrBad: unexpected packet sent, Proto=%v\", pkt.Proto)\n- case <-time.After(100 * time.Millisecond):\n// Sleep tests are gross, but this will only potentially flake\n// if there's a bug. If there is no bug this will reliably\n// succeed.\n+ ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)\n+ if pkt, ok := c.linkEP.ReadContext(ctx); ok {\n+ t.Errorf(\"stackAddrBad: unexpected packet sent, Proto=%v\", pkt.Proto)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "package ipv6\nimport (\n+ \"context\"\n\"reflect\"\n\"strings\"\n\"testing\"\n@@ -264,8 +265,8 @@ func newTestContext(t *testing.T) *testContext {\n}\nfunc (c *testContext) cleanup() {\n- close(c.linkEP0.C)\n- close(c.linkEP1.C)\n+ c.linkEP0.Close()\n+ c.linkEP1.Close()\n}\ntype routeArgs struct {\n@@ -276,7 +277,7 @@ type routeArgs struct {\nfunc routeICMPv6Packet(t *testing.T, args routeArgs, fn func(*testing.T, header.ICMPv6)) {\nt.Helper()\n- pi := <-args.src.C\n+ pi, _ := args.src.ReadContext(context.Background())\n{\nviews := []buffer.View{pi.Pkt.Header.View(), pi.Pkt.Data.ToView()}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "package stack_test\nimport (\n+ \"context\"\n\"encoding/binary\"\n\"fmt\"\n\"testing\"\n@@ -405,7 +406,7 @@ func TestDADResolve(t *testing.T) {\n// Validate the sent Neighbor Solicitation messages.\nfor i := uint8(0); i < test.dupAddrDetectTransmits; i++ {\n- p := <-e.C\n+ p, _ := e.ReadContext(context.Background())\n// Make sure its an IPv6 packet.\nif p.Proto != header.IPv6ProtocolNumber {\n@@ -3285,8 +3286,13 @@ func TestRouterSolicitation(t *testing.T) {\ne := channel.New(int(test.maxRtrSolicit), 1280, linkAddr1)\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\n- select {\n- case p := <-e.C:\n+ ctx, _ := context.WithTimeout(context.Background(), timeout)\n+ p, ok := e.ReadContext(ctx)\n+ if !ok {\n+ t.Fatal(\"timed out waiting for packet\")\n+ return\n+ }\n+\nif p.Proto != header.IPv6ProtocolNumber {\nt.Fatalf(\"got Proto = %d, want = %d\", p.Proto, header.IPv6ProtocolNumber)\n}\n@@ -3297,17 +3303,12 @@ func TestRouterSolicitation(t *testing.T) {\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPRS(),\n)\n-\n- case <-time.After(timeout):\n- t.Fatal(\"timed out waiting for packet\")\n- }\n}\nwaitForNothing := func(timeout time.Duration) {\nt.Helper()\n- select {\n- case <-e.C:\n+ ctx, _ := context.WithTimeout(context.Background(), timeout)\n+ if _, ok := e.ReadContext(ctx); ok {\nt.Fatal(\"unexpectedly got a packet\")\n- case <-time.After(timeout):\n}\n}\ns := stack.New(stack.Options{\n@@ -3362,8 +3363,13 @@ func TestStopStartSolicitingRouters(t *testing.T) {\ne := channel.New(maxRtrSolicitations, 1280, linkAddr1)\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\n- select {\n- case p := <-e.C:\n+ ctx, _ := context.WithTimeout(context.Background(), timeout)\n+ p, ok := e.ReadContext(ctx)\n+ if !ok {\n+ t.Fatal(\"timed out waiting for packet\")\n+ return\n+ }\n+\nif p.Proto != header.IPv6ProtocolNumber {\nt.Fatalf(\"got Proto = %d, want = %d\", p.Proto, header.IPv6ProtocolNumber)\n}\n@@ -3372,10 +3378,6 @@ func TestStopStartSolicitingRouters(t *testing.T) {\nchecker.DstAddr(header.IPv6AllRoutersMulticastAddress),\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPRS())\n-\n- case <-time.After(timeout):\n- t.Fatal(\"timed out waiting for packet\")\n- }\n}\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n@@ -3391,23 +3393,20 @@ func TestStopStartSolicitingRouters(t *testing.T) {\n// Enable forwarding which should stop router solicitations.\ns.SetForwarding(true)\n- select {\n- case <-e.C:\n+ ctx, _ := context.WithTimeout(context.Background(), delay+defaultTimeout)\n+ if _, ok := e.ReadContext(ctx); ok {\n// A single RS may have been sent before forwarding was enabled.\n- select {\n- case <-e.C:\n+ ctx, _ = context.WithTimeout(context.Background(), interval+defaultTimeout)\n+ if _, ok = e.ReadContext(ctx); ok {\nt.Fatal(\"Should not have sent more than one RS message\")\n- case <-time.After(interval + defaultTimeout):\n}\n- case <-time.After(delay + defaultTimeout):\n}\n// Enabling forwarding again should do nothing.\ns.SetForwarding(true)\n- select {\n- case <-e.C:\n+ ctx, _ = context.WithTimeout(context.Background(), delay+defaultTimeout)\n+ if _, ok := e.ReadContext(ctx); ok {\nt.Fatal(\"unexpectedly got a packet after becoming a router\")\n- case <-time.After(delay + defaultTimeout):\n}\n// Disable forwarding which should start router solicitations.\n@@ -3415,17 +3414,15 @@ func TestStopStartSolicitingRouters(t *testing.T) {\nwaitForPkt(delay + defaultAsyncEventTimeout)\nwaitForPkt(interval + defaultAsyncEventTimeout)\nwaitForPkt(interval + defaultAsyncEventTimeout)\n- select {\n- case <-e.C:\n+ ctx, _ = context.WithTimeout(context.Background(), interval+defaultTimeout)\n+ if _, ok := e.ReadContext(ctx); ok {\nt.Fatal(\"unexpectedly got an extra packet after sending out the expected RSs\")\n- case <-time.After(interval + defaultTimeout):\n}\n// Disabling forwarding again should do nothing.\ns.SetForwarding(false)\n- select {\n- case <-e.C:\n+ ctx, _ = context.WithTimeout(context.Background(), delay+defaultTimeout)\n+ if _, ok := e.ReadContext(ctx); ok {\nt.Fatal(\"unexpectedly got a packet after becoming a router\")\n- case <-time.After(delay + defaultTimeout):\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -1880,9 +1880,7 @@ func TestNICForwarding(t *testing.T) {\nData: buf.ToVectorisedView(),\n})\n- select {\n- case <-ep2.C:\n- default:\n+ if _, ok := ep2.Read(); !ok {\nt.Fatal(\"Packet not forwarded\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_test.go", "new_path": "pkg/tcpip/stack/transport_test.go", "diff": "@@ -623,10 +623,8 @@ func TestTransportForwarding(t *testing.T) {\nt.Fatalf(\"Write failed: %v\", err)\n}\n- var p channel.PacketInfo\n- select {\n- case p = <-ep2.C:\n- default:\n+ p, ok := ep2.Read()\n+ if !ok {\nt.Fatal(\"Response packet not forwarded\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -18,6 +18,7 @@ package context\nimport (\n\"bytes\"\n+ \"context\"\n\"testing\"\n\"time\"\n@@ -215,11 +216,9 @@ func (c *Context) Stack() *stack.Stack {\nfunc (c *Context) CheckNoPacketTimeout(errMsg string, wait time.Duration) {\nc.t.Helper()\n- select {\n- case <-c.linkEP.C:\n+ ctx, _ := context.WithTimeout(context.Background(), wait)\n+ if _, ok := c.linkEP.ReadContext(ctx); ok {\nc.t.Fatal(errMsg)\n-\n- case <-time.After(wait):\n}\n}\n@@ -234,8 +233,14 @@ func (c *Context) CheckNoPacket(errMsg string) {\n// 2 seconds.\nfunc (c *Context) GetPacket() []byte {\nc.t.Helper()\n- select {\n- case p := <-c.linkEP.C:\n+\n+ ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ p, ok := c.linkEP.ReadContext(ctx)\n+ if !ok {\n+ c.t.Fatalf(\"Packet wasn't written out\")\n+ return nil\n+ }\n+\nif p.Proto != ipv4.ProtocolNumber {\nc.t.Fatalf(\"Bad network protocol: got %v, wanted %v\", p.Proto, ipv4.ProtocolNumber)\n}\n@@ -249,12 +254,6 @@ func (c *Context) GetPacket() []byte {\nchecker.IPv4(c.t, b, checker.SrcAddr(StackAddr), checker.DstAddr(TestAddr))\nreturn b\n-\n- case <-time.After(2 * time.Second):\n- c.t.Fatalf(\"Packet wasn't written out\")\n- }\n-\n- return nil\n}\n// GetPacketNonBlocking reads a packet from the link layer endpoint\n@@ -263,8 +262,12 @@ func (c *Context) GetPacket() []byte {\n// nil immediately.\nfunc (c *Context) GetPacketNonBlocking() []byte {\nc.t.Helper()\n- select {\n- case p := <-c.linkEP.C:\n+\n+ p, ok := c.linkEP.Read()\n+ if !ok {\n+ return nil\n+ }\n+\nif p.Proto != ipv4.ProtocolNumber {\nc.t.Fatalf(\"Bad network protocol: got %v, wanted %v\", p.Proto, ipv4.ProtocolNumber)\n}\n@@ -274,9 +277,6 @@ func (c *Context) GetPacketNonBlocking() []byte {\nchecker.IPv4(c.t, b, checker.SrcAddr(StackAddr), checker.DstAddr(TestAddr))\nreturn b\n- default:\n- return nil\n- }\n}\n// SendICMPPacket builds and sends an ICMPv4 packet via the link layer endpoint.\n@@ -484,8 +484,14 @@ func (c *Context) CreateV6Endpoint(v6only bool) {\n// and asserts that it is an IPv6 Packet with the expected src/dest addresses.\nfunc (c *Context) GetV6Packet() []byte {\nc.t.Helper()\n- select {\n- case p := <-c.linkEP.C:\n+\n+ ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ p, ok := c.linkEP.ReadContext(ctx)\n+ if !ok {\n+ c.t.Fatalf(\"Packet wasn't written out\")\n+ return nil\n+ }\n+\nif p.Proto != ipv6.ProtocolNumber {\nc.t.Fatalf(\"Bad network protocol: got %v, wanted %v\", p.Proto, ipv6.ProtocolNumber)\n}\n@@ -495,12 +501,6 @@ func (c *Context) GetV6Packet() []byte {\nchecker.IPv6(c.t, b, checker.SrcAddr(StackV6Addr), checker.DstAddr(TestV6Addr))\nreturn b\n-\n- case <-time.After(2 * time.Second):\n- c.t.Fatalf(\"Packet wasn't written out\")\n- }\n-\n- return nil\n}\n// SendV6Packet builds and sends an IPv6 Packet via the link layer endpoint of\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -16,6 +16,7 @@ package udp_test\nimport (\n\"bytes\"\n+ \"context\"\n\"fmt\"\n\"math/rand\"\n\"testing\"\n@@ -357,8 +358,13 @@ func (c *testContext) createEndpointForFlow(flow testFlow) {\nfunc (c *testContext) getPacketAndVerify(flow testFlow, checkers ...checker.NetworkChecker) []byte {\nc.t.Helper()\n- select {\n- case p := <-c.linkEP.C:\n+ ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)\n+ p, ok := c.linkEP.ReadContext(ctx)\n+ if !ok {\n+ c.t.Fatalf(\"Packet wasn't written out\")\n+ return nil\n+ }\n+\nif p.Proto != flow.netProto() {\nc.t.Fatalf(\"Bad network protocol: got %v, wanted %v\", p.Proto, flow.netProto())\n}\n@@ -367,7 +373,7 @@ func (c *testContext) getPacketAndVerify(flow testFlow, checkers ...checker.Netw\nb := append(hdr[:len(hdr):len(hdr)], p.Pkt.Data.ToView()...)\nh := flow.header4Tuple(outgoing)\n- checkers := append(\n+ checkers = append(\ncheckers,\nchecker.SrcAddr(h.srcAddr.Addr),\nchecker.DstAddr(h.dstAddr.Addr),\n@@ -375,12 +381,6 @@ func (c *testContext) getPacketAndVerify(flow testFlow, checkers ...checker.Netw\n)\nflow.checkerFn()(c.t, b, checkers...)\nreturn b\n-\n- case <-time.After(2 * time.Second):\n- c.t.Fatalf(\"Packet wasn't written out\")\n- }\n-\n- return nil\n}\n// injectPacket creates a packet of the given flow and with the given payload,\n@@ -1541,16 +1541,21 @@ func TestV4UnknownDestination(t *testing.T) {\n}\nc.injectPacket(tc.flow, payload)\nif !tc.icmpRequired {\n- select {\n- case p := <-c.linkEP.C:\n+ ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ if p, ok := c.linkEP.ReadContext(ctx); ok {\nt.Fatalf(\"unexpected packet received: %+v\", p)\n- case <-time.After(1 * time.Second):\n+ }\nreturn\n}\n+\n+ // ICMP required.\n+ ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ p, ok := c.linkEP.ReadContext(ctx)\n+ if !ok {\n+ t.Fatalf(\"packet wasn't written out\")\n+ return\n}\n- select {\n- case p := <-c.linkEP.C:\nvar pkt []byte\npkt = append(pkt, p.Pkt.Header.View()...)\npkt = append(pkt, p.Pkt.Data.ToView()...)\n@@ -1581,9 +1586,6 @@ func TestV4UnknownDestination(t *testing.T) {\nif got, want := origDgram.Payload(), payload[:wantLen]; !bytes.Equal(got, want) {\nt.Fatalf(\"unexpected payload got: %d, want: %d\", got, want)\n}\n- case <-time.After(1 * time.Second):\n- t.Fatalf(\"packet wasn't written out\")\n- }\n})\n}\n}\n@@ -1615,16 +1617,21 @@ func TestV6UnknownDestination(t *testing.T) {\n}\nc.injectPacket(tc.flow, payload)\nif !tc.icmpRequired {\n- select {\n- case p := <-c.linkEP.C:\n+ ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ if p, ok := c.linkEP.ReadContext(ctx); ok {\nt.Fatalf(\"unexpected packet received: %+v\", p)\n- case <-time.After(1 * time.Second):\n+ }\nreturn\n}\n+\n+ // ICMP required.\n+ ctx, _ := context.WithTimeout(context.Background(), time.Second)\n+ p, ok := c.linkEP.ReadContext(ctx)\n+ if !ok {\n+ t.Fatalf(\"packet wasn't written out\")\n+ return\n}\n- select {\n- case p := <-c.linkEP.C:\nvar pkt []byte\npkt = append(pkt, p.Pkt.Header.View()...)\npkt = append(pkt, p.Pkt.Data.ToView()...)\n@@ -1654,9 +1661,6 @@ func TestV6UnknownDestination(t *testing.T) {\nif got, want := origDgram.Payload(), payload[:wantLen]; !bytes.Equal(got, want) {\nt.Fatalf(\"unexpected payload got: %v, want: %v\", got, want)\n}\n- case <-time.After(1 * time.Second):\n- t.Fatalf(\"packet wasn't written out\")\n- }\n})\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor to hide C from channel.Endpoint. This is to aid later implementation for /dev/net/tun device. PiperOrigin-RevId: 291746025
259,860
27.01.2020 12:19:20
28,800
13c1f38dfa215ab3e3cc70642721f55ab226d5b7
Update bug number for supporting extended attribute namespaces.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "new_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "diff": "@@ -103,6 +103,7 @@ func getXattr(t *kernel.Task, d *fs.Dirent, nameAddr usermem.Addr, size uint64)\nreturn 0, \"\", err\n}\n+ // TODO(b/148380782): Support xattrs in namespaces other than \"user\".\nif !strings.HasPrefix(name, linux.XATTR_USER_PREFIX) {\nreturn 0, \"\", syserror.EOPNOTSUPP\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/xattr.cc", "new_path": "test/syscalls/linux/xattr.cc", "diff": "@@ -131,7 +131,7 @@ TEST_F(XattrTest, XattrWriteOnly_NoRandomSave) {\n}\nTEST_F(XattrTest, XattrTrustedWithNonadmin) {\n- // TODO(b/127675828): Support setxattr and getxattr with \"trusted\" prefix.\n+ // TODO(b/148380782): Support setxattr and getxattr with \"trusted\" prefix.\nSKIP_IF(IsRunningOnGvisor());\nSKIP_IF(ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_SYS_ADMIN)));\n" } ]
Go
Apache License 2.0
google/gvisor
Update bug number for supporting extended attribute namespaces. PiperOrigin-RevId: 291774815
259,962
27.01.2020 12:32:07
28,800
fbfcfcf5b03b4fddb4f00a3e8721cba07fc5343f
Update ChecksumVVWithoffset to use unrolled version. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/checksum.go", "new_path": "pkg/tcpip/header/checksum.go", "diff": "@@ -213,7 +213,7 @@ func ChecksumVVWithOffset(vv buffer.VectorisedView, initial uint16, off int, siz\n}\nv = v[:l]\n- sum, odd = calculateChecksum(v, odd, uint32(sum))\n+ sum, odd = unrolledCalculateChecksum(v, odd, uint32(sum))\nsize -= len(v)\nif size == 0 {\n" } ]
Go
Apache License 2.0
google/gvisor
Update ChecksumVVWithoffset to use unrolled version. Fixes #1656 PiperOrigin-RevId: 291777279
259,858
27.01.2020 13:22:50
28,800
90ec5961667a1c4a21702e64adb383403af8ad25
Fix licenses. The preferred Copyright holder is "The gVisor Authors".
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table.go", "new_path": "pkg/sentry/kernel/fd_table.go", "diff": "-// Copyright 2018 Google LLC\n+// 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table_test.go", "new_path": "pkg/sentry/kernel/fd_table_test.go", "diff": "-// Copyright 2018 Google LLC\n+// 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table_unsafe.go", "new_path": "pkg/sentry/kernel/fd_table_unsafe.go", "diff": "-// Copyright 2018 Google LLC\n+// 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/entry_arm64.go", "new_path": "pkg/sentry/platform/ring0/entry_arm64.go", "diff": "-// Copyright 2019 Google Inc.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/kernel_arm64.go", "new_path": "pkg/sentry/platform/ring0/kernel_arm64.go", "diff": "-// Copyright 2019 Google Inc.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/lib_arm64.go", "new_path": "pkg/sentry/platform/ring0/lib_arm64.go", "diff": "-// Copyright 2019 Google Inc.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/offsets_arm64.go", "new_path": "pkg/sentry/platform/ring0/offsets_arm64.go", "diff": "-// Copyright 2019 Google Inc.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "-// Copyright 2019 The gVisor authors.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "-// Copyright 2019 The gVisor authors.\n+// Copyright 2019 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" }, { "change_type": "MODIFY", "old_path": "runsc/cmd/help.go", "new_path": "runsc/cmd/help.go", "diff": "-// Copyright 2018 Google LLC\n+// 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" }, { "change_type": "MODIFY", "old_path": "tools/go_marshal/main.go", "new_path": "tools/go_marshal/main.go", "diff": "-// Copyright 2019 Google LLC\n+// Copyright 2019 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" } ]
Go
Apache License 2.0
google/gvisor
Fix licenses. The preferred Copyright holder is "The gVisor Authors". PiperOrigin-RevId: 291786657
259,858
27.01.2020 18:26:26
28,800
5776a7b6f6b52faf6e0735c3f4a892639c1bd773
Fix header ordering and format all C++ code.
[ { "change_type": "MODIFY", "old_path": "CONTRIBUTING.md", "new_path": "CONTRIBUTING.md", "diff": "@@ -36,7 +36,8 @@ directory tree.\nAll Go code should conform to the [Go style guidelines][gostyle]. C++ code\nshould conform to the [Google C++ Style Guide][cppstyle] and the guidelines\n-described for [tests][teststyle].\n+described for [tests][teststyle]. Note that code may be automatically formatted\n+per the guidelines when merged.\nAs a secure runtime, we need to maintain the safety of all of code included in\ngVisor. The following rules help mitigate issues.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mempolicy.cc", "new_path": "test/syscalls/linux/mempolicy.cc", "diff": "@@ -221,8 +221,8 @@ TEST(MempolicyTest, GetMempolicyQueryNodeForAddress) {\nSyscallFailsWithErrno(EFAULT));\n// Invalid mode pointer.\n- ASSERT_THAT(get_mempolicy(reinterpret_cast<int*>(invalid_address), nullptr, 0,\n- &dummy_stack_address, MPOL_F_ADDR | MPOL_F_NODE),\n+ ASSERT_THAT(get_mempolicy(reinterpret_cast<int *>(invalid_address), nullptr,\n+ 0, &dummy_stack_address, MPOL_F_ADDR | MPOL_F_NODE),\nSyscallFailsWithErrno(EFAULT));\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/mlock.cc", "new_path": "test/syscalls/linux/mlock.cc", "diff": "@@ -60,7 +60,6 @@ bool IsPageMlocked(uintptr_t addr) {\nreturn true;\n}\n-\nTEST(MlockTest, Basic) {\nSKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(CanMlock()));\nauto const mapping = ASSERT_NO_ERRNO_AND_VALUE(\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/msync.cc", "new_path": "test/syscalls/linux/msync.cc", "diff": "@@ -60,9 +60,7 @@ std::vector<std::function<PosixErrorOr<Mapping>()>> SyncableMappings() {\nfor (int const mflags : {MAP_PRIVATE, MAP_SHARED}) {\nint const prot = PROT_READ | (writable ? PROT_WRITE : 0);\nint const oflags = O_CREAT | (writable ? O_RDWR : O_RDONLY);\n- funcs.push_back([=] {\n- return MmapAnon(kPageSize, prot, mflags);\n- });\n+ funcs.push_back([=] { return MmapAnon(kPageSize, prot, mflags); });\nfuncs.push_back([=]() -> PosixErrorOr<Mapping> {\nstd::string const path = NewTempAbsPath();\nASSIGN_OR_RETURN_ERRNO(auto fd, Open(path, oflags, 0644));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ptrace.cc", "new_path": "test/syscalls/linux/ptrace.cc", "diff": "@@ -178,7 +178,8 @@ TEST(PtraceTest, GetSigMask) {\n// Install a signal handler for kBlockSignal to avoid termination and block\n// it.\n- TEST_PCHECK(signal(kBlockSignal, +[](int signo) {}) != SIG_ERR);\n+ TEST_PCHECK(signal(\n+ kBlockSignal, +[](int signo) {}) != SIG_ERR);\nMaybeSave();\nTEST_PCHECK(sigprocmask(SIG_SETMASK, &blocked, nullptr) == 0);\nMaybeSave();\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/seccomp.cc", "new_path": "test/syscalls/linux/seccomp.cc", "diff": "@@ -113,7 +113,8 @@ TEST(SeccompTest, RetKillCausesDeathBySIGSYS) {\npid_t const pid = fork();\nif (pid == 0) {\n// Register a signal handler for SIGSYS that we don't expect to be invoked.\n- RegisterSignalHandler(SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_KILL);\nsyscall(kFilteredSyscall);\nTEST_CHECK_MSG(false, \"Survived invocation of test syscall\");\n@@ -132,7 +133,8 @@ TEST(SeccompTest, RetKillOnlyKillsOneThread) {\npid_t const pid = fork();\nif (pid == 0) {\n// Register a signal handler for SIGSYS that we don't expect to be invoked.\n- RegisterSignalHandler(SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_KILL);\n// Pass CLONE_VFORK to block the original thread in the child process until\n// the clone thread exits with SIGSYS.\n@@ -346,7 +348,8 @@ TEST(SeccompTest, LeastPermissiveFilterReturnValueApplies) {\n// one that causes the kill that should be ignored.\npid_t const pid = fork();\nif (pid == 0) {\n- RegisterSignalHandler(SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\n+ RegisterSignalHandler(\n+ SIGSYS, +[](int, siginfo_t*, void*) { _exit(1); });\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_TRACE);\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_KILL);\nApplySeccompFilter(kFilteredSyscall, SECCOMP_RET_ERRNO | ENOTNAM);\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket_errqueue_test_case.cc", "new_path": "test/syscalls/linux/udp_socket_errqueue_test_case.cc", "diff": "#ifndef __fuchsia__\n-#include \"test/syscalls/linux/udp_socket_test_cases.h\"\n-\n#include <arpa/inet.h>\n#include <fcntl.h>\n#include <linux/errqueue.h>\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/udp_socket_test_cases.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n" }, { "change_type": "MODIFY", "old_path": "test/util/capability_util.cc", "new_path": "test/util/capability_util.cc", "diff": "@@ -36,8 +36,8 @@ PosixErrorOr<bool> CanCreateUserNamespace() {\nASSIGN_OR_RETURN_ERRNO(\nauto child_stack,\nMmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n- int const child_pid =\n- clone(+[](void*) { return 0; },\n+ int const child_pid = clone(\n+ +[](void*) { return 0; },\nreinterpret_cast<void*>(child_stack.addr() + kPageSize),\nCLONE_NEWUSER | SIGCHLD, /* arg = */ nullptr);\nif (child_pid > 0) {\n" }, { "change_type": "MODIFY", "old_path": "test/util/multiprocess_util.h", "new_path": "test/util/multiprocess_util.h", "diff": "@@ -99,7 +99,8 @@ inline PosixErrorOr<Cleanup> ForkAndExec(const std::string& filename,\nconst ExecveArray& argv,\nconst ExecveArray& envv, pid_t* child,\nint* execve_errno) {\n- return ForkAndExec(filename, argv, envv, [] {}, child, execve_errno);\n+ return ForkAndExec(\n+ filename, argv, envv, [] {}, child, execve_errno);\n}\n// Equivalent to ForkAndExec, except using dirfd and flags with execveat.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix header ordering and format all C++ code. PiperOrigin-RevId: 291844200
260,004
27.01.2020 20:28:14
28,800
2a2da5be31ea3c32e66f0c0ff61ef189848f5258
Add a type to represent the NDP Source Link Layer Address option Tests: header.TestNDPSourceLinkLayerAddressOptionEthernetAddress header.TestNDPSourceLinkLayerAddressOptionSerialize header.TestNDPOptionsIterCheck header.TestNDPOptionsIter
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/icmpv6.go", "new_path": "pkg/tcpip/header/icmpv6.go", "diff": "@@ -52,7 +52,7 @@ const (\n// ICMPv6NeighborAdvertSize is size of a neighbor advertisement\n// including the NDP Target Link Layer option for an Ethernet\n// address.\n- ICMPv6NeighborAdvertSize = ICMPv6HeaderSize + NDPNAMinimumSize + ndpTargetEthernetLinkLayerAddressSize\n+ ICMPv6NeighborAdvertSize = ICMPv6HeaderSize + NDPNAMinimumSize + ndpLinkLayerAddressSize\n// ICMPv6EchoMinimumSize is the minimum size of a valid ICMP echo packet.\nICMPv6EchoMinimumSize = 8\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ndp_options.go", "new_path": "pkg/tcpip/header/ndp_options.go", "diff": "@@ -24,13 +24,17 @@ import (\n)\nconst (\n- // NDPTargetLinkLayerAddressOptionType is the type of the Target\n- // Link-Layer Address option, as per RFC 4861 section 4.6.1.\n+ // NDPSourceLinkLayerAddressOptionType is the type of the Source Link Layer\n+ // Address option, as per RFC 4861 section 4.6.1.\n+ NDPSourceLinkLayerAddressOptionType = 1\n+\n+ // NDPTargetLinkLayerAddressOptionType is the type of the Target Link Layer\n+ // Address option, as per RFC 4861 section 4.6.1.\nNDPTargetLinkLayerAddressOptionType = 2\n- // ndpTargetEthernetLinkLayerAddressSize is the size of a Target\n- // Link Layer Option for an Ethernet address.\n- ndpTargetEthernetLinkLayerAddressSize = 8\n+ // ndpLinkLayerAddressSize is the size of a Source or Target Link Layer\n+ // Address option.\n+ ndpLinkLayerAddressSize = 8\n// NDPPrefixInformationType is the type of the Prefix Information\n// option, as per RFC 4861 section 4.6.2.\n@@ -189,6 +193,9 @@ func (i *NDPOptionIterator) Next() (NDPOption, bool, error) {\ni.opts = i.opts[numBytes:]\nswitch t {\n+ case NDPSourceLinkLayerAddressOptionType:\n+ return NDPSourceLinkLayerAddressOption(body), false, nil\n+\ncase NDPTargetLinkLayerAddressOptionType:\nreturn NDPTargetLinkLayerAddressOption(body), false, nil\n@@ -368,6 +375,41 @@ func (b NDPOptionsSerializer) Length() int {\nreturn l\n}\n+// NDPSourceLinkLayerAddressOption is the NDP Source Link Layer Option\n+// as defined by RFC 4861 section 4.6.1.\n+//\n+// It is the first X bytes following the NDP option's Type and Length field\n+// where X is the value in Length multiplied by lengthByteUnits - 2 bytes.\n+type NDPSourceLinkLayerAddressOption tcpip.LinkAddress\n+\n+// Type implements NDPOption.Type.\n+func (o NDPSourceLinkLayerAddressOption) Type() uint8 {\n+ return NDPSourceLinkLayerAddressOptionType\n+}\n+\n+// Length implements NDPOption.Length.\n+func (o NDPSourceLinkLayerAddressOption) Length() int {\n+ return len(o)\n+}\n+\n+// serializeInto implements NDPOption.serializeInto.\n+func (o NDPSourceLinkLayerAddressOption) serializeInto(b []byte) int {\n+ return copy(b, o)\n+}\n+\n+// EthernetAddress will return an ethernet (MAC) address if the\n+// NDPSourceLinkLayerAddressOption's body has at minimum EthernetAddressSize\n+// bytes. If the body has more than EthernetAddressSize bytes, only the first\n+// EthernetAddressSize bytes are returned as that is all that is needed for an\n+// Ethernet address.\n+func (o NDPSourceLinkLayerAddressOption) EthernetAddress() tcpip.LinkAddress {\n+ if len(o) >= EthernetAddressSize {\n+ return tcpip.LinkAddress(o[:EthernetAddressSize])\n+ }\n+\n+ return tcpip.LinkAddress([]byte(nil))\n+}\n+\n// NDPTargetLinkLayerAddressOption is the NDP Target Link Layer Option\n// as defined by RFC 4861 section 4.6.1.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ndp_test.go", "new_path": "pkg/tcpip/header/ndp_test.go", "diff": "@@ -153,6 +153,125 @@ func TestNDPRouterAdvert(t *testing.T) {\n}\n}\n+// TestNDPSourceLinkLayerAddressOptionEthernetAddress tests getting the\n+// Ethernet address from an NDPSourceLinkLayerAddressOption.\n+func TestNDPSourceLinkLayerAddressOptionEthernetAddress(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ buf []byte\n+ expected tcpip.LinkAddress\n+ }{\n+ {\n+ \"ValidMAC\",\n+ []byte{1, 2, 3, 4, 5, 6},\n+ tcpip.LinkAddress(\"\\x01\\x02\\x03\\x04\\x05\\x06\"),\n+ },\n+ {\n+ \"SLLBodyTooShort\",\n+ []byte{1, 2, 3, 4, 5},\n+ tcpip.LinkAddress([]byte(nil)),\n+ },\n+ {\n+ \"SLLBodyLargerThanNeeded\",\n+ []byte{1, 2, 3, 4, 5, 6, 7, 8},\n+ tcpip.LinkAddress(\"\\x01\\x02\\x03\\x04\\x05\\x06\"),\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ sll := NDPSourceLinkLayerAddressOption(test.buf)\n+ if got := sll.EthernetAddress(); got != test.expected {\n+ t.Errorf(\"got sll.EthernetAddress = %s, want = %s\", got, test.expected)\n+ }\n+ })\n+ }\n+}\n+\n+// TestNDPSourceLinkLayerAddressOptionSerialize tests serializing a\n+// NDPSourceLinkLayerAddressOption.\n+func TestNDPSourceLinkLayerAddressOptionSerialize(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ buf []byte\n+ expectedBuf []byte\n+ addr tcpip.LinkAddress\n+ }{\n+ {\n+ \"Ethernet\",\n+ make([]byte, 8),\n+ []byte{1, 1, 1, 2, 3, 4, 5, 6},\n+ \"\\x01\\x02\\x03\\x04\\x05\\x06\",\n+ },\n+ {\n+ \"Padding\",\n+ []byte{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},\n+ []byte{1, 2, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0},\n+ \"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\",\n+ },\n+ {\n+ \"Empty\",\n+ nil,\n+ nil,\n+ \"\",\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ opts := NDPOptions(test.buf)\n+ serializer := NDPOptionsSerializer{\n+ NDPSourceLinkLayerAddressOption(test.addr),\n+ }\n+ if got, want := int(serializer.Length()), len(test.expectedBuf); got != want {\n+ t.Fatalf(\"got Length = %d, want = %d\", got, want)\n+ }\n+ opts.Serialize(serializer)\n+ if !bytes.Equal(test.buf, test.expectedBuf) {\n+ t.Fatalf(\"got b = %d, want = %d\", test.buf, test.expectedBuf)\n+ }\n+\n+ it, err := opts.Iter(true)\n+ if err != nil {\n+ t.Fatalf(\"got Iter = (_, %s), want = (_, nil)\", err)\n+ }\n+\n+ if len(test.expectedBuf) > 0 {\n+ next, done, err := it.Next()\n+ if err != nil {\n+ t.Fatalf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if done {\n+ t.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n+ }\n+ if got := next.Type(); got != NDPSourceLinkLayerAddressOptionType {\n+ t.Fatalf(\"got Type = %d, want = %d\", got, NDPSourceLinkLayerAddressOptionType)\n+ }\n+ sll := next.(NDPSourceLinkLayerAddressOption)\n+ if got, want := []byte(sll), test.expectedBuf[2:]; !bytes.Equal(got, want) {\n+ t.Fatalf(\"got Next = (%x, _, _), want = (%x, _, _)\", got, want)\n+ }\n+\n+ if got, want := sll.EthernetAddress(), tcpip.LinkAddress(test.expectedBuf[2:][:EthernetAddressSize]); got != want {\n+ t.Errorf(\"got sll.EthernetAddress = %s, want = %s\", got, want)\n+ }\n+ }\n+\n+ // Iterator should not return anything else.\n+ next, done, err := it.Next()\n+ if err != nil {\n+ t.Errorf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if !done {\n+ t.Error(\"got Next = (_, false, _), want = (_, true, _)\")\n+ }\n+ if next != nil {\n+ t.Errorf(\"got Next = (%x, _, _), want = (nil, _, _)\", next)\n+ }\n+ })\n+ }\n+}\n+\n// TestNDPTargetLinkLayerAddressOptionEthernetAddress tests getting the\n// Ethernet address from an NDPTargetLinkLayerAddressOption.\nfunc TestNDPTargetLinkLayerAddressOptionEthernetAddress(t *testing.T) {\n@@ -186,7 +305,6 @@ func TestNDPTargetLinkLayerAddressOptionEthernetAddress(t *testing.T) {\n}\n})\n}\n-\n}\n// TestNDPTargetLinkLayerAddressOptionSerialize tests serializing a\n@@ -212,8 +330,8 @@ func TestNDPTargetLinkLayerAddressOptionSerialize(t *testing.T) {\n},\n{\n\"Empty\",\n- []byte{},\n- []byte{},\n+ nil,\n+ nil,\n\"\",\n},\n}\n@@ -246,7 +364,7 @@ func TestNDPTargetLinkLayerAddressOptionSerialize(t *testing.T) {\nt.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n}\nif got := next.Type(); got != NDPTargetLinkLayerAddressOptionType {\n- t.Fatalf(\"got Type %= %d, want = %d\", got, NDPTargetLinkLayerAddressOptionType)\n+ t.Fatalf(\"got Type = %d, want = %d\", got, NDPTargetLinkLayerAddressOptionType)\n}\ntll := next.(NDPTargetLinkLayerAddressOption)\nif got, want := []byte(tll), test.expectedBuf[2:]; !bytes.Equal(got, want) {\n@@ -254,7 +372,7 @@ func TestNDPTargetLinkLayerAddressOptionSerialize(t *testing.T) {\n}\nif got, want := tll.EthernetAddress(), tcpip.LinkAddress(test.expectedBuf[2:][:EthernetAddressSize]); got != want {\n- t.Errorf(\"got tll.MACAddress = %s, want = %s\", got, want)\n+ t.Errorf(\"got tll.EthernetAddress = %s, want = %s\", got, want)\n}\n}\n@@ -510,7 +628,7 @@ func TestNDPRecursiveDNSServerOption(t *testing.T) {\nt.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n}\nif got := next.Type(); got != NDPRecursiveDNSServerOptionType {\n- t.Fatalf(\"got Type %= %d, want = %d\", got, NDPRecursiveDNSServerOptionType)\n+ t.Fatalf(\"got Type = %d, want = %d\", got, NDPRecursiveDNSServerOptionType)\n}\nopt, ok := next.(NDPRecursiveDNSServer)\n@@ -552,6 +670,16 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n[]byte{0, 0, 0, 0, 0, 0, 0, 0},\nErrNDPOptZeroLength,\n},\n+ {\n+ \"ValidSourceLinkLayerAddressOption\",\n+ []byte{1, 1, 1, 2, 3, 4, 5, 6},\n+ nil,\n+ },\n+ {\n+ \"TooSmallSourceLinkLayerAddressOption\",\n+ []byte{1, 1, 1, 2, 3, 4, 5},\n+ ErrNDPOptBufExhausted,\n+ },\n{\n\"ValidTargetLinkLayerAddressOption\",\n[]byte{2, 1, 1, 2, 3, 4, 5, 6},\n@@ -603,10 +731,13 @@ func TestNDPOptionsIterCheck(t *testing.T) {\nErrNDPOptMalformedBody,\n},\n{\n- \"ValidTargetLinkLayerAddressWithPrefixInformation\",\n+ \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformation\",\n[]byte{\n+ // Source Link-Layer Address.\n+ 1, 1, 1, 2, 3, 4, 5, 6,\n+\n// Target Link-Layer Address.\n- 2, 1, 1, 2, 3, 4, 5, 6,\n+ 2, 1, 7, 8, 9, 10, 11, 12,\n// Prefix information.\n3, 4, 43, 64,\n@@ -621,10 +752,13 @@ func TestNDPOptionsIterCheck(t *testing.T) {\nnil,\n},\n{\n- \"ValidTargetLinkLayerAddressWithPrefixInformationWithUnrecognized\",\n+ \"ValidSourceAndTargetLinkLayerAddressWithPrefixInformationWithUnrecognized\",\n[]byte{\n+ // Source Link-Layer Address.\n+ 1, 1, 1, 2, 3, 4, 5, 6,\n+\n// Target Link-Layer Address.\n- 2, 1, 1, 2, 3, 4, 5, 6,\n+ 2, 1, 7, 8, 9, 10, 11, 12,\n// 255 is an unrecognized type. If 255 ends up\n// being the type for some recognized type,\n@@ -714,8 +848,11 @@ func TestNDPOptionsIterCheck(t *testing.T) {\n// here.\nfunc TestNDPOptionsIter(t *testing.T) {\nbuf := []byte{\n+ // Source Link-Layer Address.\n+ 1, 1, 1, 2, 3, 4, 5, 6,\n+\n// Target Link-Layer Address.\n- 2, 1, 1, 2, 3, 4, 5, 6,\n+ 2, 1, 7, 8, 9, 10, 11, 12,\n// 255 is an unrecognized type. If 255 ends up being the type\n// for some recognized type, update 255 to some other\n@@ -740,7 +877,7 @@ func TestNDPOptionsIter(t *testing.T) {\nt.Fatalf(\"got Iter = (_, %s), want = (_, nil)\", err)\n}\n- // Test the first (Taret Link-Layer) option.\n+ // Test the first (Source Link-Layer) option.\nnext, done, err := it.Next()\nif err != nil {\nt.Fatalf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n@@ -748,7 +885,22 @@ func TestNDPOptionsIter(t *testing.T) {\nif done {\nt.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n}\n- if got, want := []byte(next.(NDPTargetLinkLayerAddressOption)), buf[2:][:6]; !bytes.Equal(got, want) {\n+ if got, want := []byte(next.(NDPSourceLinkLayerAddressOption)), buf[2:][:6]; !bytes.Equal(got, want) {\n+ t.Errorf(\"got Next = (%x, _, _), want = (%x, _, _)\", got, want)\n+ }\n+ if got := next.Type(); got != NDPSourceLinkLayerAddressOptionType {\n+ t.Errorf(\"got Type = %d, want = %d\", got, NDPSourceLinkLayerAddressOptionType)\n+ }\n+\n+ // Test the next (Target Link-Layer) option.\n+ next, done, err = it.Next()\n+ if err != nil {\n+ t.Fatalf(\"got Next = (_, _, %s), want = (_, _, nil)\", err)\n+ }\n+ if done {\n+ t.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n+ }\n+ if got, want := []byte(next.(NDPTargetLinkLayerAddressOption)), buf[10:][:6]; !bytes.Equal(got, want) {\nt.Errorf(\"got Next = (%x, _, _), want = (%x, _, _)\", got, want)\n}\nif got := next.Type(); got != NDPTargetLinkLayerAddressOptionType {\n@@ -764,7 +916,7 @@ func TestNDPOptionsIter(t *testing.T) {\nif done {\nt.Fatal(\"got Next = (_, true, _), want = (_, false, _)\")\n}\n- if got, want := next.(NDPPrefixInformation), buf[26:][:30]; !bytes.Equal(got, want) {\n+ if got, want := next.(NDPPrefixInformation), buf[34:][:30]; !bytes.Equal(got, want) {\nt.Errorf(\"got Next = (%x, _, _), want = (%x, _, _)\", got, want)\n}\nif got := next.Type(); got != NDPPrefixInformationType {\n" } ]
Go
Apache License 2.0
google/gvisor
Add a type to represent the NDP Source Link Layer Address option Tests: - header.TestNDPSourceLinkLayerAddressOptionEthernetAddress - header.TestNDPSourceLinkLayerAddressOptionSerialize - header.TestNDPOptionsIterCheck - header.TestNDPOptionsIter PiperOrigin-RevId: 291856429
259,858
27.01.2020 22:27:57
28,800
5d569408ef94c753b7aae9392b5e4ebf7e5ea50d
Create platform_util for tests.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/32bit.cc", "new_path": "test/syscalls/linux/32bit.cc", "diff": "#include <string.h>\n#include <sys/mman.h>\n+#include \"gtest/gtest.h\"\n+#include \"absl/base/macros.h\"\n#include \"test/util/memory_util.h\"\n+#include \"test/util/platform_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/test_util.h\"\n-#include \"gtest/gtest.h\"\n#ifndef __x86_64__\n#error \"This test is x86-64 specific.\"\n@@ -30,7 +32,6 @@ namespace testing {\nnamespace {\nconstexpr char kInt3 = '\\xcc';\n-\nconstexpr char kInt80[2] = {'\\xcd', '\\x80'};\nconstexpr char kSyscall[2] = {'\\x0f', '\\x05'};\nconstexpr char kSysenter[2] = {'\\x0f', '\\x34'};\n@@ -43,6 +44,7 @@ void ExitGroup32(const char instruction[2], int code) {\n// Fill with INT 3 in case we execute too far.\nmemset(m.ptr(), kInt3, m.len());\n+ // Copy in the actual instruction.\nmemcpy(m.ptr(), instruction, 2);\n// We're playing *extremely* fast-and-loose with the various syscall ABIs\n@@ -78,70 +80,87 @@ void ExitGroup32(const char instruction[2], int code) {\nconstexpr int kExitCode = 42;\nTEST(Syscall32Bit, Int80) {\n- switch (GvisorPlatform()) {\n- case Platform::kKVM:\n- // TODO(b/111805002): 32-bit segments are broken (but not explictly\n- // disabled).\n- return;\n- case Platform::kPtrace:\n- // TODO(gvisor.dev/issue/167): The ptrace platform does not have a\n- // consistent story here.\n- return;\n- case Platform::kNative:\n+ switch (PlatformSupport32Bit()) {\n+ case PlatformSupport::NotSupported:\n+ break;\n+ case PlatformSupport::Segfault:\n+ EXPECT_EXIT(ExitGroup32(kInt80, kExitCode),\n+ ::testing::KilledBySignal(SIGSEGV), \"\");\nbreak;\n- }\n- // Upstream Linux. 32-bit syscalls allowed.\n+ case PlatformSupport::Ignored:\n+ // Since the call is ignored, we'll hit the int3 trap.\n+ EXPECT_EXIT(ExitGroup32(kInt80, kExitCode),\n+ ::testing::KilledBySignal(SIGTRAP), \"\");\n+ break;\n+\n+ case PlatformSupport::Allowed:\nEXPECT_EXIT(ExitGroup32(kInt80, kExitCode), ::testing::ExitedWithCode(42),\n\"\");\n-}\n-\n-TEST(Syscall32Bit, Sysenter) {\n- switch (GvisorPlatform()) {\n- case Platform::kKVM:\n- // TODO(b/111805002): See above.\n- return;\n- case Platform::kPtrace:\n- // TODO(gvisor.dev/issue/167): See above.\n- return;\n- case Platform::kNative:\nbreak;\n}\n+}\n- if (GetCPUVendor() == CPUVendor::kAMD) {\n+TEST(Syscall32Bit, Sysenter) {\n+ if (PlatformSupport32Bit() == PlatformSupport::Allowed &&\n+ GetCPUVendor() == CPUVendor::kAMD) {\n// SYSENTER is an illegal instruction in compatibility mode on AMD.\nEXPECT_EXIT(ExitGroup32(kSysenter, kExitCode),\n::testing::KilledBySignal(SIGILL), \"\");\nreturn;\n}\n- // Upstream Linux on !AMD, 32-bit syscalls allowed.\n- EXPECT_EXIT(ExitGroup32(kSysenter, kExitCode), ::testing::ExitedWithCode(42),\n- \"\");\n-}\n+ switch (PlatformSupport32Bit()) {\n+ case PlatformSupport::NotSupported:\n+ break;\n-TEST(Syscall32Bit, Syscall) {\n- switch (GvisorPlatform()) {\n- case Platform::kKVM:\n- // TODO(b/111805002): See above.\n- return;\n- case Platform::kPtrace:\n- // TODO(gvisor.dev/issue/167): See above.\n- return;\n- case Platform::kNative:\n+ case PlatformSupport::Segfault:\n+ EXPECT_EXIT(ExitGroup32(kSysenter, kExitCode),\n+ ::testing::KilledBySignal(SIGSEGV), \"\");\n+ break;\n+\n+ case PlatformSupport::Ignored:\n+ // See above, except expected code is SIGSEGV.\n+ EXPECT_EXIT(ExitGroup32(kSysenter, kExitCode),\n+ ::testing::KilledBySignal(SIGSEGV), \"\");\nbreak;\n+\n+ case PlatformSupport::Allowed:\n+ EXPECT_EXIT(ExitGroup32(kSysenter, kExitCode),\n+ ::testing::ExitedWithCode(42), \"\");\n+ break;\n+ }\n}\n- if (GetCPUVendor() == CPUVendor::kIntel) {\n+TEST(Syscall32Bit, Syscall) {\n+ if (PlatformSupport32Bit() == PlatformSupport::Allowed &&\n+ GetCPUVendor() == CPUVendor::kIntel) {\n// SYSCALL is an illegal instruction in compatibility mode on Intel.\nEXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n::testing::KilledBySignal(SIGILL), \"\");\nreturn;\n}\n- // Upstream Linux on !Intel, 32-bit syscalls allowed.\n- EXPECT_EXIT(ExitGroup32(kSyscall, kExitCode), ::testing::ExitedWithCode(42),\n- \"\");\n+ switch (PlatformSupport32Bit()) {\n+ case PlatformSupport::NotSupported:\n+ break;\n+\n+ case PlatformSupport::Segfault:\n+ EXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n+ ::testing::KilledBySignal(SIGSEGV), \"\");\n+ break;\n+\n+ case PlatformSupport::Ignored:\n+ // See above.\n+ EXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n+ ::testing::KilledBySignal(SIGILL), \"\");\n+ break;\n+\n+ case PlatformSupport::Allowed:\n+ EXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n+ ::testing::ExitedWithCode(42), \"\");\n+ break;\n+ }\n}\n// Far call code called below.\n@@ -205,20 +224,21 @@ void FarCall32() {\n}\nTEST(Call32Bit, Disallowed) {\n- switch (GvisorPlatform()) {\n- case Platform::kKVM:\n- // TODO(b/111805002): See above.\n- return;\n- case Platform::kPtrace:\n- // The ptrace platform cannot prevent switching to compatibility mode.\n- ABSL_FALLTHROUGH_INTENDED;\n- case Platform::kNative:\n+ switch (PlatformSupport32Bit()) {\n+ case PlatformSupport::NotSupported:\n+ break;\n+\n+ case PlatformSupport::Segfault:\n+ EXPECT_EXIT(FarCall32(), ::testing::KilledBySignal(SIGSEGV), \"\");\nbreak;\n- }\n+ case PlatformSupport::Ignored:\n+ ABSL_FALLTHROUGH_INTENDED;\n+ case PlatformSupport::Allowed:\n// Shouldn't crash.\nFarCall32();\n}\n+}\n} // namespace\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -197,9 +197,11 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\"//test/util:memory_util\",\n+ \"//test/util:platform_util\",\n\"//test/util:posix_error\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n+ \"@com_google_absl//absl/base:core_headers\",\n\"@com_google_googletest//:gtest\",\n],\n)\n@@ -479,6 +481,7 @@ cc_binary(\nsrcs = [\"concurrency.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:platform_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n@@ -584,6 +587,7 @@ cc_binary(\nlinkstatic = 1,\ndeps = [\n\"//test/util:logging\",\n+ \"//test/util:platform_util\",\n\"//test/util:signal_util\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n@@ -1658,6 +1662,7 @@ cc_binary(\ndeps = [\n\"//test/util:logging\",\n\"//test/util:multiprocess_util\",\n+ \"//test/util:platform_util\",\n\"//test/util:signal_util\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/arch_prctl.cc", "new_path": "test/syscalls/linux/arch_prctl.cc", "diff": "#include <asm/prctl.h>\n#include <sys/prctl.h>\n-#include <sys/syscall.h>\n#include \"gtest/gtest.h\"\n-#include \"test/util/file_descriptor.h\"\n#include \"test/util/test_util.h\"\n// glibc does not provide a prototype for arch_prctl() so declare it here.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/concurrency.cc", "new_path": "test/syscalls/linux/concurrency.cc", "diff": "#include \"absl/strings/string_view.h\"\n#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n+#include \"test/util/platform_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -99,6 +100,7 @@ TEST(ConcurrencyTest, MultiProcessMultithreaded) {\n// Test that multiple processes can execute concurrently, even if one process\n// never yields.\nTEST(ConcurrencyTest, MultiProcessConcurrency) {\n+ SKIP_IF(PlatformSupportMultiProcess() == PlatformSupport::NotSupported);\npid_t child_pid = fork();\nif (child_pid == 0) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/exceptions.cc", "new_path": "test/syscalls/linux/exceptions.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"test/util/logging.h\"\n+#include \"test/util/platform_util.h\"\n#include \"test/util/signal_util.h\"\n#include \"test/util/test_util.h\"\n@@ -324,6 +325,7 @@ TEST(ExceptionTest, AlignmentHalt) {\n}\nTEST(ExceptionTest, AlignmentCheck) {\n+ SKIP_IF(PlatformSupportAlignmentCheck() != PlatformSupport::Allowed);\n// See above.\nstruct sigaction sa = {};\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ptrace.cc", "new_path": "test/syscalls/linux/ptrace.cc", "diff": "#include \"absl/time/time.h\"\n#include \"test/util/logging.h\"\n#include \"test/util/multiprocess_util.h\"\n+#include \"test/util/platform_util.h\"\n#include \"test/util/signal_util.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -824,13 +825,8 @@ TEST(PtraceTest,\n// These tests requires knowledge of architecture-specific syscall convention.\n#ifdef __x86_64__\nTEST(PtraceTest, Int3) {\n- switch (GvisorPlatform()) {\n- case Platform::kKVM:\n- // TODO(b/124248694): int3 isn't handled properly.\n- return;\n- default:\n- break;\n- }\n+ SKIP_IF(PlatformSupportInt3() == PlatformSupport::NotSupported);\n+\npid_t const child_pid = fork();\nif (child_pid == 0) {\n// In child process.\n" }, { "change_type": "MODIFY", "old_path": "test/util/BUILD", "new_path": "test/util/BUILD", "diff": "@@ -165,6 +165,14 @@ cc_library(\n],\n)\n+cc_library(\n+ name = \"platform_util\",\n+ testonly = 1,\n+ srcs = [\"platform_util.cc\"],\n+ hdrs = [\"platform_util.h\"],\n+ deps = [\":test_util\"],\n+)\n+\ncc_library(\nname = \"posix_error\",\ntestonly = 1,\n@@ -238,12 +246,7 @@ cc_library(\n\"test_util_runfiles.cc\",\n],\nhdrs = [\"test_util.h\"],\n- defines = select_system(\n- fuchsia = [\n- \"__opensource__\",\n- \"__fuchsia__\",\n- ],\n- ),\n+ defines = select_system(),\ndeps = [\n\":fs_util\",\n\":logging\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/platform_util.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/util/platform_util.h\"\n+\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+PlatformSupport PlatformSupport32Bit() {\n+ if (GvisorPlatform() == Platform::kPtrace) {\n+ return PlatformSupport::NotSupported;\n+ } else if (GvisorPlatform() == Platform::kKVM) {\n+ return PlatformSupport::Segfault;\n+ } else {\n+ return PlatformSupport::Allowed;\n+ }\n+}\n+\n+PlatformSupport PlatformSupportAlignmentCheck() {\n+ return PlatformSupport::Allowed;\n+}\n+\n+PlatformSupport PlatformSupportMultiProcess() {\n+ return PlatformSupport::Allowed;\n+}\n+\n+PlatformSupport PlatformSupportInt3() {\n+ if (GvisorPlatform() == Platform::kKVM) {\n+ return PlatformSupport::NotSupported;\n+ } else {\n+ return PlatformSupport::Allowed;\n+ }\n+}\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/util/platform_util.h", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#ifndef GVISOR_TEST_UTIL_PLATFORM_UTIL_H_\n+#define GVISOR_TEST_UTIL_PLATFORM_UTIL_H_\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// PlatformSupport is a generic enumeration of classes of support.\n+//\n+// It is up to the individual functions and callers to agree on the precise\n+// definition for each case. The document here generally refers to 32-bit\n+// as an example. Many cases will use only NotSupported and Allowed.\n+enum class PlatformSupport {\n+ // The feature is not supported on the current platform.\n+ //\n+ // In the case of 32-bit, this means that calls will generally be interpreted\n+ // as 64-bit calls, and there is no support for 32-bit binaries, long calls,\n+ // etc. This usually means that the underlying implementation just pretends\n+ // that 32-bit doesn't exist.\n+ NotSupported,\n+\n+ // Calls will be ignored by the kernel with a fixed error.\n+ Ignored,\n+\n+ // Calls will result in a SIGSEGV or similar fault.\n+ Segfault,\n+\n+ // The feature is supported as expected.\n+ //\n+ // In the case of 32-bit, this means that the system call or far call will be\n+ // handled properly.\n+ Allowed,\n+};\n+\n+PlatformSupport PlatformSupport32Bit();\n+PlatformSupport PlatformSupportAlignmentCheck();\n+PlatformSupport PlatformSupportMultiProcess();\n+PlatformSupport PlatformSupportInt3();\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n+#endif // GVISOR_TEST_UTIL_PLATFORM_UTL_H_\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.cc", "new_path": "test/util/test_util.cc", "diff": "@@ -45,20 +45,13 @@ namespace testing {\nbool IsRunningOnGvisor() { return GvisorPlatform() != Platform::kNative; }\n-Platform GvisorPlatform() {\n+const std::string GvisorPlatform() {\n// Set by runner.go.\nchar* env = getenv(TEST_ON_GVISOR);\nif (!env) {\nreturn Platform::kNative;\n}\n- if (strcmp(env, \"ptrace\") == 0) {\n- return Platform::kPtrace;\n- }\n- if (strcmp(env, \"kvm\") == 0) {\n- return Platform::kKVM;\n- }\n- std::cerr << \"unknown platform \" << env;\n- abort();\n+ return std::string(env);\n}\nbool IsRunningWithHostinet() {\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.h", "new_path": "test/util/test_util.h", "diff": "// IsRunningOnGvisor returns true if the test is known to be running on gVisor.\n// GvisorPlatform can be used to get more detail:\n//\n-// switch (GvisorPlatform()) {\n-// case Platform::kNative:\n-// case Platform::kGvisor:\n-// EXPECT_THAT(mmap(...), SyscallSucceeds());\n-// break;\n-// case Platform::kPtrace:\n-// EXPECT_THAT(mmap(...), SyscallFailsWithErrno(ENOSYS));\n-// break;\n+// if (GvisorPlatform() == Platform::kPtrace) {\n+// ...\n// }\n//\n+// SetupGvisorDeathTest ensures that signal handling does not interfere with\n+/// tests that rely on fatal signals.\n+//\n// Matchers\n// ========\n//\n@@ -213,13 +210,15 @@ void TestInit(int* argc, char*** argv);\nif (expr) GTEST_SKIP() << #expr; \\\n} while (0)\n-enum class Platform {\n- kNative,\n- kKVM,\n- kPtrace,\n-};\n+// Platform contains platform names.\n+namespace Platform {\n+constexpr char kNative[] = \"native\";\n+constexpr char kPtrace[] = \"ptrace\";\n+constexpr char kKVM[] = \"kvm\";\n+} // namespace Platform\n+\nbool IsRunningOnGvisor();\n-Platform GvisorPlatform();\n+const std::string GvisorPlatform();\nbool IsRunningWithHostinet();\n#ifdef __linux__\n" } ]
Go
Apache License 2.0
google/gvisor
Create platform_util for tests. PiperOrigin-RevId: 291869423
259,881
28.01.2020 11:12:01
28,800
76483b8b1ec4ee1fb6b6efb6bdcfaf6dba7be4ce
Check sigsetsize in rt_sigaction This isn't in the libc wrapper, but it is in the syscall itself. Discovered by in
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_amd64.go", "new_path": "pkg/sentry/strace/linux64_amd64.go", "diff": "@@ -37,7 +37,7 @@ var linuxAMD64 = SyscallMap{\n10: makeSyscallInfo(\"mprotect\", Hex, Hex, Hex),\n11: makeSyscallInfo(\"munmap\", Hex, Hex),\n12: makeSyscallInfo(\"brk\", Hex),\n- 13: makeSyscallInfo(\"rt_sigaction\", Signal, SigAction, PostSigAction),\n+ 13: makeSyscallInfo(\"rt_sigaction\", Signal, SigAction, PostSigAction, Hex),\n14: makeSyscallInfo(\"rt_sigprocmask\", SignalMaskAction, SigSet, PostSigSet, Hex),\n15: makeSyscallInfo(\"rt_sigreturn\"),\n16: makeSyscallInfo(\"ioctl\", FD, Hex, Hex),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_arm64.go", "new_path": "pkg/sentry/strace/linux64_arm64.go", "diff": "@@ -158,7 +158,7 @@ var linuxARM64 = SyscallMap{\n131: makeSyscallInfo(\"tgkill\", Hex, Hex, Signal),\n132: makeSyscallInfo(\"sigaltstack\", Hex, Hex),\n133: makeSyscallInfo(\"rt_sigsuspend\", Hex),\n- 134: makeSyscallInfo(\"rt_sigaction\", Signal, SigAction, PostSigAction),\n+ 134: makeSyscallInfo(\"rt_sigaction\", Signal, SigAction, PostSigAction, Hex),\n135: makeSyscallInfo(\"rt_sigprocmask\", SignalMaskAction, SigSet, PostSigSet, Hex),\n136: makeSyscallInfo(\"rt_sigpending\", Hex),\n137: makeSyscallInfo(\"rt_sigtimedwait\", SigSet, Hex, Timespec, Hex),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_signal.go", "new_path": "pkg/sentry/syscalls/linux/sys_signal.go", "diff": "@@ -245,6 +245,11 @@ func RtSigaction(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nsig := linux.Signal(args[0].Int())\nnewactarg := args[1].Pointer()\noldactarg := args[2].Pointer()\n+ sigsetsize := args[3].SizeT()\n+\n+ if sigsetsize != linux.SignalSetSize {\n+ return 0, nil, syserror.EINVAL\n+ }\nvar newactptr *arch.SignalAct\nif newactarg != 0 {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/sigaction.cc", "new_path": "test/syscalls/linux/sigaction.cc", "diff": "// limitations under the License.\n#include <signal.h>\n+#include <sys/syscall.h>\n#include \"gtest/gtest.h\"\n#include \"test/util/test_util.h\"\n@@ -23,45 +24,53 @@ namespace testing {\nnamespace {\nTEST(SigactionTest, GetLessThanOrEqualToZeroFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(-1, NULL, &act), SyscallFailsWithErrno(EINVAL));\n- ASSERT_THAT(sigaction(0, NULL, &act), SyscallFailsWithErrno(EINVAL));\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(-1, nullptr, &act), SyscallFailsWithErrno(EINVAL));\n+ ASSERT_THAT(sigaction(0, nullptr, &act), SyscallFailsWithErrno(EINVAL));\n}\nTEST(SigactionTest, SetLessThanOrEqualToZeroFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(0, &act, NULL), SyscallFailsWithErrno(EINVAL));\n- ASSERT_THAT(sigaction(0, &act, NULL), SyscallFailsWithErrno(EINVAL));\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(0, &act, nullptr), SyscallFailsWithErrno(EINVAL));\n+ ASSERT_THAT(sigaction(0, &act, nullptr), SyscallFailsWithErrno(EINVAL));\n}\nTEST(SigactionTest, GetGreaterThanMaxFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(SIGRTMAX + 1, NULL, &act),\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(SIGRTMAX + 1, nullptr, &act),\nSyscallFailsWithErrno(EINVAL));\n}\nTEST(SigactionTest, SetGreaterThanMaxFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(SIGRTMAX + 1, &act, NULL),\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(SIGRTMAX + 1, &act, nullptr),\nSyscallFailsWithErrno(EINVAL));\n}\nTEST(SigactionTest, SetSigkillFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(SIGKILL, NULL, &act), SyscallSucceeds());\n- ASSERT_THAT(sigaction(SIGKILL, &act, NULL), SyscallFailsWithErrno(EINVAL));\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(SIGKILL, nullptr, &act), SyscallSucceeds());\n+ ASSERT_THAT(sigaction(SIGKILL, &act, nullptr), SyscallFailsWithErrno(EINVAL));\n}\nTEST(SigactionTest, SetSigstopFails) {\n- struct sigaction act;\n- memset(&act, 0, sizeof(act));\n- ASSERT_THAT(sigaction(SIGSTOP, NULL, &act), SyscallSucceeds());\n- ASSERT_THAT(sigaction(SIGSTOP, &act, NULL), SyscallFailsWithErrno(EINVAL));\n+ struct sigaction act = {};\n+ ASSERT_THAT(sigaction(SIGSTOP, nullptr, &act), SyscallSucceeds());\n+ ASSERT_THAT(sigaction(SIGSTOP, &act, nullptr), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(SigactionTest, BadSigsetFails) {\n+ constexpr size_t kWrongSigSetSize = 43;\n+\n+ struct sigaction act = {};\n+\n+ // The syscall itself (rather than the libc wrapper) takes the sigset_t size.\n+ ASSERT_THAT(\n+ syscall(SYS_rt_sigaction, SIGTERM, nullptr, &act, kWrongSigSetSize),\n+ SyscallFailsWithErrno(EINVAL));\n+ ASSERT_THAT(\n+ syscall(SYS_rt_sigaction, SIGTERM, &act, nullptr, kWrongSigSetSize),\n+ SyscallFailsWithErrno(EINVAL));\n}\n} // namespace\n" } ]
Go
Apache License 2.0
google/gvisor
Check sigsetsize in rt_sigaction This isn't in the libc wrapper, but it is in the syscall itself. Discovered by @xiaobo55x in #1625. PiperOrigin-RevId: 291973931
259,885
28.01.2020 12:06:58
28,800
1119644080ae57c206b9b0d8d127cf48423af7f2
Implement an anon_inode equivalent for VFS2.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/BUILD", "new_path": "pkg/sentry/vfs/BUILD", "diff": "@@ -5,6 +5,7 @@ licenses([\"notice\"])\ngo_library(\nname = \"vfs\",\nsrcs = [\n+ \"anonfs.go\",\n\"context.go\",\n\"debug.go\",\n\"dentry.go\",\n@@ -20,7 +21,6 @@ go_library(\n\"pathname.go\",\n\"permissions.go\",\n\"resolving_path.go\",\n- \"testutil.go\",\n\"vfs.go\",\n],\nvisibility = [\"//pkg/sentry:internal\"],\n@@ -50,7 +50,6 @@ go_test(\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/sentry/contexttest\",\n- \"//pkg/sentry/kernel/auth\",\n\"//pkg/sync\",\n\"//pkg/syserror\",\n\"//pkg/usermem\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/vfs/anonfs.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package vfs\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// NewAnonVirtualDentry returns a VirtualDentry with the given synthetic name,\n+// consistent with Linux's fs/anon_inodes.c:anon_inode_getfile(). References\n+// are taken on the returned VirtualDentry.\n+func (vfs *VirtualFilesystem) NewAnonVirtualDentry(name string) VirtualDentry {\n+ d := anonDentry{\n+ name: name,\n+ }\n+ d.vfsd.Init(&d)\n+ vfs.anonMount.IncRef()\n+ // anonDentry no-ops refcounting.\n+ return VirtualDentry{\n+ mount: vfs.anonMount,\n+ dentry: &d.vfsd,\n+ }\n+}\n+\n+const anonfsBlockSize = usermem.PageSize // via fs/libfs.c:pseudo_fs_fill_super()\n+\n+// anonFilesystem is the implementation of FilesystemImpl that backs\n+// VirtualDentries returned by VirtualFilesystem.NewAnonVirtualDentry().\n+//\n+// Since all Dentries in anonFilesystem are non-directories, all FilesystemImpl\n+// methods that would require an anonDentry to be a directory return ENOTDIR.\n+type anonFilesystem struct {\n+ vfsfs Filesystem\n+\n+ devMinor uint32\n+}\n+\n+type anonDentry struct {\n+ vfsd Dentry\n+\n+ name string\n+}\n+\n+// Release implements FilesystemImpl.Release.\n+func (fs *anonFilesystem) Release() {\n+}\n+\n+// Sync implements FilesystemImpl.Sync.\n+func (fs *anonFilesystem) Sync(ctx context.Context) error {\n+ return nil\n+}\n+\n+// GetDentryAt implements FilesystemImpl.GetDentryAt.\n+func (fs *anonFilesystem) GetDentryAt(ctx context.Context, rp *ResolvingPath, opts GetDentryOptions) (*Dentry, error) {\n+ if !rp.Done() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ if opts.CheckSearchable {\n+ return nil, syserror.ENOTDIR\n+ }\n+ // anonDentry no-ops refcounting.\n+ return rp.Start(), nil\n+}\n+\n+// GetParentDentryAt implements FilesystemImpl.GetParentDentryAt.\n+func (fs *anonFilesystem) GetParentDentryAt(ctx context.Context, rp *ResolvingPath) (*Dentry, error) {\n+ if !rp.Final() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ // anonDentry no-ops refcounting.\n+ return rp.Start(), nil\n+}\n+\n+// LinkAt implements FilesystemImpl.LinkAt.\n+func (fs *anonFilesystem) LinkAt(ctx context.Context, rp *ResolvingPath, vd VirtualDentry) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// MkdirAt implements FilesystemImpl.MkdirAt.\n+func (fs *anonFilesystem) MkdirAt(ctx context.Context, rp *ResolvingPath, opts MkdirOptions) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// MknodAt implements FilesystemImpl.MknodAt.\n+func (fs *anonFilesystem) MknodAt(ctx context.Context, rp *ResolvingPath, opts MknodOptions) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// OpenAt implements FilesystemImpl.OpenAt.\n+func (fs *anonFilesystem) OpenAt(ctx context.Context, rp *ResolvingPath, opts OpenOptions) (*FileDescription, error) {\n+ if !rp.Done() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ return nil, syserror.ENODEV\n+}\n+\n+// ReadlinkAt implements FilesystemImpl.ReadlinkAt.\n+func (fs *anonFilesystem) ReadlinkAt(ctx context.Context, rp *ResolvingPath) (string, error) {\n+ if !rp.Done() {\n+ return \"\", syserror.ENOTDIR\n+ }\n+ return \"\", syserror.EINVAL\n+}\n+\n+// RenameAt implements FilesystemImpl.RenameAt.\n+func (fs *anonFilesystem) RenameAt(ctx context.Context, rp *ResolvingPath, oldParentVD VirtualDentry, oldName string, opts RenameOptions) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// RmdirAt implements FilesystemImpl.RmdirAt.\n+func (fs *anonFilesystem) RmdirAt(ctx context.Context, rp *ResolvingPath) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// SetStatAt implements FilesystemImpl.SetStatAt.\n+func (fs *anonFilesystem) SetStatAt(ctx context.Context, rp *ResolvingPath, opts SetStatOptions) error {\n+ if !rp.Done() {\n+ return syserror.ENOTDIR\n+ }\n+ // Linux actually permits anon_inode_inode's metadata to be set, which is\n+ // visible to all users of anon_inode_inode. We just silently ignore\n+ // metadata changes.\n+ return nil\n+}\n+\n+// StatAt implements FilesystemImpl.StatAt.\n+func (fs *anonFilesystem) StatAt(ctx context.Context, rp *ResolvingPath, opts StatOptions) (linux.Statx, error) {\n+ if !rp.Done() {\n+ return linux.Statx{}, syserror.ENOTDIR\n+ }\n+ // See fs/anon_inodes.c:anon_inode_init() => fs/libfs.c:alloc_anon_inode().\n+ return linux.Statx{\n+ Mask: linux.STATX_TYPE | linux.STATX_MODE | linux.STATX_NLINK | linux.STATX_UID | linux.STATX_GID | linux.STATX_INO | linux.STATX_SIZE | linux.STATX_BLOCKS,\n+ Blksize: anonfsBlockSize,\n+ Nlink: 1,\n+ UID: uint32(auth.RootKUID),\n+ GID: uint32(auth.RootKGID),\n+ Mode: 0600, // no type is correct\n+ Ino: 1,\n+ Size: 0,\n+ Blocks: 0,\n+ DevMajor: 0,\n+ DevMinor: fs.devMinor,\n+ }, nil\n+}\n+\n+// StatFSAt implements FilesystemImpl.StatFSAt.\n+func (fs *anonFilesystem) StatFSAt(ctx context.Context, rp *ResolvingPath) (linux.Statfs, error) {\n+ if !rp.Done() {\n+ return linux.Statfs{}, syserror.ENOTDIR\n+ }\n+ return linux.Statfs{\n+ Type: linux.ANON_INODE_FS_MAGIC,\n+ BlockSize: anonfsBlockSize,\n+ }, nil\n+}\n+\n+// SymlinkAt implements FilesystemImpl.SymlinkAt.\n+func (fs *anonFilesystem) SymlinkAt(ctx context.Context, rp *ResolvingPath, target string) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// UnlinkAt implements FilesystemImpl.UnlinkAt.\n+func (fs *anonFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) error {\n+ if !rp.Final() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// ListxattrAt implements FilesystemImpl.ListxattrAt.\n+func (fs *anonFilesystem) ListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error) {\n+ if !rp.Done() {\n+ return nil, syserror.ENOTDIR\n+ }\n+ return nil, nil\n+}\n+\n+// GetxattrAt implements FilesystemImpl.GetxattrAt.\n+func (fs *anonFilesystem) GetxattrAt(ctx context.Context, rp *ResolvingPath, name string) (string, error) {\n+ if !rp.Done() {\n+ return \"\", syserror.ENOTDIR\n+ }\n+ return \"\", syserror.ENOTSUP\n+}\n+\n+// SetxattrAt implements FilesystemImpl.SetxattrAt.\n+func (fs *anonFilesystem) SetxattrAt(ctx context.Context, rp *ResolvingPath, opts SetxattrOptions) error {\n+ if !rp.Done() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// RemovexattrAt implements FilesystemImpl.RemovexattrAt.\n+func (fs *anonFilesystem) RemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error {\n+ if !rp.Done() {\n+ return syserror.ENOTDIR\n+ }\n+ return syserror.EPERM\n+}\n+\n+// PrependPath implements FilesystemImpl.PrependPath.\n+func (fs *anonFilesystem) PrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error {\n+ b.PrependComponent(fmt.Sprintf(\"anon_inode:%s\", vd.dentry.impl.(*anonDentry).name))\n+ return PrependPathSyntheticError{}\n+}\n+\n+// IncRef implements DentryImpl.IncRef.\n+func (d *anonDentry) IncRef() {\n+ // no-op\n+}\n+\n+// TryIncRef implements DentryImpl.TryIncRef.\n+func (d *anonDentry) TryIncRef() bool {\n+ return true\n+}\n+\n+// DecRef implements DentryImpl.DecRef.\n+func (d *anonDentry) DecRef() {\n+ // no-op\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "new_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n- \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -46,9 +45,11 @@ type genCountFD struct {\ncount uint64 // accessed using atomic memory ops\n}\n-func newGenCountFD(mnt *Mount, vfsd *Dentry) *FileDescription {\n+func newGenCountFD(vfsObj *VirtualFilesystem) *FileDescription {\n+ vd := vfsObj.NewAnonVirtualDentry(\"genCountFD\")\n+ defer vd.DecRef()\nvar fd genCountFD\n- fd.vfsfd.Init(&fd, 0 /* statusFlags */, mnt, vfsd, &FileDescriptionOptions{})\n+ fd.vfsfd.Init(&fd, 0 /* statusFlags */, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{})\nfd.DynamicBytesFileDescriptionImpl.SetDataSource(&fd)\nreturn &fd.vfsfd\n}\n@@ -86,18 +87,9 @@ func (fd *genCountFD) Generate(ctx context.Context, buf *bytes.Buffer) error {\nfunc TestGenCountFD(t *testing.T) {\nctx := contexttest.Context(t)\n- creds := auth.CredentialsFromContext(ctx)\nvfsObj := New() // vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"testfs\", FDTestFilesystemType{}, &RegisterFilesystemTypeOptions{})\n- mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"testfs\", &GetFilesystemOptions{})\n- if err != nil {\n- t.Fatalf(\"failed to create testfs root mount: %v\", err)\n- }\n- vd := mntns.Root()\n- defer vd.DecRef()\n-\n- fd := newGenCountFD(vd.Mount(), vd.Dentry())\n+ fd := newGenCountFD(vfsObj)\ndefer fd.DecRef()\n// The first read causes Generate to be called to fill the FD's buffer.\n" }, { "change_type": "DELETE", "old_path": "pkg/sentry/vfs/testutil.go", "new_path": null, "diff": "-// Copyright 2019 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 vfs\n-\n-import (\n- \"fmt\"\n-\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/fspath\"\n- \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n- \"gvisor.dev/gvisor/pkg/syserror\"\n-)\n-\n-// FDTestFilesystemType is a test-only FilesystemType that produces Filesystems\n-// for which all FilesystemImpl methods taking a path return EPERM. It is used\n-// to produce Mounts and Dentries for testing of FileDescriptionImpls that do\n-// not depend on their originating Filesystem.\n-type FDTestFilesystemType struct{}\n-\n-// FDTestFilesystem is a test-only FilesystemImpl produced by\n-// FDTestFilesystemType.\n-type FDTestFilesystem struct {\n- vfsfs Filesystem\n-}\n-\n-// GetFilesystem implements FilesystemType.GetFilesystem.\n-func (fstype FDTestFilesystemType) GetFilesystem(ctx context.Context, vfsObj *VirtualFilesystem, creds *auth.Credentials, source string, opts GetFilesystemOptions) (*Filesystem, *Dentry, error) {\n- var fs FDTestFilesystem\n- fs.vfsfs.Init(vfsObj, &fs)\n- return &fs.vfsfs, fs.NewDentry(), nil\n-}\n-\n-// Release implements FilesystemImpl.Release.\n-func (fs *FDTestFilesystem) Release() {\n-}\n-\n-// Sync implements FilesystemImpl.Sync.\n-func (fs *FDTestFilesystem) Sync(ctx context.Context) error {\n- return nil\n-}\n-\n-// GetDentryAt implements FilesystemImpl.GetDentryAt.\n-func (fs *FDTestFilesystem) GetDentryAt(ctx context.Context, rp *ResolvingPath, opts GetDentryOptions) (*Dentry, error) {\n- return nil, syserror.EPERM\n-}\n-\n-// GetParentDentryAt implements FilesystemImpl.GetParentDentryAt.\n-func (fs *FDTestFilesystem) GetParentDentryAt(ctx context.Context, rp *ResolvingPath) (*Dentry, error) {\n- return nil, syserror.EPERM\n-}\n-\n-// LinkAt implements FilesystemImpl.LinkAt.\n-func (fs *FDTestFilesystem) LinkAt(ctx context.Context, rp *ResolvingPath, vd VirtualDentry) error {\n- return syserror.EPERM\n-}\n-\n-// MkdirAt implements FilesystemImpl.MkdirAt.\n-func (fs *FDTestFilesystem) MkdirAt(ctx context.Context, rp *ResolvingPath, opts MkdirOptions) error {\n- return syserror.EPERM\n-}\n-\n-// MknodAt implements FilesystemImpl.MknodAt.\n-func (fs *FDTestFilesystem) MknodAt(ctx context.Context, rp *ResolvingPath, opts MknodOptions) error {\n- return syserror.EPERM\n-}\n-\n-// OpenAt implements FilesystemImpl.OpenAt.\n-func (fs *FDTestFilesystem) OpenAt(ctx context.Context, rp *ResolvingPath, opts OpenOptions) (*FileDescription, error) {\n- return nil, syserror.EPERM\n-}\n-\n-// ReadlinkAt implements FilesystemImpl.ReadlinkAt.\n-func (fs *FDTestFilesystem) ReadlinkAt(ctx context.Context, rp *ResolvingPath) (string, error) {\n- return \"\", syserror.EPERM\n-}\n-\n-// RenameAt implements FilesystemImpl.RenameAt.\n-func (fs *FDTestFilesystem) RenameAt(ctx context.Context, rp *ResolvingPath, oldParentVD VirtualDentry, oldName string, opts RenameOptions) error {\n- return syserror.EPERM\n-}\n-\n-// RmdirAt implements FilesystemImpl.RmdirAt.\n-func (fs *FDTestFilesystem) RmdirAt(ctx context.Context, rp *ResolvingPath) error {\n- return syserror.EPERM\n-}\n-\n-// SetStatAt implements FilesystemImpl.SetStatAt.\n-func (fs *FDTestFilesystem) SetStatAt(ctx context.Context, rp *ResolvingPath, opts SetStatOptions) error {\n- return syserror.EPERM\n-}\n-\n-// StatAt implements FilesystemImpl.StatAt.\n-func (fs *FDTestFilesystem) StatAt(ctx context.Context, rp *ResolvingPath, opts StatOptions) (linux.Statx, error) {\n- return linux.Statx{}, syserror.EPERM\n-}\n-\n-// StatFSAt implements FilesystemImpl.StatFSAt.\n-func (fs *FDTestFilesystem) StatFSAt(ctx context.Context, rp *ResolvingPath) (linux.Statfs, error) {\n- return linux.Statfs{}, syserror.EPERM\n-}\n-\n-// SymlinkAt implements FilesystemImpl.SymlinkAt.\n-func (fs *FDTestFilesystem) SymlinkAt(ctx context.Context, rp *ResolvingPath, target string) error {\n- return syserror.EPERM\n-}\n-\n-// UnlinkAt implements FilesystemImpl.UnlinkAt.\n-func (fs *FDTestFilesystem) UnlinkAt(ctx context.Context, rp *ResolvingPath) error {\n- return syserror.EPERM\n-}\n-\n-// ListxattrAt implements FilesystemImpl.ListxattrAt.\n-func (fs *FDTestFilesystem) ListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error) {\n- return nil, syserror.EPERM\n-}\n-\n-// GetxattrAt implements FilesystemImpl.GetxattrAt.\n-func (fs *FDTestFilesystem) GetxattrAt(ctx context.Context, rp *ResolvingPath, name string) (string, error) {\n- return \"\", syserror.EPERM\n-}\n-\n-// SetxattrAt implements FilesystemImpl.SetxattrAt.\n-func (fs *FDTestFilesystem) SetxattrAt(ctx context.Context, rp *ResolvingPath, opts SetxattrOptions) error {\n- return syserror.EPERM\n-}\n-\n-// RemovexattrAt implements FilesystemImpl.RemovexattrAt.\n-func (fs *FDTestFilesystem) RemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error {\n- return syserror.EPERM\n-}\n-\n-// PrependPath implements FilesystemImpl.PrependPath.\n-func (fs *FDTestFilesystem) PrependPath(ctx context.Context, vfsroot, vd VirtualDentry, b *fspath.Builder) error {\n- b.PrependComponent(fmt.Sprintf(\"vfs.fdTestDentry:%p\", vd.dentry.impl.(*fdTestDentry)))\n- return PrependPathSyntheticError{}\n-}\n-\n-type fdTestDentry struct {\n- vfsd Dentry\n-}\n-\n-// NewDentry returns a new Dentry.\n-func (fs *FDTestFilesystem) NewDentry() *Dentry {\n- var d fdTestDentry\n- d.vfsd.Init(&d)\n- return &d.vfsd\n-}\n-\n-// IncRef implements DentryImpl.IncRef.\n-func (d *fdTestDentry) IncRef() {\n-}\n-\n-// TryIncRef implements DentryImpl.TryIncRef.\n-func (d *fdTestDentry) TryIncRef() bool {\n- return true\n-}\n-\n-// DecRef implements DentryImpl.DecRef.\n-func (d *fdTestDentry) DecRef() {\n-}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -75,6 +75,14 @@ type VirtualFilesystem struct {\n// mountpoints is analogous to Linux's mountpoint_hashtable.\nmountpoints map[*Dentry]map[*Mount]struct{}\n+ // anonMount is a Mount, not included in mounts or mountpoints,\n+ // representing an anonFilesystem. anonMount is used to back\n+ // VirtualDentries returned by VirtualFilesystem.NewAnonVirtualDentry().\n+ // anonMount is immutable.\n+ //\n+ // anonMount is analogous to Linux's anon_inode_mnt.\n+ anonMount *Mount\n+\n// devices contains all registered Devices. devices is protected by\n// devicesMu.\ndevicesMu sync.RWMutex\n@@ -110,6 +118,22 @@ func New() *VirtualFilesystem {\nfilesystems: make(map[*Filesystem]struct{}),\n}\nvfs.mounts.Init()\n+\n+ // Construct vfs.anonMount.\n+ anonfsDevMinor, err := vfs.GetAnonBlockDevMinor()\n+ if err != nil {\n+ panic(fmt.Sprintf(\"VirtualFilesystem.GetAnonBlockDevMinor() failed during VirtualFilesystem construction: %v\", err))\n+ }\n+ anonfs := anonFilesystem{\n+ devMinor: anonfsDevMinor,\n+ }\n+ anonfs.vfsfs.Init(vfs, &anonfs)\n+ vfs.anonMount = &Mount{\n+ vfs: vfs,\n+ fs: &anonfs.vfsfs,\n+ refs: 1,\n+ }\n+\nreturn vfs\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement an anon_inode equivalent for VFS2. PiperOrigin-RevId: 291986033
259,883
28.01.2020 12:31:58
28,800
d99329e58492ef91b44a0bac346f757e8af2a7ec
netlink: add support for RTM_F_LOOKUP_TABLE Test command: $ ip route get 1.1.1.1 Fixes: COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1121 from tanjianfeng:fix-1099
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netlink_route.go", "new_path": "pkg/abi/linux/netlink_route.go", "diff": "@@ -205,6 +205,9 @@ type RouteMessage struct {\nFlags uint32\n}\n+// SizeOfRouteMessage is the size of RouteMessage.\n+const SizeOfRouteMessage = 12\n+\n// Route types, from uapi/linux/rtnetlink.h.\nconst (\n// RTN_UNSPEC represents an unspecified route type.\n@@ -331,3 +334,13 @@ const (\nRTF_GATEWAY = 0x2\nRTF_UP = 0x1\n)\n+\n+// RtAttr is the header of optional addition route information, as a netlink\n+// attribute. From include/uapi/linux/rtnetlink.h.\n+type RtAttr struct {\n+ Len uint16\n+ Type uint16\n+}\n+\n+// SizeOfRtAttr is the size of RtAttr.\n+const SizeOfRtAttr = 4\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/route/BUILD", "new_path": "pkg/sentry/socket/netlink/route/BUILD", "diff": "@@ -4,15 +4,19 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"route\",\n- srcs = [\"protocol.go\"],\n+ srcs = [\n+ \"protocol.go\",\n+ ],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n\"//pkg/context\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/socket/netlink\",\n\"//pkg/syserr\",\n+ \"//pkg/usermem\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/route/protocol.go", "new_path": "pkg/sentry/socket/netlink/route/protocol.go", "diff": "@@ -19,12 +19,14 @@ import (\n\"bytes\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netlink\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\n// commandKind describes the operational class of a message type.\n@@ -66,8 +68,14 @@ func (p *Protocol) CanSend() bool {\nreturn true\n}\n-// dumpLinks handles RTM_GETLINK + NLM_F_DUMP requests.\n+// dumpLinks handles RTM_GETLINK dump requests.\nfunc (p *Protocol) dumpLinks(ctx context.Context, hdr linux.NetlinkMessageHeader, data []byte, ms *netlink.MessageSet) *syserr.Error {\n+ // TODO(b/68878065): Only the dump variant of the types below are\n+ // supported.\n+ if hdr.Flags&linux.NLM_F_DUMP != linux.NLM_F_DUMP {\n+ return syserr.ErrNotSupported\n+ }\n+\n// NLM_F_DUMP + RTM_GETLINK messages are supposed to include an\n// ifinfomsg. However, Linux <3.9 only checked for rtgenmsg, and some\n// userspace applications (including glibc) still include rtgenmsg.\n@@ -121,8 +129,14 @@ func (p *Protocol) dumpLinks(ctx context.Context, hdr linux.NetlinkMessageHeader\nreturn nil\n}\n-// dumpAddrs handles RTM_GETADDR + NLM_F_DUMP requests.\n+// dumpAddrs handles RTM_GETADDR dump requests.\nfunc (p *Protocol) dumpAddrs(ctx context.Context, hdr linux.NetlinkMessageHeader, data []byte, ms *netlink.MessageSet) *syserr.Error {\n+ // TODO(b/68878065): Only the dump variant of the types below are\n+ // supported.\n+ if hdr.Flags&linux.NLM_F_DUMP != linux.NLM_F_DUMP {\n+ return syserr.ErrNotSupported\n+ }\n+\n// RTM_GETADDR dump requests need not contain anything more than the\n// netlink header and 1 byte protocol family common to all\n// NETLINK_ROUTE requests.\n@@ -163,22 +177,146 @@ func (p *Protocol) dumpAddrs(ctx context.Context, hdr linux.NetlinkMessageHeader\nreturn nil\n}\n-// dumpRoutes handles RTM_GETROUTE + NLM_F_DUMP requests.\n+// commonPrefixLen reports the length of the longest IP address prefix.\n+// This is a simplied version from Golang's src/net/addrselect.go.\n+func commonPrefixLen(a, b []byte) (cpl int) {\n+ for len(a) > 0 {\n+ if a[0] == b[0] {\n+ cpl += 8\n+ a = a[1:]\n+ b = b[1:]\n+ continue\n+ }\n+ bits := 8\n+ ab, bb := a[0], b[0]\n+ for {\n+ ab >>= 1\n+ bb >>= 1\n+ bits--\n+ if ab == bb {\n+ cpl += bits\n+ return\n+ }\n+ }\n+ }\n+ return\n+}\n+\n+// fillRoute returns the Route using LPM algorithm. Refer to Linux's\n+// net/ipv4/route.c:rt_fill_info().\n+func fillRoute(routes []inet.Route, addr []byte) (inet.Route, *syserr.Error) {\n+ family := uint8(linux.AF_INET)\n+ if len(addr) != 4 {\n+ family = linux.AF_INET6\n+ }\n+\n+ idx := -1 // Index of the Route rule to be returned.\n+ idxDef := -1 // Index of the default route rule.\n+ prefix := 0 // Current longest prefix.\n+ for i, route := range routes {\n+ if route.Family != family {\n+ continue\n+ }\n+\n+ if len(route.GatewayAddr) > 0 && route.DstLen == 0 {\n+ idxDef = i\n+ continue\n+ }\n+\n+ cpl := commonPrefixLen(addr, route.DstAddr)\n+ if cpl < int(route.DstLen) {\n+ continue\n+ }\n+ cpl = int(route.DstLen)\n+ if cpl > prefix {\n+ idx = i\n+ prefix = cpl\n+ }\n+ }\n+ if idx == -1 {\n+ idx = idxDef\n+ }\n+ if idx == -1 {\n+ return inet.Route{}, syserr.ErrNoRoute\n+ }\n+\n+ route := routes[idx]\n+ if family == linux.AF_INET {\n+ route.DstLen = 32\n+ } else {\n+ route.DstLen = 128\n+ }\n+ route.DstAddr = addr\n+ route.Flags |= linux.RTM_F_CLONED // This route is cloned.\n+ return route, nil\n+}\n+\n+// parseForDestination parses a message as format of RouteMessage-RtAttr-dst.\n+func parseForDestination(data []byte) ([]byte, *syserr.Error) {\n+ var rtMsg linux.RouteMessage\n+ if len(data) < linux.SizeOfRouteMessage {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ binary.Unmarshal(data[:linux.SizeOfRouteMessage], usermem.ByteOrder, &rtMsg)\n+ // iproute2 added the RTM_F_LOOKUP_TABLE flag in version v4.4.0. See\n+ // commit bc234301af12. Note we don't check this flag for backward\n+ // compatibility.\n+ if rtMsg.Flags != 0 && rtMsg.Flags != linux.RTM_F_LOOKUP_TABLE {\n+ return nil, syserr.ErrNotSupported\n+ }\n+\n+ data = data[linux.SizeOfRouteMessage:]\n+\n+ // TODO(gvisor.dev/issue/1611): Add generic attribute parsing.\n+ var rtAttr linux.RtAttr\n+ if len(data) < linux.SizeOfRtAttr {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ binary.Unmarshal(data[:linux.SizeOfRtAttr], usermem.ByteOrder, &rtAttr)\n+ if rtAttr.Type != linux.RTA_DST {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ if len(data) < int(rtAttr.Len) {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ return data[linux.SizeOfRtAttr:rtAttr.Len], nil\n+}\n+\n+// dumpRoutes handles RTM_GETROUTE requests.\nfunc (p *Protocol) dumpRoutes(ctx context.Context, hdr linux.NetlinkMessageHeader, data []byte, ms *netlink.MessageSet) *syserr.Error {\n// RTM_GETROUTE dump requests need not contain anything more than the\n// netlink header and 1 byte protocol family common to all\n// NETLINK_ROUTE requests.\n- // We always send back an NLMSG_DONE.\n- ms.Multi = true\n-\nstack := inet.StackFromContext(ctx)\nif stack == nil {\n// No network routes.\nreturn nil\n}\n- for _, rt := range stack.RouteTable() {\n+ routeTables := stack.RouteTable()\n+\n+ if hdr.Flags == linux.NLM_F_REQUEST {\n+ dst, err := parseForDestination(data)\n+ if err != nil {\n+ return err\n+ }\n+ route, err := fillRoute(routeTables, dst)\n+ if err != nil {\n+ // TODO(gvisor.dev/issue/1237): return NLMSG_ERROR with ENETUNREACH.\n+ return syserr.ErrNotSupported\n+ }\n+ routeTables = append([]inet.Route{}, route)\n+ } else if hdr.Flags&linux.NLM_F_DUMP == linux.NLM_F_DUMP {\n+ // We always send back an NLMSG_DONE.\n+ ms.Multi = true\n+ } else {\n+ // TODO(b/68878065): Only above cases are supported.\n+ return syserr.ErrNotSupported\n+ }\n+\n+ for _, rt := range routeTables {\nm := ms.AddMessage(linux.NetlinkMessageHeader{\nType: linux.RTM_NEWROUTE,\n})\n@@ -236,12 +374,6 @@ func (p *Protocol) ProcessMessage(ctx context.Context, hdr linux.NetlinkMessageH\n}\n}\n- // TODO(b/68878065): Only the dump variant of the types below are\n- // supported.\n- if hdr.Flags&linux.NLM_F_DUMP != linux.NLM_F_DUMP {\n- return syserr.ErrNotSupported\n- }\n-\nswitch hdr.Type {\ncase linux.RTM_GETLINK:\nreturn p.dumpLinks(ctx, hdr, data, ms)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_route.cc", "new_path": "test/syscalls/linux/socket_netlink_route.cc", "diff": "@@ -442,6 +442,90 @@ TEST(NetlinkRouteTest, GetRouteDump) {\nEXPECT_TRUE(dstFound);\n}\n+// GetRouteRequest tests a RTM_GETROUTE request with RTM_F_LOOKUP_TABLE flag.\n+TEST(NetlinkRouteTest, GetRouteRequest) {\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NetlinkBoundSocket(NETLINK_ROUTE));\n+ uint32_t port = ASSERT_NO_ERRNO_AND_VALUE(NetlinkPortID(fd.get()));\n+\n+ struct __attribute__((__packed__)) request {\n+ struct nlmsghdr hdr;\n+ struct rtmsg rtm;\n+ struct nlattr nla;\n+ struct in_addr sin_addr;\n+ };\n+\n+ constexpr uint32_t kSeq = 12345;\n+\n+ struct request req = {};\n+ req.hdr.nlmsg_len = sizeof(req);\n+ req.hdr.nlmsg_type = RTM_GETROUTE;\n+ req.hdr.nlmsg_flags = NLM_F_REQUEST;\n+ req.hdr.nlmsg_seq = kSeq;\n+\n+ req.rtm.rtm_family = AF_INET;\n+ req.rtm.rtm_dst_len = 32;\n+ req.rtm.rtm_src_len = 0;\n+ req.rtm.rtm_tos = 0;\n+ req.rtm.rtm_table = RT_TABLE_UNSPEC;\n+ req.rtm.rtm_protocol = RTPROT_UNSPEC;\n+ req.rtm.rtm_scope = RT_SCOPE_UNIVERSE;\n+ req.rtm.rtm_type = RTN_UNSPEC;\n+ req.rtm.rtm_flags = RTM_F_LOOKUP_TABLE;\n+\n+ req.nla.nla_len = 8;\n+ req.nla.nla_type = RTA_DST;\n+ inet_aton(\"127.0.0.2\", &req.sin_addr);\n+\n+ bool rtDstFound = false;\n+ ASSERT_NO_ERRNO(NetlinkRequestResponseSingle(\n+ fd, &req, sizeof(req), [&](const struct nlmsghdr* hdr) {\n+ // Validate the reponse to RTM_GETROUTE request with RTM_F_LOOKUP_TABLE\n+ // flag.\n+ EXPECT_THAT(hdr->nlmsg_type, RTM_NEWROUTE);\n+\n+ EXPECT_TRUE(hdr->nlmsg_flags == 0) << std::hex << hdr->nlmsg_flags;\n+\n+ EXPECT_EQ(hdr->nlmsg_seq, kSeq);\n+ EXPECT_EQ(hdr->nlmsg_pid, port);\n+\n+ // RTM_NEWROUTE contains at least the header and rtmsg.\n+ ASSERT_GE(hdr->nlmsg_len, NLMSG_SPACE(sizeof(struct rtmsg)));\n+ const struct rtmsg* msg =\n+ reinterpret_cast<const struct rtmsg*>(NLMSG_DATA(hdr));\n+\n+ // NOTE: rtmsg fields are char fields.\n+ std::cout << \"Found route table=\" << static_cast<int>(msg->rtm_table)\n+ << \", protocol=\" << static_cast<int>(msg->rtm_protocol)\n+ << \", scope=\" << static_cast<int>(msg->rtm_scope)\n+ << \", type=\" << static_cast<int>(msg->rtm_type);\n+\n+ EXPECT_EQ(msg->rtm_family, AF_INET);\n+ EXPECT_EQ(msg->rtm_dst_len, 32);\n+ EXPECT_TRUE((msg->rtm_flags & RTM_F_CLONED) == RTM_F_CLONED)\n+ << std::hex << msg->rtm_flags;\n+\n+ int len = RTM_PAYLOAD(hdr);\n+ std::cout << \", len=\" << len;\n+ for (struct rtattr* attr = RTM_RTA(msg); RTA_OK(attr, len);\n+ attr = RTA_NEXT(attr, len)) {\n+ if (attr->rta_type == RTA_DST) {\n+ char address[INET_ADDRSTRLEN] = {};\n+ inet_ntop(AF_INET, RTA_DATA(attr), address, sizeof(address));\n+ std::cout << \", dst=\" << address;\n+ rtDstFound = true;\n+ } else if (attr->rta_type == RTA_OIF) {\n+ const char* oif = reinterpret_cast<const char*>(RTA_DATA(attr));\n+ std::cout << \", oif=\" << oif;\n+ }\n+ }\n+\n+ std::cout << std::endl;\n+ }));\n+ // Found RTA_DST for RTM_F_LOOKUP_TABLE.\n+ EXPECT_TRUE(rtDstFound);\n+}\n+\n// RecvmsgTrunc tests the recvmsg MSG_TRUNC flag with zero length output\n// buffer. MSG_TRUNC with a zero length buffer should consume subsequent\n// messages off the socket.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_util.cc", "new_path": "test/syscalls/linux/socket_netlink_util.cc", "diff": "@@ -108,5 +108,43 @@ PosixError NetlinkRequestResponse(\nreturn NoError();\n}\n+PosixError NetlinkRequestResponseSingle(\n+ const FileDescriptor& fd, void* request, size_t len,\n+ const std::function<void(const struct nlmsghdr* hdr)>& fn) {\n+ struct iovec iov = {};\n+ iov.iov_base = request;\n+ iov.iov_len = len;\n+\n+ struct msghdr msg = {};\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+ // No destination required; it defaults to pid 0, the kernel.\n+\n+ RETURN_ERROR_IF_SYSCALL_FAIL(RetryEINTR(sendmsg)(fd.get(), &msg, 0));\n+\n+ constexpr size_t kBufferSize = 4096;\n+ std::vector<char> buf(kBufferSize);\n+ iov.iov_base = buf.data();\n+ iov.iov_len = buf.size();\n+\n+ int ret;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(ret = RetryEINTR(recvmsg)(fd.get(), &msg, 0));\n+\n+ // We don't bother with the complexity of dealing with truncated messages.\n+ // We must allocate a large enough buffer up front.\n+ if ((msg.msg_flags & MSG_TRUNC) == MSG_TRUNC) {\n+ return PosixError(\n+ EIO,\n+ absl::StrCat(\"Received truncated message with flags: \", msg.msg_flags));\n+ }\n+\n+ for (struct nlmsghdr* hdr = reinterpret_cast<struct nlmsghdr*>(buf.data());\n+ NLMSG_OK(hdr, ret); hdr = NLMSG_NEXT(hdr, ret)) {\n+ fn(hdr);\n+ }\n+\n+ return NoError();\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_netlink_util.h", "new_path": "test/syscalls/linux/socket_netlink_util.h", "diff": "@@ -32,12 +32,21 @@ PosixErrorOr<FileDescriptor> NetlinkBoundSocket(int protocol);\n// Returns the port ID of the passed socket.\nPosixErrorOr<uint32_t> NetlinkPortID(int fd);\n-// Send the passed request and call fn will all response netlink messages.\n+// Send the passed request and call fn on all response netlink messages.\n+//\n+// To be used on requests with NLM_F_MULTI reponses.\nPosixError NetlinkRequestResponse(\nconst FileDescriptor& fd, void* request, size_t len,\nconst std::function<void(const struct nlmsghdr* hdr)>& fn,\nbool expect_nlmsgerr);\n+// Send the passed request and call fn on all response netlink messages.\n+//\n+// To be used on requests without NLM_F_MULTI reponses.\n+PosixError NetlinkRequestResponseSingle(\n+ const FileDescriptor& fd, void* request, size_t len,\n+ const std::function<void(const struct nlmsghdr* hdr)>& fn);\n+\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
netlink: add support for RTM_F_LOOKUP_TABLE Test command: $ ip route get 1.1.1.1 Fixes: #1099 Signed-off-by: Jianfeng Tan <[email protected]> COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1121 from tanjianfeng:fix-1099 e6919f3d4ede5aa51a48b3d2be0d7a4b482dd53d PiperOrigin-RevId: 291990716
259,885
28.01.2020 13:10:41
28,800
34fbd8446c386fb0136dad31ab6b173f17049a58
Add VFS2 support for epoll.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/epoll.go", "new_path": "pkg/abi/linux/epoll.go", "diff": "@@ -38,8 +38,14 @@ const (\n// Per-file descriptor flags.\nconst (\n- EPOLLET = 0x80000000\n- EPOLLONESHOT = 0x40000000\n+ EPOLLEXCLUSIVE = 1 << 28\n+ EPOLLWAKEUP = 1 << 29\n+ EPOLLONESHOT = 1 << 30\n+ EPOLLET = 1 << 31\n+\n+ // EP_PRIVATE_BITS is fs/eventpoll.c:EP_PRIVATE_BITS, the set of all bits\n+ // in an epoll event mask that correspond to flags rather than I/O events.\n+ EP_PRIVATE_BITS = EPOLLEXCLUSIVE | EPOLLWAKEUP | EPOLLONESHOT | EPOLLET\n)\n// Operation flags.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/BUILD", "new_path": "pkg/sentry/vfs/BUILD", "diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nlicenses([\"notice\"])\n+go_template_instance(\n+ name = \"epoll_interest_list\",\n+ out = \"epoll_interest_list.go\",\n+ package = \"vfs\",\n+ prefix = \"epollInterest\",\n+ template = \"//pkg/ilist:generic_list\",\n+ types = {\n+ \"Element\": \"*epollInterest\",\n+ \"Linker\": \"*epollInterest\",\n+ },\n+)\n+\ngo_library(\nname = \"vfs\",\nsrcs = [\n@@ -10,6 +23,8 @@ go_library(\n\"debug.go\",\n\"dentry.go\",\n\"device.go\",\n+ \"epoll.go\",\n+ \"epoll_interest_list.go\",\n\"file_description.go\",\n\"file_description_impl_util.go\",\n\"filesystem.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/vfs/epoll.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package vfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n+)\n+\n+// epollCycleMu serializes attempts to register EpollInstances with other\n+// EpollInstances in order to check for cycles.\n+var epollCycleMu sync.Mutex\n+\n+// EpollInstance represents an epoll instance, as described by epoll(7).\n+type EpollInstance struct {\n+ vfsfd FileDescription\n+ FileDescriptionDefaultImpl\n+ DentryMetadataFileDescriptionImpl\n+\n+ // q holds waiters on this EpollInstance.\n+ q waiter.Queue\n+\n+ // interest is the set of file descriptors that are registered with the\n+ // EpollInstance for monitoring. interest is protected by interestMu.\n+ interestMu sync.Mutex\n+ interest map[epollInterestKey]*epollInterest\n+\n+ // mu protects fields in registered epollInterests.\n+ mu sync.Mutex\n+\n+ // ready is the set of file descriptors that may be \"ready\" for I/O. Note\n+ // that this must be an ordered list, not a map: \"If more than maxevents\n+ // file descriptors are ready when epoll_wait() is called, then successive\n+ // epoll_wait() calls will round robin through the set of ready file\n+ // descriptors. This behavior helps avoid starvation scenarios, where a\n+ // process fails to notice that additional file descriptors are ready\n+ // because it focuses on a set of file descriptors that are already known\n+ // to be ready.\" - epoll_wait(2)\n+ ready epollInterestList\n+}\n+\n+type epollInterestKey struct {\n+ // file is the registered FileDescription. No reference is held on file;\n+ // instead, when the last reference is dropped, FileDescription.DecRef()\n+ // removes the FileDescription from all EpollInstances. file is immutable.\n+ file *FileDescription\n+\n+ // num is the file descriptor number with which this entry was registered.\n+ // num is immutable.\n+ num int32\n+}\n+\n+// epollInterest represents an EpollInstance's interest in a file descriptor.\n+type epollInterest struct {\n+ // epoll is the owning EpollInstance. epoll is immutable.\n+ epoll *EpollInstance\n+\n+ // key is the file to which this epollInterest applies. key is immutable.\n+ key epollInterestKey\n+\n+ // waiter is registered with key.file. entry is protected by epoll.mu.\n+ waiter waiter.Entry\n+\n+ // mask is the event mask associated with this registration, including\n+ // flags EPOLLET and EPOLLONESHOT. mask is protected by epoll.mu.\n+ mask uint32\n+\n+ // ready is true if epollInterestEntry is linked into epoll.ready. ready\n+ // and epollInterestEntry are protected by epoll.mu.\n+ ready bool\n+ epollInterestEntry\n+\n+ // userData is the epoll_data_t associated with this epollInterest.\n+ // userData is protected by epoll.mu.\n+ userData [2]int32\n+}\n+\n+// NewEpollInstanceFD returns a FileDescription representing a new epoll\n+// instance. A reference is taken on the returned FileDescription.\n+func (vfs *VirtualFilesystem) NewEpollInstanceFD() (*FileDescription, error) {\n+ vd := vfs.NewAnonVirtualDentry(\"[eventpoll]\")\n+ defer vd.DecRef()\n+ ep := &EpollInstance{\n+ interest: make(map[epollInterestKey]*epollInterest),\n+ }\n+ if err := ep.vfsfd.Init(ep, linux.O_RDWR, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+ return &ep.vfsfd, nil\n+}\n+\n+// Release implements FileDescriptionImpl.Release.\n+func (ep *EpollInstance) Release() {\n+ // Unregister all polled fds.\n+ ep.interestMu.Lock()\n+ defer ep.interestMu.Unlock()\n+ for key, epi := range ep.interest {\n+ file := key.file\n+ file.epollMu.Lock()\n+ delete(file.epolls, epi)\n+ file.epollMu.Unlock()\n+ file.EventUnregister(&epi.waiter)\n+ }\n+ ep.interest = nil\n+}\n+\n+// Readiness implements waiter.Waitable.Readiness.\n+func (ep *EpollInstance) Readiness(mask waiter.EventMask) waiter.EventMask {\n+ if mask&waiter.EventIn == 0 {\n+ return 0\n+ }\n+ ep.mu.Lock()\n+ for epi := ep.ready.Front(); epi != nil; epi = epi.Next() {\n+ wmask := waiter.EventMaskFromLinux(epi.mask)\n+ if epi.key.file.Readiness(wmask)&wmask != 0 {\n+ ep.mu.Unlock()\n+ return waiter.EventIn\n+ }\n+ }\n+ ep.mu.Unlock()\n+ return 0\n+}\n+\n+// EventRegister implements waiter.Waitable.EventRegister.\n+func (ep *EpollInstance) EventRegister(e *waiter.Entry, mask waiter.EventMask) {\n+ ep.q.EventRegister(e, mask)\n+}\n+\n+// EventUnregister implements waiter.Waitable.EventUnregister.\n+func (ep *EpollInstance) EventUnregister(e *waiter.Entry) {\n+ ep.q.EventUnregister(e)\n+}\n+\n+// Seek implements FileDescriptionImpl.Seek.\n+func (ep *EpollInstance) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ // Linux: fs/eventpoll.c:eventpoll_fops.llseek == noop_llseek\n+ return 0, nil\n+}\n+\n+// AddInterest implements the semantics of EPOLL_CTL_ADD.\n+//\n+// Preconditions: A reference must be held on file.\n+func (ep *EpollInstance) AddInterest(file *FileDescription, num int32, mask uint32, userData [2]int32) error {\n+ // Check for cyclic polling if necessary.\n+ subep, _ := file.impl.(*EpollInstance)\n+ if subep != nil {\n+ epollCycleMu.Lock()\n+ // epollCycleMu must be locked for the rest of AddInterest to ensure\n+ // that cyclic polling is not introduced after the check.\n+ defer epollCycleMu.Unlock()\n+ if subep.mightPoll(ep) {\n+ return syserror.ELOOP\n+ }\n+ }\n+\n+ ep.interestMu.Lock()\n+ defer ep.interestMu.Unlock()\n+\n+ // Fail if the key is already registered.\n+ key := epollInterestKey{\n+ file: file,\n+ num: num,\n+ }\n+ if _, ok := ep.interest[key]; ok {\n+ return syserror.EEXIST\n+ }\n+\n+ // Register interest in file.\n+ mask |= linux.EPOLLERR | linux.EPOLLRDHUP\n+ epi := &epollInterest{\n+ epoll: ep,\n+ key: key,\n+ mask: mask,\n+ userData: userData,\n+ }\n+ ep.interest[key] = epi\n+ wmask := waiter.EventMaskFromLinux(mask)\n+ file.EventRegister(&epi.waiter, wmask)\n+\n+ // Check if the file is already ready.\n+ if file.Readiness(wmask)&wmask != 0 {\n+ epi.Callback(nil)\n+ }\n+\n+ // Add epi to file.epolls so that it is removed when the last\n+ // FileDescription reference is dropped.\n+ file.epollMu.Lock()\n+ file.epolls[epi] = struct{}{}\n+ file.epollMu.Unlock()\n+\n+ return nil\n+}\n+\n+func (ep *EpollInstance) mightPoll(ep2 *EpollInstance) bool {\n+ return ep.mightPollRecursive(ep2, 4) // Linux: fs/eventpoll.c:EP_MAX_NESTS\n+}\n+\n+func (ep *EpollInstance) mightPollRecursive(ep2 *EpollInstance, remainingRecursion int) bool {\n+ ep.interestMu.Lock()\n+ defer ep.interestMu.Unlock()\n+ for key := range ep.interest {\n+ nextep, ok := key.file.impl.(*EpollInstance)\n+ if !ok {\n+ continue\n+ }\n+ if nextep == ep2 {\n+ return true\n+ }\n+ if remainingRecursion == 0 {\n+ return true\n+ }\n+ if nextep.mightPollRecursive(ep2, remainingRecursion-1) {\n+ return true\n+ }\n+ }\n+ return false\n+}\n+\n+// ModifyInterest implements the semantics of EPOLL_CTL_MOD.\n+//\n+// Preconditions: A reference must be held on file.\n+func (ep *EpollInstance) ModifyInterest(file *FileDescription, num int32, mask uint32, userData [2]int32) error {\n+ ep.interestMu.Lock()\n+ defer ep.interestMu.Unlock()\n+\n+ // Fail if the key is not already registered.\n+ epi, ok := ep.interest[epollInterestKey{\n+ file: file,\n+ num: num,\n+ }]\n+ if !ok {\n+ return syserror.ENOENT\n+ }\n+\n+ // Update epi for the next call to ep.ReadEvents().\n+ ep.mu.Lock()\n+ epi.mask = mask\n+ epi.userData = userData\n+ ep.mu.Unlock()\n+\n+ // Re-register with the new mask.\n+ mask |= linux.EPOLLERR | linux.EPOLLRDHUP\n+ file.EventUnregister(&epi.waiter)\n+ wmask := waiter.EventMaskFromLinux(mask)\n+ file.EventRegister(&epi.waiter, wmask)\n+\n+ // Check if the file is already ready with the new mask.\n+ if file.Readiness(wmask)&wmask != 0 {\n+ epi.Callback(nil)\n+ }\n+\n+ return nil\n+}\n+\n+// DeleteInterest implements the semantics of EPOLL_CTL_DEL.\n+//\n+// Preconditions: A reference must be held on file.\n+func (ep *EpollInstance) DeleteInterest(file *FileDescription, num int32) error {\n+ ep.interestMu.Lock()\n+ defer ep.interestMu.Unlock()\n+\n+ // Fail if the key is not already registered.\n+ epi, ok := ep.interest[epollInterestKey{\n+ file: file,\n+ num: num,\n+ }]\n+ if !ok {\n+ return syserror.ENOENT\n+ }\n+\n+ // Unregister from the file so that epi will no longer be readied.\n+ file.EventUnregister(&epi.waiter)\n+\n+ // Forget about epi.\n+ ep.removeLocked(epi)\n+\n+ file.epollMu.Lock()\n+ delete(file.epolls, epi)\n+ file.epollMu.Unlock()\n+\n+ return nil\n+}\n+\n+// Callback implements waiter.EntryCallback.Callback.\n+func (epi *epollInterest) Callback(*waiter.Entry) {\n+ newReady := false\n+ epi.epoll.mu.Lock()\n+ if !epi.ready {\n+ newReady = true\n+ epi.ready = true\n+ epi.epoll.ready.PushBack(epi)\n+ }\n+ epi.epoll.mu.Unlock()\n+ if newReady {\n+ epi.epoll.q.Notify(waiter.EventIn)\n+ }\n+}\n+\n+// Preconditions: ep.interestMu must be locked.\n+func (ep *EpollInstance) removeLocked(epi *epollInterest) {\n+ delete(ep.interest, epi.key)\n+ ep.mu.Lock()\n+ if epi.ready {\n+ epi.ready = false\n+ ep.ready.Remove(epi)\n+ }\n+ ep.mu.Unlock()\n+}\n+\n+// ReadEvents reads up to len(events) ready events into events and returns the\n+// number of events read.\n+//\n+// Preconditions: len(events) != 0.\n+func (ep *EpollInstance) ReadEvents(events []linux.EpollEvent) int {\n+ i := 0\n+ // Hot path: avoid defer.\n+ ep.mu.Lock()\n+ var next *epollInterest\n+ var requeue epollInterestList\n+ for epi := ep.ready.Front(); epi != nil; epi = next {\n+ next = epi.Next()\n+ // Regardless of what else happens, epi is initially removed from the\n+ // ready list.\n+ ep.ready.Remove(epi)\n+ wmask := waiter.EventMaskFromLinux(epi.mask)\n+ ievents := epi.key.file.Readiness(wmask) & wmask\n+ if ievents == 0 {\n+ // Leave epi off the ready list.\n+ epi.ready = false\n+ continue\n+ }\n+ // Determine what we should do with epi.\n+ switch {\n+ case epi.mask&linux.EPOLLONESHOT != 0:\n+ // Clear all events from the mask; they must be re-added by\n+ // EPOLL_CTL_MOD.\n+ epi.mask &= linux.EP_PRIVATE_BITS\n+ fallthrough\n+ case epi.mask&linux.EPOLLET != 0:\n+ // Leave epi off the ready list.\n+ epi.ready = false\n+ default:\n+ // Queue epi to be moved to the end of the ready list.\n+ requeue.PushBack(epi)\n+ }\n+ // Report ievents.\n+ events[i] = linux.EpollEvent{\n+ Events: ievents.ToLinux(),\n+ Fd: epi.userData[0],\n+ Data: epi.userData[1],\n+ }\n+ i++\n+ if i == len(events) {\n+ break\n+ }\n+ }\n+ ep.ready.PushBackList(&requeue)\n+ ep.mu.Unlock()\n+ return i\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n@@ -45,6 +46,11 @@ type FileDescription struct {\n// memory operations.\nstatusFlags uint32\n+ // epolls is the set of epollInterests registered for this FileDescription.\n+ // epolls is protected by epollMu.\n+ epollMu sync.Mutex\n+ epolls map[*epollInterest]struct{}\n+\n// vd is the filesystem location at which this FileDescription was opened.\n// A reference is held on vd. vd is immutable.\nvd VirtualDentry\n@@ -141,6 +147,23 @@ func (fd *FileDescription) TryIncRef() bool {\n// DecRef decrements fd's reference count.\nfunc (fd *FileDescription) DecRef() {\nif refs := atomic.AddInt64(&fd.refs, -1); refs == 0 {\n+ // Unregister fd from all epoll instances.\n+ fd.epollMu.Lock()\n+ epolls := fd.epolls\n+ fd.epolls = nil\n+ fd.epollMu.Unlock()\n+ for epi := range epolls {\n+ ep := epi.epoll\n+ ep.interestMu.Lock()\n+ // Check that epi has not been concurrently unregistered by\n+ // EpollInstance.DeleteInterest() or EpollInstance.Release().\n+ if _, ok := ep.interest[epi.key]; ok {\n+ fd.EventUnregister(&epi.waiter)\n+ ep.removeLocked(epi)\n+ }\n+ ep.interestMu.Unlock()\n+ }\n+ // Release implementation resources.\nfd.impl.Release()\nif fd.writable {\nfd.vd.mount.EndWrite()\n@@ -453,6 +476,21 @@ func (fd *FileDescription) StatFS(ctx context.Context) (linux.Statfs, error) {\nreturn fd.impl.StatFS(ctx)\n}\n+// Readiness returns fd's I/O readiness.\n+func (fd *FileDescription) Readiness(mask waiter.EventMask) waiter.EventMask {\n+ return fd.impl.Readiness(mask)\n+}\n+\n+// EventRegister registers e for I/O readiness events in mask.\n+func (fd *FileDescription) EventRegister(e *waiter.Entry, mask waiter.EventMask) {\n+ fd.impl.EventRegister(e, mask)\n+}\n+\n+// EventUnregister unregisters e for I/O readiness events.\n+func (fd *FileDescription) EventUnregister(e *waiter.Entry) {\n+ fd.impl.EventUnregister(e)\n+}\n+\n// PRead reads from the file represented by fd into dst, starting at the given\n// offset, and returns the number of bytes read. PRead is permitted to return\n// partial reads with a nil error.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "//\n// Lock order:\n//\n+// EpollInstance.interestMu\n+// FileDescription.epollMu\n// FilesystemImpl/FileDescriptionImpl locks\n// VirtualFilesystem.mountMu\n// Dentry.mu\n// Locks acquired by FilesystemImpls between Prepare{Delete,Rename}Dentry and Commit{Delete,Rename*}Dentry\n// VirtualFilesystem.filesystemsMu\n+// EpollInstance.mu\n// VirtualFilesystem.fsTypesMu\n//\n// Locking Dentry.mu in multiple Dentries requires holding\n-// VirtualFilesystem.mountMu.\n+// VirtualFilesystem.mountMu. Locking EpollInstance.interestMu in multiple\n+// EpollInstances requires holding epollCycleMu.\npackage vfs\nimport (\n" } ]
Go
Apache License 2.0
google/gvisor
Add VFS2 support for epoll. PiperOrigin-RevId: 291997879
259,853
28.01.2020 13:36:16
28,800
f263801a74d4ccac042b068d0928c8738e40af5b
fs/splice: don't report partial errors for special files Special files can have additional requirements for granularity. For example, read from eventfd returns EINVAL if a size is less 8 bytes. Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/attr.go", "new_path": "pkg/sentry/fs/attr.go", "diff": "@@ -206,6 +206,11 @@ func IsPipe(s StableAttr) bool {\nreturn s.Type == Pipe\n}\n+// IsAnonymous returns true if StableAttr.Type matches any type of anonymous.\n+func IsAnonymous(s StableAttr) bool {\n+ return s.Type == Anonymous\n+}\n+\n// IsSocket returns true if StableAttr.Type matches any type of socket.\nfunc IsSocket(s StableAttr) bool {\nreturn s.Type == Socket\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/file.go", "new_path": "pkg/sentry/fs/file.go", "diff": "@@ -555,10 +555,6 @@ type lockedWriter struct {\n//\n// This applies only to Write, not WriteAt.\nOffset int64\n-\n- // Err contains the first error encountered while copying. This is\n- // useful to determine whether Writer or Reader failed during io.Copy.\n- Err error\n}\n// Write implements io.Writer.Write.\n@@ -594,8 +590,5 @@ func (w *lockedWriter) WriteAt(buf []byte, offset int64) (int, error) {\nbreak\n}\n}\n- if w.Err == nil {\n- w.Err = err\n- }\nreturn written, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/splice.go", "new_path": "pkg/sentry/fs/splice.go", "diff": "@@ -167,11 +167,6 @@ func Splice(ctx context.Context, dst *File, src *File, opts SpliceOpts) (int64,\nif !srcPipe && !opts.SrcOffset {\natomic.StoreInt64(&src.offset, src.offset+n)\n}\n-\n- // Don't report any errors if we have some progress without data loss.\n- if w.Err == nil {\n- err = nil\n- }\n}\n// Drop locks.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_splice.go", "new_path": "pkg/sentry/syscalls/linux/sys_splice.go", "diff": "@@ -211,8 +211,10 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nopts := fs.SpliceOpts{\nLength: count,\n}\n+ inFileAttr := inFile.Dirent.Inode.StableAttr\n+ outFileAttr := outFile.Dirent.Inode.StableAttr\nswitch {\n- case fs.IsPipe(inFile.Dirent.Inode.StableAttr) && !fs.IsPipe(outFile.Dirent.Inode.StableAttr):\n+ case fs.IsPipe(inFileAttr) && !fs.IsPipe(outFileAttr):\nif inOffset != 0 {\nreturn 0, nil, syserror.ESPIPE\n}\n@@ -229,7 +231,7 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nopts.DstOffset = true\nopts.DstStart = offset\n}\n- case !fs.IsPipe(inFile.Dirent.Inode.StableAttr) && fs.IsPipe(outFile.Dirent.Inode.StableAttr):\n+ case !fs.IsPipe(inFileAttr) && fs.IsPipe(outFileAttr):\nif outOffset != 0 {\nreturn 0, nil, syserror.ESPIPE\n}\n@@ -246,13 +248,13 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nopts.SrcOffset = true\nopts.SrcStart = offset\n}\n- case fs.IsPipe(inFile.Dirent.Inode.StableAttr) && fs.IsPipe(outFile.Dirent.Inode.StableAttr):\n+ case fs.IsPipe(inFileAttr) && fs.IsPipe(outFileAttr):\nif inOffset != 0 || outOffset != 0 {\nreturn 0, nil, syserror.ESPIPE\n}\n// We may not refer to the same pipe; otherwise it's a continuous loop.\n- if inFile.Dirent.Inode.StableAttr.InodeID == outFile.Dirent.Inode.StableAttr.InodeID {\n+ if inFileAttr.InodeID == outFileAttr.InodeID {\nreturn 0, nil, syserror.EINVAL\n}\ndefault:\n@@ -262,6 +264,15 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n// Splice data.\nn, err := doSplice(t, outFile, inFile, opts, nonBlock)\n+ // Special files can have additional requirements for granularity. For\n+ // example, read from eventfd returns EINVAL if a size is less 8 bytes.\n+ // Inotify is another example. read will return EINVAL is a buffer is\n+ // too small to return the next event, but a size of an event isn't\n+ // fixed, it is sizeof(struct inotify_event) + {NAME_LEN} + 1.\n+ if n != 0 && err != nil && (fs.IsAnonymous(inFileAttr) || fs.IsAnonymous(outFileAttr)) {\n+ err = nil\n+ }\n+\n// See above; inFile is chosen arbitrarily here.\nreturn uintptr(n), nil, handleIOError(t, n != 0, err, kernel.ERESTARTSYS, \"splice\", inFile)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/eventfd.cc", "new_path": "test/syscalls/linux/eventfd.cc", "diff": "@@ -132,6 +132,31 @@ TEST(EventfdTest, BigWriteBigRead) {\nEXPECT_EQ(l[0], 1);\n}\n+TEST(EventfdTest, SpliceFromPipePartialSucceeds) {\n+ int pipes[2];\n+ ASSERT_THAT(pipe2(pipes, O_NONBLOCK), SyscallSucceeds());\n+ const FileDescriptor pipe_rfd(pipes[0]);\n+ const FileDescriptor pipe_wfd(pipes[1]);\n+ constexpr uint64_t kVal{1};\n+\n+ FileDescriptor efd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK));\n+\n+ uint64_t event_array[2];\n+ event_array[0] = kVal;\n+ event_array[1] = kVal;\n+ ASSERT_THAT(write(pipe_wfd.get(), event_array, sizeof(event_array)),\n+ SyscallSucceedsWithValue(sizeof(event_array)));\n+ EXPECT_THAT(splice(pipe_rfd.get(), /*__offin=*/nullptr, efd.get(),\n+ /*__offout=*/nullptr, sizeof(event_array[0]) + 1,\n+ SPLICE_F_NONBLOCK),\n+ SyscallSucceedsWithValue(sizeof(event_array[0])));\n+\n+ uint64_t val;\n+ ASSERT_THAT(read(efd.get(), &val, sizeof(val)),\n+ SyscallSucceedsWithValue(sizeof(val)));\n+ EXPECT_EQ(val, kVal);\n+}\n+\n// NotifyNonZero is inherently racy, so random save is disabled.\nTEST(EventfdTest, NotifyNonZero_NoRandomSave) {\n// Waits will time out at 10 seconds.\n" } ]
Go
Apache License 2.0
google/gvisor
fs/splice: don't report partial errors for special files Special files can have additional requirements for granularity. For example, read from eventfd returns EINVAL if a size is less 8 bytes. Reported-by: [email protected] PiperOrigin-RevId: 292002926
260,004
28.01.2020 13:37:10
28,800
ce0bac4be9d808877248c328fac07ff0d66b9607
Include the NDP Source Link Layer option when sending DAD messages Test: stack_test.TestDADResolve
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/checker/checker.go", "new_path": "pkg/tcpip/checker/checker.go", "diff": "@@ -771,6 +771,56 @@ func NDPNSTargetAddress(want tcpip.Address) TransportChecker {\n}\n}\n+// NDPNSOptions creates a checker that checks that the packet contains the\n+// provided NDP options within an NDP Neighbor Solicitation message.\n+//\n+// The returned TransportChecker assumes that a valid ICMPv6 is passed to it\n+// containing a valid NDPNS message as far as the size is concerned.\n+func NDPNSOptions(opts []header.NDPOption) TransportChecker {\n+ return func(t *testing.T, h header.Transport) {\n+ t.Helper()\n+\n+ icmp := h.(header.ICMPv6)\n+ ns := header.NDPNeighborSolicit(icmp.NDPPayload())\n+ it, err := ns.Options().Iter(true)\n+ if err != nil {\n+ t.Errorf(\"opts.Iter(true): %s\", err)\n+ return\n+ }\n+\n+ i := 0\n+ for {\n+ opt, done, _ := it.Next()\n+ if done {\n+ break\n+ }\n+\n+ if i >= len(opts) {\n+ t.Errorf(\"got unexpected option: %s\", opt)\n+ continue\n+ }\n+\n+ switch wantOpt := opts[i].(type) {\n+ case header.NDPSourceLinkLayerAddressOption:\n+ gotOpt, ok := opt.(header.NDPSourceLinkLayerAddressOption)\n+ if !ok {\n+ t.Errorf(\"got type = %T at index = %d; want = %T\", opt, i, wantOpt)\n+ } else if got, want := gotOpt.EthernetAddress(), wantOpt.EthernetAddress(); got != want {\n+ t.Errorf(\"got EthernetAddress() = %s at index %d, want = %s\", got, i, want)\n+ }\n+ default:\n+ panic(\"not implemented\")\n+ }\n+\n+ i++\n+ }\n+\n+ if missing := opts[i:]; len(missing) > 0 {\n+ t.Errorf(\"missing options: %s\", missing)\n+ }\n+ }\n+}\n+\n// NDPRS creates a checker that checks that the packet contains a valid NDP\n// Router Solicitation message (as per the raw wire format).\nfunc NDPRS() NetworkChecker {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/icmpv6.go", "new_path": "pkg/tcpip/header/icmpv6.go", "diff": "@@ -52,7 +52,7 @@ const (\n// ICMPv6NeighborAdvertSize is size of a neighbor advertisement\n// including the NDP Target Link Layer option for an Ethernet\n// address.\n- ICMPv6NeighborAdvertSize = ICMPv6HeaderSize + NDPNAMinimumSize + ndpLinkLayerAddressSize\n+ ICMPv6NeighborAdvertSize = ICMPv6HeaderSize + NDPNAMinimumSize + NDPLinkLayerAddressSize\n// ICMPv6EchoMinimumSize is the minimum size of a valid ICMP echo packet.\nICMPv6EchoMinimumSize = 8\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ndp_options.go", "new_path": "pkg/tcpip/header/ndp_options.go", "diff": "@@ -17,6 +17,7 @@ package header\nimport (\n\"encoding/binary\"\n\"errors\"\n+ \"fmt\"\n\"math\"\n\"time\"\n@@ -32,9 +33,9 @@ const (\n// Address option, as per RFC 4861 section 4.6.1.\nNDPTargetLinkLayerAddressOptionType = 2\n- // ndpLinkLayerAddressSize is the size of a Source or Target Link Layer\n- // Address option.\n- ndpLinkLayerAddressSize = 8\n+ // NDPLinkLayerAddressSize is the size of a Source or Target Link Layer\n+ // Address option for an Ethernet address.\n+ NDPLinkLayerAddressSize = 8\n// NDPPrefixInformationType is the type of the Prefix Information\n// option, as per RFC 4861 section 4.6.2.\n@@ -300,6 +301,8 @@ func (b NDPOptions) Serialize(s NDPOptionsSerializer) int {\n// NDPOption is the set of functions to be implemented by all NDP option types.\ntype NDPOption interface {\n+ fmt.Stringer\n+\n// Type returns the type of the receiver.\nType() uint8\n@@ -397,6 +400,11 @@ func (o NDPSourceLinkLayerAddressOption) serializeInto(b []byte) int {\nreturn copy(b, o)\n}\n+// String implements fmt.Stringer.String.\n+func (o NDPSourceLinkLayerAddressOption) String() string {\n+ return fmt.Sprintf(\"%T(%s)\", o, tcpip.LinkAddress(o))\n+}\n+\n// EthernetAddress will return an ethernet (MAC) address if the\n// NDPSourceLinkLayerAddressOption's body has at minimum EthernetAddressSize\n// bytes. If the body has more than EthernetAddressSize bytes, only the first\n@@ -432,6 +440,11 @@ func (o NDPTargetLinkLayerAddressOption) serializeInto(b []byte) int {\nreturn copy(b, o)\n}\n+// String implements fmt.Stringer.String.\n+func (o NDPTargetLinkLayerAddressOption) String() string {\n+ return fmt.Sprintf(\"%T(%s)\", o, tcpip.LinkAddress(o))\n+}\n+\n// EthernetAddress will return an ethernet (MAC) address if the\n// NDPTargetLinkLayerAddressOption's body has at minimum EthernetAddressSize\n// bytes. If the body has more than EthernetAddressSize bytes, only the first\n@@ -478,6 +491,17 @@ func (o NDPPrefixInformation) serializeInto(b []byte) int {\nreturn used\n}\n+// String implements fmt.Stringer.String.\n+func (o NDPPrefixInformation) String() string {\n+ return fmt.Sprintf(\"%T(O=%t, A=%t, PL=%s, VL=%s, Prefix=%s)\",\n+ o,\n+ o.OnLinkFlag(),\n+ o.AutonomousAddressConfigurationFlag(),\n+ o.PreferredLifetime(),\n+ o.ValidLifetime(),\n+ o.Subnet())\n+}\n+\n// PrefixLength returns the value in the number of leading bits in the Prefix\n// that are valid.\n//\n@@ -587,6 +611,11 @@ func (o NDPRecursiveDNSServer) serializeInto(b []byte) int {\nreturn used\n}\n+// String implements fmt.Stringer.String.\n+func (o NDPRecursiveDNSServer) String() string {\n+ return fmt.Sprintf(\"%T(%s valid for %s)\", o, o.Addresses(), o.Lifetime())\n+}\n+\n// Lifetime returns the length of time that the DNS server addresses\n// in this option may be used for name resolution.\n//\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -538,11 +538,29 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address) *tcpip.Error {\nr := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, snmc, ndp.nic.linkEP.LinkAddress(), ref, false, false)\ndefer r.Release()\n- hdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6NeighborSolicitMinimumSize)\n- pkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborSolicitMinimumSize))\n+ linkAddr := ndp.nic.linkEP.LinkAddress()\n+ isValidLinkAddr := header.IsValidUnicastEthernetAddress(linkAddr)\n+ ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize\n+ if isValidLinkAddr {\n+ // Only include a Source Link Layer Address option if the NIC has a valid\n+ // link layer address.\n+ //\n+ // TODO(b/141011931): Validate a LinkEndpoint's link address (provided by\n+ // LinkEndpoint.LinkAddress) before reaching this point.\n+ ndpNSSize += header.NDPLinkLayerAddressSize\n+ }\n+\n+ hdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + ndpNSSize)\n+ pkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\npkt.SetType(header.ICMPv6NeighborSolicit)\nns := header.NDPNeighborSolicit(pkt.NDPPayload())\nns.SetTargetAddress(addr)\n+\n+ if isValidLinkAddr {\n+ ns.Options().Serialize(header.NDPOptionsSerializer{\n+ header.NDPSourceLinkLayerAddressOption(linkAddr),\n+ })\n+ }\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\nsent := r.Stats().ICMP.V6PacketsSent\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -417,7 +417,11 @@ func TestDADResolve(t *testing.T) {\nchecker.IPv6(t, p.Pkt.Header.View().ToVectorisedView().First(),\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPNS(\n- checker.NDPNSTargetAddress(addr1)))\n+ checker.NDPNSTargetAddress(addr1),\n+ checker.NDPNSOptions([]header.NDPOption{\n+ header.NDPSourceLinkLayerAddressOption(linkAddr1),\n+ }),\n+ ))\n}\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Include the NDP Source Link Layer option when sending DAD messages Test: stack_test.TestDADResolve PiperOrigin-RevId: 292003124
259,885
28.01.2020 15:04:34
28,800
2862b0b1be9ce821e86877802b9608aad3102916
Add //pkg/sentry/fsimpl/devtmpfs.
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/devtmpfs/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"devtmpfs\",\n+ srcs = [\"devtmpfs.go\"],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/context\",\n+ \"//pkg/fspath\",\n+ \"//pkg/sentry/fsimpl/tmpfs\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/sync\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"devtmpfs_test\",\n+ size = \"small\",\n+ srcs = [\"devtmpfs_test.go\"],\n+ library = \":devtmpfs\",\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/fspath\",\n+ \"//pkg/sentry/contexttest\",\n+ \"//pkg/sentry/fsimpl/tmpfs\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package devtmpfs provides an implementation of /dev based on tmpfs,\n+// analogous to Linux's devtmpfs.\n+package devtmpfs\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+)\n+\n+// FilesystemType implements vfs.FilesystemType.\n+type FilesystemType struct {\n+ initOnce sync.Once\n+ initErr error\n+\n+ // fs is the tmpfs filesystem that backs all mounts of this FilesystemType.\n+ // root is fs' root. fs and root are immutable.\n+ fs *vfs.Filesystem\n+ root *vfs.Dentry\n+}\n+\n+// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\n+func (fst *FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ fst.initOnce.Do(func() {\n+ fs, root, err := tmpfs.FilesystemType{}.GetFilesystem(ctx, vfsObj, creds, \"\" /* source */, vfs.GetFilesystemOptions{\n+ Data: \"mode=0755\", // opts from drivers/base/devtmpfs.c:devtmpfs_init()\n+ })\n+ if err != nil {\n+ fst.initErr = err\n+ return\n+ }\n+ fst.fs = fs\n+ fst.root = root\n+ })\n+ if fst.initErr != nil {\n+ return nil, nil, fst.initErr\n+ }\n+ fst.fs.IncRef()\n+ fst.root.IncRef()\n+ return fst.fs, fst.root, nil\n+}\n+\n+// Accessor allows devices to create device special files in devtmpfs.\n+type Accessor struct {\n+ vfsObj *vfs.VirtualFilesystem\n+ mntns *vfs.MountNamespace\n+ root vfs.VirtualDentry\n+ creds *auth.Credentials\n+}\n+\n+// NewAccessor returns an Accessor that supports creation of device special\n+// files in the devtmpfs instance registered with name fsTypeName in vfsObj.\n+func NewAccessor(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, fsTypeName string) (*Accessor, error) {\n+ mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"devtmpfs\" /* source */, fsTypeName, &vfs.GetFilesystemOptions{})\n+ if err != nil {\n+ return nil, err\n+ }\n+ return &Accessor{\n+ vfsObj: vfsObj,\n+ mntns: mntns,\n+ root: mntns.Root(),\n+ creds: creds,\n+ }, nil\n+}\n+\n+// Release must be called when a is no longer in use.\n+func (a *Accessor) Release() {\n+ a.root.DecRef()\n+ a.mntns.DecRef(a.vfsObj)\n+}\n+\n+// accessorContext implements context.Context by extending an existing\n+// context.Context with an Accessor's values for VFS-relevant state.\n+type accessorContext struct {\n+ context.Context\n+ a *Accessor\n+}\n+\n+func (a *Accessor) wrapContext(ctx context.Context) *accessorContext {\n+ return &accessorContext{\n+ Context: ctx,\n+ a: a,\n+ }\n+}\n+\n+// Value implements context.Context.Value.\n+func (ac *accessorContext) Value(key interface{}) interface{} {\n+ switch key {\n+ case vfs.CtxMountNamespace:\n+ return ac.a.mntns\n+ case vfs.CtxRoot:\n+ ac.a.root.IncRef()\n+ return ac.a.root\n+ default:\n+ return ac.Context.Value(key)\n+ }\n+}\n+\n+func (a *Accessor) pathOperationAt(pathname string) *vfs.PathOperation {\n+ return &vfs.PathOperation{\n+ Root: a.root,\n+ Start: a.root,\n+ Path: fspath.Parse(pathname),\n+ }\n+}\n+\n+// CreateDeviceFile creates a device special file at the given pathname in the\n+// devtmpfs instance accessed by the Accessor.\n+func (a *Accessor) CreateDeviceFile(ctx context.Context, pathname string, kind vfs.DeviceKind, major, minor uint32, perms uint16) error {\n+ mode := (linux.FileMode)(perms)\n+ switch kind {\n+ case vfs.BlockDevice:\n+ mode |= linux.S_IFBLK\n+ case vfs.CharDevice:\n+ mode |= linux.S_IFCHR\n+ default:\n+ panic(fmt.Sprintf(\"invalid vfs.DeviceKind: %v\", kind))\n+ }\n+ // NOTE: Linux's devtmpfs refuses to automatically delete files it didn't\n+ // create, which it recognizes by storing a pointer to the kdevtmpfs struct\n+ // thread in struct inode::i_private. Accessor doesn't yet support deletion\n+ // of files at all, and probably won't as long as we don't need to support\n+ // kernel modules, so this is moot for now.\n+ return a.vfsObj.MknodAt(a.wrapContext(ctx), a.creds, a.pathOperationAt(pathname), &vfs.MknodOptions{\n+ Mode: mode,\n+ DevMajor: major,\n+ DevMinor: minor,\n+ })\n+}\n+\n+// UserspaceInit creates symbolic links and mount points in the devtmpfs\n+// instance accessed by the Accessor that are created by userspace in Linux. It\n+// does not create mounts.\n+func (a *Accessor) UserspaceInit(ctx context.Context) error {\n+ actx := a.wrapContext(ctx)\n+\n+ // systemd: src/shared/dev-setup.c:dev_setup()\n+ for _, symlink := range []struct {\n+ source string\n+ target string\n+ }{\n+ // /proc/kcore is not implemented.\n+ {source: \"fd\", target: \"/proc/self/fd\"},\n+ {source: \"stdin\", target: \"/proc/self/fd/0\"},\n+ {source: \"stdout\", target: \"/proc/self/fd/1\"},\n+ {source: \"stderr\", target: \"/proc/self/fd/2\"},\n+ } {\n+ if err := a.vfsObj.SymlinkAt(actx, a.creds, a.pathOperationAt(symlink.source), symlink.target); err != nil {\n+ return fmt.Errorf(\"failed to create symlink %q => %q: %v\", symlink.source, symlink.target, err)\n+ }\n+ }\n+\n+ // systemd: src/core/mount-setup.c:mount_table\n+ for _, dir := range []string{\n+ \"shm\",\n+ \"pts\",\n+ } {\n+ if err := a.vfsObj.MkdirAt(actx, a.creds, a.pathOperationAt(dir), &vfs.MkdirOptions{\n+ // systemd: src/core/mount-setup.c:mount_one()\n+ Mode: 0755,\n+ }); err != nil {\n+ return fmt.Errorf(\"failed to create directory %q: %v\", dir, err)\n+ }\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package devtmpfs\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+func TestDevtmpfs(t *testing.T) {\n+ ctx := contexttest.Context(t)\n+ creds := auth.CredentialsFromContext(ctx)\n+\n+ vfsObj := vfs.New()\n+ // Register tmpfs just so that we can have a root filesystem that isn't\n+ // devtmpfs.\n+ vfsObj.MustRegisterFilesystemType(\"tmpfs\", tmpfs.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\n+ vfsObj.MustRegisterFilesystemType(\"devtmpfs\", &FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\n+\n+ // Create a test mount namespace with devtmpfs mounted at \"/dev\".\n+ const devPath = \"/dev\"\n+ mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"tmpfs\" /* source */, \"tmpfs\" /* fsTypeName */, &vfs.GetFilesystemOptions{})\n+ if err != nil {\n+ t.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n+ }\n+ defer mntns.DecRef(vfsObj)\n+ root := mntns.Root()\n+ defer root.DecRef()\n+ devpop := vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(devPath),\n+ }\n+ if err := vfsObj.MkdirAt(ctx, creds, &devpop, &vfs.MkdirOptions{\n+ Mode: 0755,\n+ }); err != nil {\n+ t.Fatalf(\"failed to create mount point: %v\", err)\n+ }\n+ if err := vfsObj.MountAt(ctx, creds, \"devtmpfs\" /* source */, &devpop, \"devtmpfs\" /* fsTypeName */, &vfs.MountOptions{}); err != nil {\n+ t.Fatalf(\"failed to mount devtmpfs: %v\", err)\n+ }\n+\n+ a, err := NewAccessor(ctx, vfsObj, creds, \"devtmpfs\")\n+ if err != nil {\n+ t.Fatalf(\"failed to create devtmpfs.Accessor: %v\", err)\n+ }\n+ defer a.Release()\n+\n+ // Create \"userspace-initialized\" files using a devtmpfs.Accessor.\n+ if err := a.UserspaceInit(ctx); err != nil {\n+ t.Fatalf(\"failed to userspace-initialize devtmpfs: %v\", err)\n+ }\n+ // Created files should be visible in the test mount namespace.\n+ abspath := devPath + \"/fd\"\n+ target, err := vfsObj.ReadlinkAt(ctx, creds, &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(abspath),\n+ })\n+ if want := \"/proc/self/fd\"; err != nil || target != want {\n+ t.Fatalf(\"readlink(%q): got (%q, %v), wanted (%q, nil)\", abspath, target, err, want)\n+ }\n+\n+ // Create a dummy device special file using a devtmpfs.Accessor.\n+ const (\n+ pathInDev = \"dummy\"\n+ kind = vfs.CharDevice\n+ major = 12\n+ minor = 34\n+ perms = 0600\n+ wantMode = linux.S_IFCHR | perms\n+ )\n+ if err := a.CreateDeviceFile(ctx, pathInDev, kind, major, minor, perms); err != nil {\n+ t.Fatalf(\"failed to create device file: %v\", err)\n+ }\n+ // The device special file should be visible in the test mount namespace.\n+ abspath = devPath + \"/\" + pathInDev\n+ stat, err := vfsObj.StatAt(ctx, creds, &vfs.PathOperation{\n+ Root: root,\n+ Start: root,\n+ Path: fspath.Parse(abspath),\n+ }, &vfs.StatOptions{\n+ Mask: linux.STATX_TYPE | linux.STATX_MODE,\n+ })\n+ if err != nil {\n+ t.Fatalf(\"failed to stat device file at %q: %v\", abspath, err)\n+ }\n+ if stat.Mode != wantMode {\n+ t.Errorf(\"device file mode: got %v, wanted %v\", stat.Mode, wantMode)\n+ }\n+ if stat.RdevMajor != major {\n+ t.Errorf(\"major device number: got %v, wanted %v\", stat.RdevMajor, major)\n+ }\n+ if stat.RdevMinor != minor {\n+ t.Errorf(\"minor device number: got %v, wanted %v\", stat.RdevMinor, minor)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "new_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "diff": "@@ -27,6 +27,7 @@ go_library(\n\"symlink.go\",\n\"tmpfs.go\",\n],\n+ visibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/amutex\",\n" } ]
Go
Apache License 2.0
google/gvisor
Add //pkg/sentry/fsimpl/devtmpfs. PiperOrigin-RevId: 292021389
260,004
28.01.2020 15:39:48
28,800
431ff52768c2300e15cba609c2be4f507fd30d5b
Update link address for senders of Neighbor Solicitations Update link address for senders of NDP Neighbor Solicitations when the NS contains an NDP Source Link Layer Address option. Tests: ipv6.TestNeighorSolicitationWithSourceLinkLayerOption ipv6.TestNeighorSolicitationWithInvalidSourceLinkLayerOption
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -137,21 +137,24 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\n}\nns := header.NDPNeighborSolicit(h.NDPPayload())\n+ it, err := ns.Options().Iter(true)\n+ if err != nil {\n+ // If we have a malformed NDP NS option, drop the packet.\n+ received.Invalid.Increment()\n+ return\n+ }\n+\ntargetAddr := ns.TargetAddress()\ns := r.Stack()\nrxNICID := r.NICID()\n-\n- isTentative, err := s.IsAddrTentative(rxNICID, targetAddr)\n- if err != nil {\n+ if isTentative, err := s.IsAddrTentative(rxNICID, targetAddr); err != nil {\n// We will only get an error if rxNICID is unrecognized,\n// which should not happen. For now short-circuit this\n// packet.\n//\n// TODO(b/141002840): Handle this better?\nreturn\n- }\n-\n- if isTentative {\n+ } else if isTentative {\n// If the target address is tentative and the source\n// of the packet is a unicast (specified) address, then\n// the source of the packet is attempting to perform\n@@ -185,6 +188,23 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\nreturn\n}\n+ // If the NS message has the source link layer option, update the link\n+ // address cache with the link address for the sender of the message.\n+ //\n+ // TODO(b/148429853): Properly process the NS message and do Neighbor\n+ // Unreachability Detection.\n+ for {\n+ opt, done, _ := it.Next()\n+ if done {\n+ break\n+ }\n+\n+ switch opt := opt.(type) {\n+ case header.NDPSourceLinkLayerAddressOption:\n+ e.linkAddrCache.AddLinkAddress(e.nicID, r.RemoteAddress, opt.EthernetAddress())\n+ }\n+ }\n+\noptsSerializer := header.NDPOptionsSerializer{\nheader.NDPTargetLinkLayerAddressOption(r.LocalLinkAddress[:]),\n}\n@@ -211,15 +231,6 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\nr.LocalAddress = targetAddr\npacket.SetChecksum(header.ICMPv6Checksum(packet, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n- // TODO(tamird/ghanan): there exists an explicit NDP option that is\n- // used to update the neighbor table with link addresses for a\n- // neighbor from an NS (see the Source Link Layer option RFC\n- // 4861 section 4.6.1 and section 7.2.3).\n- //\n- // Furthermore, the entirety of NDP handling here seems to be\n- // contradicted by RFC 4861.\n- e.linkAddrCache.AddLinkAddress(e.nicID, r.RemoteAddress, r.RemoteLinkAddress)\n-\n// RFC 4861 Neighbor Discovery for IP version 6 (IPv6)\n//\n// 7.1.2. Validation of Neighbor Advertisements\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -70,6 +70,141 @@ func setupStackAndEndpoint(t *testing.T, llladdr, rlladdr tcpip.Address) (*stack\nreturn s, ep\n}\n+// TestNeighorSolicitationWithSourceLinkLayerOption tests that receiving an\n+// NDP NS message with the Source Link Layer Address option results in a\n+// new entry in the link address cache for the sender of the message.\n+func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\n+ const nicID = 1\n+\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{NewProtocol()},\n+ })\n+ e := channel.New(0, 1280, linkAddr0)\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n+ }\n+ if err := s.AddAddress(nicID, ProtocolNumber, lladdr0); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, ProtocolNumber, lladdr0, err)\n+ }\n+\n+ ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize + header.NDPLinkLayerAddressSize\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNSSize)\n+ pkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\n+ pkt.SetType(header.ICMPv6NeighborSolicit)\n+ ns := header.NDPNeighborSolicit(pkt.NDPPayload())\n+ ns.SetTargetAddress(lladdr0)\n+ ns.Options().Serialize(header.NDPOptionsSerializer{\n+ header.NDPSourceLinkLayerAddressOption(linkAddr1),\n+ })\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, buffer.VectorisedView{}))\n+ payloadLength := hdr.UsedLength()\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLength),\n+ NextHeader: uint8(header.ICMPv6ProtocolNumber),\n+ HopLimit: 255,\n+ SrcAddr: lladdr1,\n+ DstAddr: lladdr0,\n+ })\n+ e.InjectInbound(ProtocolNumber, tcpip.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+\n+ linkAddr, c, err := s.GetLinkAddress(nicID, lladdr1, lladdr0, ProtocolNumber, nil)\n+ if err != nil {\n+ t.Errorf(\"s.GetLinkAddress(%d, %s, %s, %d, nil): %s\", nicID, lladdr1, lladdr0, ProtocolNumber, err)\n+ }\n+ if c != nil {\n+ t.Errorf(\"got unexpected channel\")\n+ }\n+ if linkAddr != linkAddr1 {\n+ t.Errorf(\"got link address = %s, want = %s\", linkAddr, linkAddr1)\n+ }\n+}\n+\n+// TestNeighorSolicitationWithInvalidSourceLinkLayerOption tests that receiving\n+// an NDP NS message with an invalid Source Link Layer Address option does not\n+// result in a new entry in the link address cache for the sender of the\n+// message.\n+func TestNeighorSolicitationWithInvalidSourceLinkLayerOption(t *testing.T) {\n+ const nicID = 1\n+\n+ tests := []struct {\n+ name string\n+ optsBuf []byte\n+ }{\n+ {\n+ name: \"Too Small\",\n+ optsBuf: []byte{1, 1, 1, 2, 3, 4, 5},\n+ },\n+ {\n+ name: \"Invalid Length\",\n+ optsBuf: []byte{1, 2, 1, 2, 3, 4, 5, 6},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{NewProtocol()},\n+ })\n+ e := channel.New(0, 1280, linkAddr0)\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n+ }\n+ if err := s.AddAddress(nicID, ProtocolNumber, lladdr0); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, ProtocolNumber, lladdr0, err)\n+ }\n+\n+ ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize + len(test.optsBuf)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNSSize)\n+ pkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\n+ pkt.SetType(header.ICMPv6NeighborSolicit)\n+ ns := header.NDPNeighborSolicit(pkt.NDPPayload())\n+ ns.SetTargetAddress(lladdr0)\n+ opts := ns.Options()\n+ copy(opts, test.optsBuf)\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, buffer.VectorisedView{}))\n+ payloadLength := hdr.UsedLength()\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLength),\n+ NextHeader: uint8(header.ICMPv6ProtocolNumber),\n+ HopLimit: 255,\n+ SrcAddr: lladdr1,\n+ DstAddr: lladdr0,\n+ })\n+\n+ invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+\n+ // Invalid count should initially be 0.\n+ if got := invalid.Value(); got != 0 {\n+ t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ }\n+\n+ e.InjectInbound(ProtocolNumber, tcpip.PacketBuffer{\n+ Data: hdr.View().ToVectorisedView(),\n+ })\n+\n+ // Invalid count should have increased.\n+ if got := invalid.Value(); got != 1 {\n+ t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ }\n+\n+ linkAddr, c, err := s.GetLinkAddress(nicID, lladdr1, lladdr0, ProtocolNumber, nil)\n+ if err != tcpip.ErrWouldBlock {\n+ t.Errorf(\"got s.GetLinkAddress(%d, %s, %s, %d, nil) = (_, _, %v), want = (_, _, %s)\", nicID, lladdr1, lladdr0, ProtocolNumber, err, tcpip.ErrWouldBlock)\n+ }\n+ if c == nil {\n+ t.Errorf(\"expected channel from call to s.GetLinkAddress(%d, %s, %s, %d, nil)\", nicID, lladdr1, lladdr0, ProtocolNumber)\n+ }\n+ if linkAddr != \"\" {\n+ t.Errorf(\"got s.GetLinkAddress(%d, %s, %s, %d, nil) = (%s, _, ), want = ('', _, _)\", nicID, lladdr1, lladdr0, ProtocolNumber, linkAddr)\n+ }\n+ })\n+ }\n+}\n+\n// TestHopLimitValidation is a test that makes sure that NDP packets are only\n// received if their IP header's hop limit is set to 255.\nfunc TestHopLimitValidation(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Update link address for senders of Neighbor Solicitations Update link address for senders of NDP Neighbor Solicitations when the NS contains an NDP Source Link Layer Address option. Tests: - ipv6.TestNeighorSolicitationWithSourceLinkLayerOption - ipv6.TestNeighorSolicitationWithInvalidSourceLinkLayerOption PiperOrigin-RevId: 292028553
259,992
28.01.2020 16:42:05
28,800
3d046fef06ece6ba20770fa62e0a21569226adaa
Changes missing in last submit Updates Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/fd_table.go", "new_path": "pkg/sentry/kernel/fd_table.go", "diff": "package kernel\nimport (\n- \"bytes\"\n\"fmt\"\n\"math\"\n+ \"strings\"\n\"sync/atomic\"\n\"syscall\"\n@@ -221,24 +221,24 @@ func (f *FDTable) forEach(fn func(fd int32, file *fs.File, fileVFS2 *vfs.FileDes\n// String is a stringer for FDTable.\nfunc (f *FDTable) String() string {\n- var b bytes.Buffer\n+ var buf strings.Builder\nf.forEach(func(fd int32, file *fs.File, fileVFS2 *vfs.FileDescription, flags FDFlags) {\nswitch {\ncase file != nil:\nn, _ := file.Dirent.FullName(nil /* root */)\n- b.WriteString(fmt.Sprintf(\"\\tfd:%d => name %s\\n\", fd, n))\n+ fmt.Fprintf(&buf, \"\\tfd:%d => name %s\\n\", fd, n)\ncase fileVFS2 != nil:\n- fs := fileVFS2.VirtualDentry().Mount().Filesystem().VirtualFilesystem()\n- // TODO(gvisor.dev/issue/1623): We have no context nor root. Will this work?\n- name, err := fs.PathnameWithDeleted(context.Background(), vfs.VirtualDentry{}, fileVFS2.VirtualDentry())\n+ vfsObj := fileVFS2.Mount().Filesystem().VirtualFilesystem()\n+ name, err := vfsObj.PathnameWithDeleted(context.Background(), vfs.VirtualDentry{}, fileVFS2.VirtualDentry())\nif err != nil {\n- b.WriteString(fmt.Sprintf(\"<err: %v>\\n\", err))\n+ fmt.Fprintf(&buf, \"<err: %v>\\n\", err)\n+ return\n}\n- b.WriteString(fmt.Sprintf(\"\\tfd:%d => name %s\\n\", fd, name))\n+ fmt.Fprintf(&buf, \"\\tfd:%d => name %s\\n\", fd, name)\n}\n})\n- return b.String()\n+ return buf.String()\n}\n// NewFDs allocates new FDs guaranteed to be the lowest number available\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_read.go", "new_path": "pkg/sentry/syscalls/linux/sys_read.go", "diff": "@@ -29,7 +29,7 @@ import (\n)\nconst (\n- // EventMaskRead contains events that can be triggerd on reads.\n+ // EventMaskRead contains events that can be triggered on reads.\nEventMaskRead = waiter.EventIn | waiter.EventHUp | waiter.EventErr\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/sys_read.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/sys_read.go", "diff": "@@ -24,6 +24,11 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+const (\n+ // EventMaskRead contains events that can be triggered on reads.\n+ EventMaskRead = waiter.EventIn | waiter.EventHUp | waiter.EventErr\n+)\n+\n// Read implements linux syscall read(2). Note that we try to get a buffer that\n// is exactly the size requested because some applications like qemu expect\n// they can do large reads all at once. Bug for bug. Same for other read\n@@ -39,11 +44,6 @@ func Read(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\n}\ndefer file.DecRef()\n- // Check that the file is readable.\n- if !file.IsReadable() {\n- return 0, nil, syserror.EBADF\n- }\n-\n// Check that the size is legitimate.\nsi := int(size)\nif si < 0 {\n@@ -70,8 +70,8 @@ func read(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, opt\n}\n// Register for notifications.\n- _, ch := waiter.NewChannelEntry(nil)\n- // file.EventRegister(&w, EventMaskRead)\n+ w, ch := waiter.NewChannelEntry(nil)\n+ file.EventRegister(&w, EventMaskRead)\ntotal := n\nfor {\n@@ -89,7 +89,7 @@ func read(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, opt\nbreak\n}\n}\n- //file.EventUnregister(&w)\n+ file.EventUnregister(&w)\nreturn total, err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Changes missing in last submit Updates #1487 Updates #1623 PiperOrigin-RevId: 292040835
259,992
28.01.2020 18:30:36
28,800
396c574db276ae1424af7098b5cd917e2bed9921
Add support for WritableSource in DynamicBytesFileDescriptionImpl WritableSource is a convenience interface used for files that can be written to, e.g. /proc/net/ipv4/tpc_sack. It reads max of 4KB and only from offset 0 which should cover most cases. It can be extended as neeed. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "new_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "diff": "@@ -108,12 +108,12 @@ func (fd *DynamicBytesFD) PRead(ctx context.Context, dst usermem.IOSequence, off\n// Write implements vfs.FileDescriptionImpl.Write.\nfunc (fd *DynamicBytesFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n- return fd.FileDescriptionDefaultImpl.Write(ctx, src, opts)\n+ return fd.DynamicBytesFileDescriptionImpl.Write(ctx, src, opts)\n}\n// PWrite implements vfs.FileDescriptionImpl.PWrite.\nfunc (fd *DynamicBytesFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- return fd.FileDescriptionDefaultImpl.PWrite(ctx, src, offset, opts)\n+ return fd.DynamicBytesFileDescriptionImpl.PWrite(ctx, src, offset, opts)\n}\n// Release implements vfs.FileDescriptionImpl.Release.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -69,7 +69,7 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\n\"cpuinfo\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(cpuInfoData(k))),\n//\"filesystems\": newDentry(root, inoGen.NextIno(), 0444, &filesystemsData{}),\n\"loadavg\": newDentry(root, inoGen.NextIno(), 0444, &loadavgData{}),\n- \"sys\": newSysDir(root, inoGen),\n+ \"sys\": newSysDir(root, inoGen, k),\n\"meminfo\": newDentry(root, inoGen.NextIno(), 0444, &meminfoData{}),\n\"mounts\": kernfs.NewStaticSymlink(root, inoGen.NextIno(), \"self/mounts\"),\n\"net\": newNetDir(root, inoGen, k),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go", "diff": "@@ -21,12 +21,16 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\n// newSysDir returns the dentry corresponding to /proc/sys directory.\n-func newSysDir(root *auth.Credentials, inoGen InoGenerator) *kernfs.Dentry {\n+func newSysDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *kernfs.Dentry {\nreturn kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n\"kernel\": kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n\"hostname\": newDentry(root, inoGen.NextIno(), 0444, &hostnameData{}),\n@@ -38,18 +42,18 @@ func newSysDir(root *auth.Credentials, inoGen InoGenerator) *kernfs.Dentry {\n\"mmap_min_addr\": newDentry(root, inoGen.NextIno(), 0444, &mmapMinAddrData{}),\n\"overcommit_memory\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(\"0\\n\")),\n}),\n- \"net\": newSysNetDir(root, inoGen),\n+ \"net\": newSysNetDir(root, inoGen, k),\n})\n}\n// newSysNetDir returns the dentry corresponding to /proc/sys/net directory.\n-func newSysNetDir(root *auth.Credentials, inoGen InoGenerator) *kernfs.Dentry {\n- return kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n- \"net\": kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n+func newSysNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *kernfs.Dentry {\n+ var contents map[string]*kernfs.Dentry\n+\n+ if stack := k.NetworkStack(); stack != nil {\n+ contents = map[string]*kernfs.Dentry{\n\"ipv4\": kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n- // Add tcp_sack.\n- // TODO(gvisor.dev/issue/1195): tcp_sack allows write(2)\n- // \"tcp_sack\": newTCPSackInode(ctx, msrc, s),\n+ \"tcp_sack\": newDentry(root, inoGen.NextIno(), 0644, &tcpSackData{stack: stack}),\n// The following files are simple stubs until they are implemented in\n// netstack, most of these files are configuration related. We use the\n@@ -103,7 +107,11 @@ func newSysNetDir(root *auth.Credentials, inoGen InoGenerator) *kernfs.Dentry {\n\"wmem_default\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(\"212992\")),\n\"wmem_max\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(\"212992\")),\n}),\n- }),\n+ }\n+ }\n+\n+ return kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, map[string]*kernfs.Dentry{\n+ \"net\": kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, contents),\n})\n}\n@@ -141,3 +149,61 @@ func (*hostnameData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nbuf.WriteString(\"\\n\")\nreturn nil\n}\n+\n+// tcpSackData implements vfs.WritableDynamicBytesSource for\n+// /proc/sys/net/tcp_sack.\n+//\n+// +stateify savable\n+type tcpSackData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack `state:\"wait\"`\n+ enabled *bool\n+}\n+\n+var _ vfs.WritableDynamicBytesSource = (*tcpSackData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.\n+func (d *tcpSackData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ if d.enabled == nil {\n+ sack, err := d.stack.TCPSACKEnabled()\n+ if err != nil {\n+ return err\n+ }\n+ d.enabled = &sack\n+ }\n+\n+ val := \"0\\n\"\n+ if *d.enabled {\n+ // Technically, this is not quite compatible with Linux. Linux stores these\n+ // as an integer, so if you write \"2\" into tcp_sack, you should get 2 back.\n+ // Tough luck.\n+ val = \"1\\n\"\n+ }\n+ buf.WriteString(val)\n+ return nil\n+}\n+\n+func (d *tcpSackData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ if offset != 0 {\n+ // No need to handle partial writes thus far.\n+ return 0, syserror.EINVAL\n+ }\n+ if src.NumBytes() == 0 {\n+ return 0, nil\n+ }\n+\n+ // Limit the amount of memory allocated.\n+ src = src.TakeFirst(usermem.PageSize - 1)\n+\n+ var v int32\n+ n, err := usermem.CopyInt32StringInVec(ctx, src.IO, src.Addrs, &v, src.Opts)\n+ if err != nil {\n+ return n, err\n+ }\n+ if d.enabled == nil {\n+ d.enabled = new(bool)\n+ }\n+ *d.enabled = v != 0\n+ return n, d.stack.SetTCPSACKEnabled(*d.enabled)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -192,21 +192,6 @@ func (DentryMetadataFileDescriptionImpl) SetStat(ctx context.Context, opts SetSt\npanic(\"illegal call to DentryMetadataFileDescriptionImpl.SetStat\")\n}\n-// DynamicBytesFileDescriptionImpl may be embedded by implementations of\n-// FileDescriptionImpl that represent read-only regular files whose contents\n-// are backed by a bytes.Buffer that is regenerated when necessary, consistent\n-// with Linux's fs/seq_file.c:single_open().\n-//\n-// DynamicBytesFileDescriptionImpl.SetDataSource() must be called before first\n-// use.\n-type DynamicBytesFileDescriptionImpl struct {\n- data DynamicBytesSource // immutable\n- mu sync.Mutex // protects the following fields\n- buf bytes.Buffer\n- off int64\n- lastRead int64 // offset at which the last Read, PRead, or Seek ended\n-}\n-\n// DynamicBytesSource represents a data source for a\n// DynamicBytesFileDescriptionImpl.\ntype DynamicBytesSource interface {\n@@ -225,6 +210,30 @@ func (s *StaticData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n+// WritableDynamicBytesSource extends DynamicBytesSource to allow writes to the\n+// underlying source.\n+type WritableDynamicBytesSource interface {\n+ DynamicBytesSource\n+\n+ // Write sends writes to the source.\n+ Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error)\n+}\n+\n+// DynamicBytesFileDescriptionImpl may be embedded by implementations of\n+// FileDescriptionImpl that represent read-only regular files whose contents\n+// are backed by a bytes.Buffer that is regenerated when necessary, consistent\n+// with Linux's fs/seq_file.c:single_open().\n+//\n+// DynamicBytesFileDescriptionImpl.SetDataSource() must be called before first\n+// use.\n+type DynamicBytesFileDescriptionImpl struct {\n+ data DynamicBytesSource // immutable\n+ mu sync.Mutex // protects the following fields\n+ buf bytes.Buffer\n+ off int64\n+ lastRead int64 // offset at which the last Read, PRead, or Seek ended\n+}\n+\n// SetDataSource must be called exactly once on fd before first use.\nfunc (fd *DynamicBytesFileDescriptionImpl) SetDataSource(data DynamicBytesSource) {\nfd.data = data\n@@ -304,6 +313,43 @@ func (fd *DynamicBytesFileDescriptionImpl) Seek(ctx context.Context, offset int6\nreturn offset, nil\n}\n+// Preconditions: fd.mu must be locked.\n+func (fd *DynamicBytesFileDescriptionImpl) pwriteLocked(ctx context.Context, src usermem.IOSequence, offset int64, opts WriteOptions) (int64, error) {\n+ if opts.Flags&^(linux.RWF_HIPRI|linux.RWF_DSYNC|linux.RWF_SYNC) != 0 {\n+ return 0, syserror.EOPNOTSUPP\n+ }\n+\n+ writable, ok := fd.data.(WritableDynamicBytesSource)\n+ if !ok {\n+ return 0, syserror.EINVAL\n+ }\n+ n, err := writable.Write(ctx, src, offset)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ // Invalidate cached data that might exist prior to this call.\n+ fd.buf.Reset()\n+ return n, nil\n+}\n+\n+// PWrite implements FileDescriptionImpl.PWrite.\n+func (fd *DynamicBytesFileDescriptionImpl) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts WriteOptions) (int64, error) {\n+ fd.mu.Lock()\n+ n, err := fd.pwriteLocked(ctx, src, offset, opts)\n+ fd.mu.Unlock()\n+ return n, err\n+}\n+\n+// Write implements FileDescriptionImpl.Write.\n+func (fd *DynamicBytesFileDescriptionImpl) Write(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error) {\n+ fd.mu.Lock()\n+ n, err := fd.pwriteLocked(ctx, src, fd.off, opts)\n+ fd.off += n\n+ fd.mu.Unlock()\n+ return n, err\n+}\n+\n// GenericConfigureMMap may be used by most implementations of\n// FileDescriptionImpl.ConfigureMMap.\nfunc GenericConfigureMMap(fd *FileDescription, m memmap.Mappable, opts *memmap.MMapOpts) error {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "new_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "diff": "@@ -35,61 +35,80 @@ type fileDescription struct {\nFileDescriptionDefaultImpl\n}\n-// genCountFD is a read-only FileDescriptionImpl representing a regular file\n-// that contains the number of times its DynamicBytesSource.Generate()\n+// genCount contains the number of times its DynamicBytesSource.Generate()\n// implementation has been called.\n-type genCountFD struct {\n+type genCount struct {\n+ count uint64 // accessed using atomic memory ops\n+}\n+\n+// Generate implements DynamicBytesSource.Generate.\n+func (g *genCount) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"%d\", atomic.AddUint64(&g.count, 1))\n+ return nil\n+}\n+\n+type storeData struct {\n+ data string\n+}\n+\n+var _ WritableDynamicBytesSource = (*storeData)(nil)\n+\n+// Generate implements DynamicBytesSource.\n+func (d *storeData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ buf.WriteString(d.data)\n+ return nil\n+}\n+\n+// Generate implements WritableDynamicBytesSource.\n+func (d *storeData) Write(ctx context.Context, src usermem.IOSequence, offset int64) (int64, error) {\n+ buf := make([]byte, src.NumBytes())\n+ n, err := src.CopyIn(ctx, buf)\n+ if err != nil {\n+ return 0, err\n+ }\n+\n+ d.data = string(buf[:n])\n+ return 0, nil\n+}\n+\n+// testFD is a read-only FileDescriptionImpl representing a regular file.\n+type testFD struct {\nfileDescription\nDynamicBytesFileDescriptionImpl\n- count uint64 // accessed using atomic memory ops\n+ data DynamicBytesSource\n}\n-func newGenCountFD(vfsObj *VirtualFilesystem) *FileDescription {\n+func newTestFD(vfsObj *VirtualFilesystem, statusFlags uint32, data DynamicBytesSource) *FileDescription {\nvd := vfsObj.NewAnonVirtualDentry(\"genCountFD\")\ndefer vd.DecRef()\n- var fd genCountFD\n- fd.vfsfd.Init(&fd, 0 /* statusFlags */, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{})\n- fd.DynamicBytesFileDescriptionImpl.SetDataSource(&fd)\n+ var fd testFD\n+ fd.vfsfd.Init(&fd, statusFlags, vd.Mount(), vd.Dentry(), &FileDescriptionOptions{})\n+ fd.DynamicBytesFileDescriptionImpl.SetDataSource(data)\nreturn &fd.vfsfd\n}\n// Release implements FileDescriptionImpl.Release.\n-func (fd *genCountFD) Release() {\n-}\n-\n-// StatusFlags implements FileDescriptionImpl.StatusFlags.\n-func (fd *genCountFD) StatusFlags(ctx context.Context) (uint32, error) {\n- return 0, nil\n+func (fd *testFD) Release() {\n}\n// SetStatusFlags implements FileDescriptionImpl.SetStatusFlags.\n-func (fd *genCountFD) SetStatusFlags(ctx context.Context, flags uint32) error {\n- return syserror.EPERM\n-}\n-\n// Stat implements FileDescriptionImpl.Stat.\n-func (fd *genCountFD) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n+func (fd *testFD) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n// Note that Statx.Mask == 0 in the return value.\nreturn linux.Statx{}, nil\n}\n// SetStat implements FileDescriptionImpl.SetStat.\n-func (fd *genCountFD) SetStat(ctx context.Context, opts SetStatOptions) error {\n+func (fd *testFD) SetStat(ctx context.Context, opts SetStatOptions) error {\nreturn syserror.EPERM\n}\n-// Generate implements DynamicBytesSource.Generate.\n-func (fd *genCountFD) Generate(ctx context.Context, buf *bytes.Buffer) error {\n- fmt.Fprintf(buf, \"%d\", atomic.AddUint64(&fd.count, 1))\n- return nil\n-}\n-\nfunc TestGenCountFD(t *testing.T) {\nctx := contexttest.Context(t)\nvfsObj := New() // vfs.New()\n- fd := newGenCountFD(vfsObj)\n+ fd := newTestFD(vfsObj, linux.O_RDWR, &genCount{})\ndefer fd.DecRef()\n// The first read causes Generate to be called to fill the FD's buffer.\n@@ -130,4 +149,69 @@ func TestGenCountFD(t *testing.T) {\nif want := byte('3'); buf[0] != want {\nt.Errorf(\"PRead: got byte %c, wanted %c\", buf[0], want)\n}\n+\n+ // Write and PWrite fails.\n+ if _, err := fd.Write(ctx, ioseq, WriteOptions{}); err != syserror.EINVAL {\n+ t.Errorf(\"Write: got err %v, wanted %v\", err, syserror.EINVAL)\n+ }\n+ if _, err := fd.PWrite(ctx, ioseq, 0, WriteOptions{}); err != syserror.EINVAL {\n+ t.Errorf(\"Write: got err %v, wanted %v\", err, syserror.EINVAL)\n+ }\n+}\n+\n+func TestWritable(t *testing.T) {\n+ ctx := contexttest.Context(t)\n+\n+ vfsObj := New() // vfs.New()\n+ fd := newTestFD(vfsObj, linux.O_RDWR, &storeData{data: \"init\"})\n+ defer fd.DecRef()\n+\n+ buf := make([]byte, 10)\n+ ioseq := usermem.BytesIOSequence(buf)\n+ if n, err := fd.Read(ctx, ioseq, ReadOptions{}); n != 4 && err != io.EOF {\n+ t.Fatalf(\"Read: got (%v, %v), wanted (4, EOF)\", n, err)\n+ }\n+ if want := \"init\"; want == string(buf) {\n+ t.Fatalf(\"Read: got %v, wanted %v\", string(buf), want)\n+ }\n+\n+ // Test PWrite.\n+ want := \"write\"\n+ writeIOSeq := usermem.BytesIOSequence([]byte(want))\n+ if n, err := fd.PWrite(ctx, writeIOSeq, 0, WriteOptions{}); int(n) != len(want) && err != nil {\n+ t.Errorf(\"PWrite: got err (%v, %v), wanted (%v, nil)\", n, err, len(want))\n+ }\n+ if n, err := fd.PRead(ctx, ioseq, 0, ReadOptions{}); int(n) != len(want) && err != io.EOF {\n+ t.Fatalf(\"PRead: got (%v, %v), wanted (%v, EOF)\", n, err, len(want))\n+ }\n+ if want == string(buf) {\n+ t.Fatalf(\"PRead: got %v, wanted %v\", string(buf), want)\n+ }\n+\n+ // Test Seek to 0 followed by Write.\n+ want = \"write2\"\n+ writeIOSeq = usermem.BytesIOSequence([]byte(want))\n+ if n, err := fd.Seek(ctx, 0, linux.SEEK_SET); n != 0 && err != nil {\n+ t.Errorf(\"Seek: got err (%v, %v), wanted (0, nil)\", n, err)\n+ }\n+ if n, err := fd.Write(ctx, writeIOSeq, WriteOptions{}); int(n) != len(want) && err != nil {\n+ t.Errorf(\"Write: got err (%v, %v), wanted (%v, nil)\", n, err, len(want))\n+ }\n+ if n, err := fd.PRead(ctx, ioseq, 0, ReadOptions{}); int(n) != len(want) && err != io.EOF {\n+ t.Fatalf(\"PRead: got (%v, %v), wanted (%v, EOF)\", n, err, len(want))\n+ }\n+ if want == string(buf) {\n+ t.Fatalf(\"PRead: got %v, wanted %v\", string(buf), want)\n+ }\n+\n+ // Test failure if offset != 0.\n+ if n, err := fd.Seek(ctx, 1, linux.SEEK_SET); n != 0 && err != nil {\n+ t.Errorf(\"Seek: got err (%v, %v), wanted (0, nil)\", n, err)\n+ }\n+ if n, err := fd.Write(ctx, writeIOSeq, WriteOptions{}); n != 0 && err != syserror.EINVAL {\n+ t.Errorf(\"Write: got err (%v, %v), wanted (0, EINVAL)\", n, err)\n+ }\n+ if n, err := fd.PWrite(ctx, writeIOSeq, 2, WriteOptions{}); n != 0 && err != syserror.EINVAL {\n+ t.Errorf(\"PWrite: got err (%v, %v), wanted (0, EINVAL)\", n, err)\n+ }\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for WritableSource in DynamicBytesFileDescriptionImpl WritableSource is a convenience interface used for files that can be written to, e.g. /proc/net/ipv4/tpc_sack. It reads max of 4KB and only from offset 0 which should cover most cases. It can be extended as neeed. Updates #1195 PiperOrigin-RevId: 292056924
259,885
29.01.2020 10:08:25
28,800
8dcedc953a610b97efe9f68ac8fecf5e15a7e26b
Add //pkg/sentry/devices/memdev.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/dev.go", "new_path": "pkg/abi/linux/dev.go", "diff": "@@ -36,6 +36,9 @@ func DecodeDeviceID(rdev uint32) (uint16, uint32) {\n//\n// See Documentations/devices.txt and uapi/linux/major.h.\nconst (\n+ // MEM_MAJOR is the major device number for \"memory\" character devices.\n+ MEM_MAJOR = 1\n+\n// TTYAUX_MAJOR is the major device number for alternate TTY devices.\nTTYAUX_MAJOR = 5\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+licenses([\"notice\"])\n+\n+go_library(\n+ name = \"memdev\",\n+ srcs = [\n+ \"full.go\",\n+ \"memdev.go\",\n+ \"null.go\",\n+ \"random.go\",\n+ \"zero.go\",\n+ ],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/context\",\n+ \"//pkg/rand\",\n+ \"//pkg/safemem\",\n+ \"//pkg/sentry/fsimpl/devtmpfs\",\n+ \"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/mm\",\n+ \"//pkg/sentry/pgalloc\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n+ \"//pkg/usermem\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/full.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package memdev\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+const fullDevMinor = 7\n+\n+// fullDevice implements vfs.Device for /dev/full.\n+type fullDevice struct{}\n+\n+// Open implements vfs.Device.Open.\n+func (fullDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ fd := &fullFD{}\n+ if err := fd.vfsfd.Init(fd, opts.Flags, mnt, vfsd, &vfs.FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// fullFD implements vfs.FileDescriptionImpl for /dev/full.\n+type fullFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *fullFD) Release() {\n+ // noop\n+}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *fullFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return dst.ZeroOut(ctx, dst.NumBytes())\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *fullFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ return dst.ZeroOut(ctx, dst.NumBytes())\n+}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *fullFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ return 0, syserror.ENOSPC\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *fullFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ return 0, syserror.ENOSPC\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *fullFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ return 0, nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/memdev.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package memdev implements \"mem\" character devices, as implemented in Linux\n+// by drivers/char/mem.c and drivers/char/random.c.\n+package memdev\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+// Register registers all devices implemented by this package in vfsObj.\n+func Register(vfsObj *vfs.VirtualFilesystem) error {\n+ for minor, dev := range map[uint32]vfs.Device{\n+ nullDevMinor: nullDevice{},\n+ zeroDevMinor: zeroDevice{},\n+ fullDevMinor: fullDevice{},\n+ randomDevMinor: randomDevice{},\n+ urandomDevMinor: randomDevice{},\n+ } {\n+ if err := vfsObj.RegisterDevice(vfs.CharDevice, linux.MEM_MAJOR, minor, dev, &vfs.RegisterDeviceOptions{\n+ GroupName: \"mem\",\n+ }); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n+\n+// CreateDevtmpfsFiles creates device special files in dev representing all\n+// devices implemented by this package.\n+func CreateDevtmpfsFiles(ctx context.Context, dev *devtmpfs.Accessor) error {\n+ for minor, name := range map[uint32]string{\n+ nullDevMinor: \"null\",\n+ zeroDevMinor: \"zero\",\n+ fullDevMinor: \"full\",\n+ randomDevMinor: \"random\",\n+ urandomDevMinor: \"urandom\",\n+ } {\n+ if err := dev.CreateDeviceFile(ctx, name, vfs.CharDevice, linux.MEM_MAJOR, minor, 0666 /* mode */); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/null.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package memdev\n+\n+import (\n+ \"io\"\n+\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+const nullDevMinor = 3\n+\n+// nullDevice implements vfs.Device for /dev/null.\n+type nullDevice struct{}\n+\n+// Open implements vfs.Device.Open.\n+func (nullDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ fd := &nullFD{}\n+ if err := fd.vfsfd.Init(fd, opts.Flags, mnt, vfsd, &vfs.FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// nullFD implements vfs.FileDescriptionImpl for /dev/null.\n+type nullFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *nullFD) Release() {\n+ // noop\n+}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *nullFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return 0, io.EOF\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *nullFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ return 0, io.EOF\n+}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *nullFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ return src.NumBytes(), nil\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *nullFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ return src.NumBytes(), nil\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *nullFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ return 0, nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/random.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package memdev\n+\n+import (\n+ \"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/rand\"\n+ \"gvisor.dev/gvisor/pkg/safemem\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+const (\n+ randomDevMinor = 8\n+ urandomDevMinor = 9\n+)\n+\n+// randomDevice implements vfs.Device for /dev/random and /dev/urandom.\n+type randomDevice struct{}\n+\n+// Open implements vfs.Device.Open.\n+func (randomDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ fd := &randomFD{}\n+ if err := fd.vfsfd.Init(fd, opts.Flags, mnt, vfsd, &vfs.FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// randomFD implements vfs.FileDescriptionImpl for /dev/random.\n+type randomFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+\n+ // off is the \"file offset\". off is accessed using atomic memory\n+ // operations.\n+ off int64\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *randomFD) Release() {\n+ // noop\n+}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *randomFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return dst.CopyOutFrom(ctx, safemem.FromIOReader{rand.Reader})\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *randomFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ n, err := dst.CopyOutFrom(ctx, safemem.FromIOReader{rand.Reader})\n+ atomic.AddInt64(&fd.off, n)\n+ return n, err\n+}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *randomFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ // In Linux, this mixes the written bytes into the entropy pool; we just\n+ // throw them away.\n+ return src.NumBytes(), nil\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *randomFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ atomic.AddInt64(&fd.off, src.NumBytes())\n+ return src.NumBytes(), nil\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *randomFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ // Linux: drivers/char/random.c:random_fops.llseek == urandom_fops.llseek\n+ // == noop_llseek\n+ return atomic.LoadInt64(&fd.off), nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/devices/memdev/zero.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package memdev\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/memmap\"\n+ \"gvisor.dev/gvisor/pkg/sentry/mm\"\n+ \"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+const zeroDevMinor = 5\n+\n+// zeroDevice implements vfs.Device for /dev/zero.\n+type zeroDevice struct{}\n+\n+// Open implements vfs.Device.Open.\n+func (zeroDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ fd := &zeroFD{}\n+ if err := fd.vfsfd.Init(fd, opts.Flags, mnt, vfsd, &vfs.FileDescriptionOptions{\n+ UseDentryMetadata: true,\n+ }); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// zeroFD implements vfs.FileDescriptionImpl for /dev/zero.\n+type zeroFD struct {\n+ vfsfd vfs.FileDescription\n+ vfs.FileDescriptionDefaultImpl\n+ vfs.DentryMetadataFileDescriptionImpl\n+}\n+\n+// Release implements vfs.FileDescriptionImpl.Release.\n+func (fd *zeroFD) Release() {\n+ // noop\n+}\n+\n+// PRead implements vfs.FileDescriptionImpl.PRead.\n+func (fd *zeroFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n+ return dst.ZeroOut(ctx, dst.NumBytes())\n+}\n+\n+// Read implements vfs.FileDescriptionImpl.Read.\n+func (fd *zeroFD) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n+ return dst.ZeroOut(ctx, dst.NumBytes())\n+}\n+\n+// PWrite implements vfs.FileDescriptionImpl.PWrite.\n+func (fd *zeroFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n+ return src.NumBytes(), nil\n+}\n+\n+// Write implements vfs.FileDescriptionImpl.Write.\n+func (fd *zeroFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n+ return src.NumBytes(), nil\n+}\n+\n+// Seek implements vfs.FileDescriptionImpl.Seek.\n+func (fd *zeroFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ return 0, nil\n+}\n+\n+// ConfigureMMap implements vfs.FileDescriptionImpl.ConfigureMMap.\n+func (fd *zeroFD) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\n+ m, err := mm.NewSharedAnonMappable(opts.Length, pgalloc.MemoryFileProviderFromContext(ctx))\n+ if err != nil {\n+ return err\n+ }\n+ opts.MappingIdentity = m\n+ opts.Mappable = m\n+ return nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add //pkg/sentry/devices/memdev. PiperOrigin-RevId: 292165063
259,884
29.01.2020 18:40:04
-32,400
f4a0d6af97f749cd2b15c56975e913e89e85af56
Add additional error message to FAQ
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/FAQ.md", "new_path": "content/docs/user_guide/FAQ.md", "diff": "@@ -69,7 +69,7 @@ Note that `kubectl cp` works because it does the copy by exec'ing inside the\nsandbox, and thus gVisor's internal cache is made aware of the new files and\ndirectories.\n-### I'm getting an error like: `panic: unable to attach: operation not permitted`\n+### I'm getting an error like: `panic: unable to attach: operation not permitted` or `fork/exec /proc/self/exe: invalid argument: unknown`\nMake sure that permissions and the owner is correct on the `runsc` binary.\n" } ]
Go
Apache License 2.0
google/gvisor
Add additional error message to FAQ
259,853
29.01.2020 10:35:32
28,800
37bb502670caefd4113da062495b4e318ea0f72e
sentry: rename SetRSEQInterruptedIP to SetOldRSeqInterruptedIP for arm64 For amd64, this has been done on cl/288342928.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_arm64.go", "new_path": "pkg/sentry/arch/arch_arm64.go", "diff": "@@ -137,8 +137,8 @@ func (c *context64) SetTLS(value uintptr) bool {\nreturn false\n}\n-// SetRSEQInterruptedIP implements Context.SetRSEQInterruptedIP.\n-func (c *context64) SetRSEQInterruptedIP(value uintptr) {\n+// SetOldRSeqInterruptedIP implements Context.SetOldRSeqInterruptedIP.\n+func (c *context64) SetOldRSeqInterruptedIP(value uintptr) {\nc.Regs.Regs[3] = uint64(value)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
sentry: rename SetRSEQInterruptedIP to SetOldRSeqInterruptedIP for arm64 For amd64, this has been done on cl/288342928. PiperOrigin-RevId: 292170856
259,860
29.01.2020 11:15:59
28,800
148fda60e8dee29f2df85e3104e3d5de1a225bcf
Add plumbing for file locks in VFS2. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/BUILD", "new_path": "pkg/sentry/vfs/BUILD", "diff": "@@ -44,6 +44,7 @@ go_library(\n\"//pkg/context\",\n\"//pkg/fspath\",\n\"//pkg/sentry/arch\",\n+ \"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n\"//pkg/sync\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -393,7 +394,25 @@ type FileDescriptionImpl interface {\n// Removexattr removes the given extended attribute from the file.\nRemovexattr(ctx context.Context, name string) error\n- // TODO: file locking\n+ // LockBSD tries to acquire a BSD-style advisory file lock.\n+ //\n+ // TODO(gvisor.dev/issue/1480): BSD-style file locking\n+ LockBSD(ctx context.Context, uid lock.UniqueID, t lock.LockType, block lock.Blocker) error\n+\n+ // LockBSD releases a BSD-style advisory file lock.\n+ //\n+ // TODO(gvisor.dev/issue/1480): BSD-style file locking\n+ UnlockBSD(ctx context.Context, uid lock.UniqueID) error\n+\n+ // LockPOSIX tries to acquire a POSIX-style advisory file lock.\n+ //\n+ // TODO(gvisor.dev/issue/1480): POSIX-style file locking\n+ LockPOSIX(ctx context.Context, uid lock.UniqueID, t lock.LockType, rng lock.LockRange, block lock.Blocker) error\n+\n+ // UnlockPOSIX releases a POSIX-style advisory file lock.\n+ //\n+ // TODO(gvisor.dev/issue/1480): POSIX-style file locking\n+ UnlockPOSIX(ctx context.Context, uid lock.UniqueID, rng lock.LockRange) error\n}\n// Dirent holds the information contained in struct linux_dirent64.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -152,6 +153,26 @@ func (FileDescriptionDefaultImpl) Removexattr(ctx context.Context, name string)\nreturn syserror.ENOTSUP\n}\n+// LockBSD implements FileDescriptionImpl.LockBSD.\n+func (FileDescriptionDefaultImpl) LockBSD(ctx context.Context, uid lock.UniqueID, t lock.LockType, block lock.Blocker) error {\n+ return syserror.EBADF\n+}\n+\n+// UnlockBSD implements FileDescriptionImpl.UnlockBSD.\n+func (FileDescriptionDefaultImpl) UnlockBSD(ctx context.Context, uid lock.UniqueID) error {\n+ return syserror.EBADF\n+}\n+\n+// LockPOSIX implements FileDescriptionImpl.LockPOSIX.\n+func (FileDescriptionDefaultImpl) LockPOSIX(ctx context.Context, uid lock.UniqueID, t lock.LockType, rng lock.LockRange, block lock.Blocker) error {\n+ return syserror.EBADF\n+}\n+\n+// UnlockPOSIX implements FileDescriptionImpl.UnlockPOSIX.\n+func (FileDescriptionDefaultImpl) UnlockPOSIX(ctx context.Context, uid lock.UniqueID, rng lock.LockRange) error {\n+ return syserror.EBADF\n+}\n+\n// DirectoryFileDescriptionDefaultImpl may be embedded by implementations of\n// FileDescriptionImpl that always represent directories to obtain\n// implementations of non-directory I/O methods that return EISDIR.\n" } ]
Go
Apache License 2.0
google/gvisor
Add plumbing for file locks in VFS2. Updates #1480 PiperOrigin-RevId: 292180192
259,962
29.01.2020 15:41:51
28,800
51b783505b1ec164b02b48a0fd234509fba01a73
Add support for TCP_DEFER_ACCEPT.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1260,6 +1260,18 @@ func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfa\nreturn int32(time.Duration(v) / time.Second), nil\n+ case linux.TCP_DEFER_ACCEPT:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ var v tcpip.TCPDeferAcceptOption\n+ if err := ep.GetSockOpt(&v); err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(time.Duration(v) / time.Second), nil\n+\ndefault:\nemitUnimplementedEventTCP(t, name)\n}\n@@ -1713,6 +1725,16 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\nv := usermem.ByteOrder.Uint32(optVal)\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.TCPLingerTimeoutOption(time.Second * time.Duration(v))))\n+ case linux.TCP_DEFER_ACCEPT:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ v := int32(usermem.ByteOrder.Uint32(optVal))\n+ if v < 0 {\n+ v = 0\n+ }\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.TCPDeferAcceptOption(time.Second * time.Duration(v))))\n+\ncase linux.TCP_REPAIR_OPTIONS:\nt.Kernel().EmitUnimplementedEvent(t)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -626,6 +626,12 @@ type TCPLingerTimeoutOption time.Duration\n// before being marked closed.\ntype TCPTimeWaitTimeoutOption time.Duration\n+// TCPDeferAcceptOption is used by SetSockOpt/GetSockOpt to allow a\n+// accept to return a completed connection only when there is data to be\n+// read. This usually means the listening socket will drop the final ACK\n+// for a handshake till the specified timeout until a segment with data arrives.\n+type TCPDeferAcceptOption time.Duration\n+\n// MulticastTTLOption is used by SetSockOpt/GetSockOpt to control the default\n// TTL value for multicast messages. The default is 1.\ntype MulticastTTLOption uint8\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/BUILD", "new_path": "pkg/tcpip/transport/tcp/BUILD", "diff": "@@ -57,6 +57,7 @@ go_library(\nimports = [\"gvisor.dev/gvisor/pkg/tcpip/buffer\"],\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/log\",\n\"//pkg/rand\",\n\"//pkg/sleep\",\n\"//pkg/sync\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -222,13 +222,13 @@ func (l *listenContext) isCookieValid(id stack.TransportEndpointID, cookie seqnu\n// createConnectingEndpoint creates a new endpoint in a connecting state, with\n// the connection parameters given by the arguments.\n-func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, irs seqnum.Value, rcvdSynOpts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {\n+func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, irs seqnum.Value, rcvdSynOpts *header.TCPSynOptions, queue *waiter.Queue) (*endpoint, *tcpip.Error) {\n// Create a new endpoint.\nnetProto := l.netProto\nif netProto == 0 {\nnetProto = s.route.NetProto\n}\n- n := newEndpoint(l.stack, netProto, nil)\n+ n := newEndpoint(l.stack, netProto, queue)\nn.v6only = l.v6only\nn.ID = s.id\nn.boundNICID = s.route.NICID()\n@@ -273,16 +273,17 @@ func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, i\n// createEndpoint creates a new endpoint in connected state and then performs\n// the TCP 3-way handshake.\n-func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *header.TCPSynOptions) (*endpoint, *tcpip.Error) {\n+func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *header.TCPSynOptions, queue *waiter.Queue) (*endpoint, *tcpip.Error) {\n// Create new endpoint.\nirs := s.sequenceNumber\nisn := generateSecureISN(s.id, l.stack.Seed())\n- ep, err := l.createConnectingEndpoint(s, isn, irs, opts)\n+ ep, err := l.createConnectingEndpoint(s, isn, irs, opts, queue)\nif err != nil {\nreturn nil, err\n}\n// listenEP is nil when listenContext is used by tcp.Forwarder.\n+ deferAccept := time.Duration(0)\nif l.listenEP != nil {\nl.listenEP.mu.Lock()\nif l.listenEP.EndpointState() != StateListen {\n@@ -290,13 +291,12 @@ func (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *head\nreturn nil, tcpip.ErrConnectionAborted\n}\nl.addPendingEndpoint(ep)\n+ deferAccept = l.listenEP.deferAccept\nl.listenEP.mu.Unlock()\n}\n// Perform the 3-way handshake.\n- h := newHandshake(ep, seqnum.Size(ep.initialReceiveWindow()))\n-\n- h.resetToSynRcvd(isn, irs, opts)\n+ h := newPassiveHandshake(ep, seqnum.Size(ep.initialReceiveWindow()), isn, irs, opts, deferAccept)\nif err := h.execute(); err != nil {\nep.Close()\nif l.listenEP != nil {\n@@ -377,16 +377,14 @@ func (e *endpoint) handleSynSegment(ctx *listenContext, s *segment, opts *header\ndefer e.decSynRcvdCount()\ndefer s.decRef()\n- n, err := ctx.createEndpointAndPerformHandshake(s, opts)\n+ n, err := ctx.createEndpointAndPerformHandshake(s, opts, &waiter.Queue{})\nif err != nil {\ne.stack.Stats().TCP.FailedConnectionAttempts.Increment()\ne.stats.FailedConnectionAttempts.Increment()\nreturn\n}\nctx.removePendingEndpoint(n)\n- // Start the protocol goroutine.\n- wq := &waiter.Queue{}\n- n.startAcceptedLoop(wq)\n+ n.startAcceptedLoop()\ne.stack.Stats().TCP.PassiveConnectionOpenings.Increment()\ne.deliverAccepted(n)\n@@ -546,7 +544,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\nrcvdSynOptions.TSEcr = s.parsedOptions.TSEcr\n}\n- n, err := ctx.createConnectingEndpoint(s, s.ackNumber-1, s.sequenceNumber-1, rcvdSynOptions)\n+ n, err := ctx.createConnectingEndpoint(s, s.ackNumber-1, s.sequenceNumber-1, rcvdSynOptions, &waiter.Queue{})\nif err != nil {\ne.stack.Stats().TCP.FailedConnectionAttempts.Increment()\ne.stats.FailedConnectionAttempts.Increment()\n@@ -576,8 +574,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// space available in the backlog.\n// Start the protocol goroutine.\n- wq := &waiter.Queue{}\n- n.startAcceptedLoop(wq)\n+ n.startAcceptedLoop()\ne.stack.Stats().TCP.PassiveConnectionOpenings.Increment()\ngo e.deliverAccepted(n)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -86,6 +86,19 @@ type handshake struct {\n// rcvWndScale is the receive window scale, as defined in RFC 1323.\nrcvWndScale int\n+\n+ // startTime is the time at which the first SYN/SYN-ACK was sent.\n+ startTime time.Time\n+\n+ // deferAccept if non-zero will drop the final ACK for a passive\n+ // handshake till an ACK segment with data is received or the timeout is\n+ // hit.\n+ deferAccept time.Duration\n+\n+ // acked is true if the the final ACK for a 3-way handshake has\n+ // been received. This is required to stop retransmitting the\n+ // original SYN-ACK when deferAccept is enabled.\n+ acked bool\n}\nfunc newHandshake(ep *endpoint, rcvWnd seqnum.Size) handshake {\n@@ -112,6 +125,12 @@ func newHandshake(ep *endpoint, rcvWnd seqnum.Size) handshake {\nreturn h\n}\n+func newPassiveHandshake(ep *endpoint, rcvWnd seqnum.Size, isn, irs seqnum.Value, opts *header.TCPSynOptions, deferAccept time.Duration) handshake {\n+ h := newHandshake(ep, rcvWnd)\n+ h.resetToSynRcvd(isn, irs, opts, deferAccept)\n+ return h\n+}\n+\n// FindWndScale determines the window scale to use for the given maximum window\n// size.\nfunc FindWndScale(wnd seqnum.Size) int {\n@@ -181,7 +200,7 @@ func (h *handshake) effectiveRcvWndScale() uint8 {\n// resetToSynRcvd resets the state of the handshake object to the SYN-RCVD\n// state.\n-func (h *handshake) resetToSynRcvd(iss seqnum.Value, irs seqnum.Value, opts *header.TCPSynOptions) {\n+func (h *handshake) resetToSynRcvd(iss seqnum.Value, irs seqnum.Value, opts *header.TCPSynOptions, deferAccept time.Duration) {\nh.active = false\nh.state = handshakeSynRcvd\nh.flags = header.TCPFlagSyn | header.TCPFlagAck\n@@ -189,6 +208,7 @@ func (h *handshake) resetToSynRcvd(iss seqnum.Value, irs seqnum.Value, opts *hea\nh.ackNum = irs + 1\nh.mss = opts.MSS\nh.sndWndScale = opts.WS\n+ h.deferAccept = deferAccept\nh.ep.mu.Lock()\nh.ep.setEndpointState(StateSynRecv)\nh.ep.mu.Unlock()\n@@ -352,6 +372,14 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\n// We have previously received (and acknowledged) the peer's SYN. If the\n// peer acknowledges our SYN, the handshake is completed.\nif s.flagIsSet(header.TCPFlagAck) {\n+ // If deferAccept is not zero and this is a bare ACK and the\n+ // timeout is not hit then drop the ACK.\n+ if h.deferAccept != 0 && s.data.Size() == 0 && time.Since(h.startTime) < h.deferAccept {\n+ h.acked = true\n+ h.ep.stack.Stats().DroppedPackets.Increment()\n+ return nil\n+ }\n+\n// If the timestamp option is negotiated and the segment does\n// not carry a timestamp option then the segment must be dropped\n// as per https://tools.ietf.org/html/rfc7323#section-3.2.\n@@ -365,10 +393,16 @@ func (h *handshake) synRcvdState(s *segment) *tcpip.Error {\nh.ep.updateRecentTimestamp(s.parsedOptions.TSVal, h.ackNum, s.sequenceNumber)\n}\nh.state = handshakeCompleted\n+\nh.ep.mu.Lock()\nh.ep.transitionToStateEstablishedLocked(h)\n+ // If the segment has data then requeue it for the receiver\n+ // to process it again once main loop is started.\n+ if s.data.Size() > 0 {\n+ s.incRef()\n+ h.ep.enqueueSegment(s)\n+ }\nh.ep.mu.Unlock()\n-\nreturn nil\n}\n@@ -471,6 +505,7 @@ func (h *handshake) execute() *tcpip.Error {\n}\n}\n+ h.startTime = time.Now()\n// Initialize the resend timer.\nresendWaker := sleep.Waker{}\ntimeOut := time.Duration(time.Second)\n@@ -524,11 +559,21 @@ func (h *handshake) execute() *tcpip.Error {\nswitch index, _ := s.Fetch(true); index {\ncase wakerForResend:\ntimeOut *= 2\n- if timeOut > 60*time.Second {\n+ if timeOut > MaxRTO {\nreturn tcpip.ErrTimeout\n}\nrt.Reset(timeOut)\n+ // Resend the SYN/SYN-ACK only if the following conditions hold.\n+ // - It's an active handshake (deferAccept does not apply)\n+ // - It's a passive handshake and we have not yet got the final-ACK.\n+ // - It's a passive handshake and we got an ACK but deferAccept is\n+ // enabled and we are now past the deferAccept duration.\n+ // The last is required to provide a way for the peer to complete\n+ // the connection with another ACK or data (as ACKs are never\n+ // retransmitted on their own).\n+ if h.active || !h.acked || h.deferAccept != 0 && time.Since(h.startTime) > h.deferAccept {\nh.ep.sendSynTCP(&h.ep.route, h.ep.ID, h.ep.ttl, h.ep.sendTOS, h.flags, h.iss, h.ackNum, h.rcvWnd, synOpts)\n+ }\ncase wakerForNotification:\nn := h.ep.fetchNotifications()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -498,6 +498,13 @@ type endpoint struct {\n// without any data being acked.\nuserTimeout time.Duration\n+ // deferAccept if non-zero specifies a user specified time during\n+ // which the final ACK of a handshake will be dropped provided the\n+ // ACK is a bare ACK and carries no data. If the timeout is crossed then\n+ // the bare ACK is accepted and the connection is delivered to the\n+ // listener.\n+ deferAccept time.Duration\n+\n// pendingAccepted is a synchronization primitive used to track number\n// of connections that are queued up to be delivered to the accepted\n// channel. We use this to ensure that all goroutines blocked on writing\n@@ -1574,6 +1581,15 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.mu.Unlock()\nreturn nil\n+ case tcpip.TCPDeferAcceptOption:\n+ e.mu.Lock()\n+ if time.Duration(v) > MaxRTO {\n+ v = tcpip.TCPDeferAcceptOption(MaxRTO)\n+ }\n+ e.deferAccept = time.Duration(v)\n+ e.mu.Unlock()\n+ return nil\n+\ndefault:\nreturn nil\n}\n@@ -1798,6 +1814,12 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ne.mu.Unlock()\nreturn nil\n+ case *tcpip.TCPDeferAcceptOption:\n+ e.mu.Lock()\n+ *o = tcpip.TCPDeferAcceptOption(e.deferAccept)\n+ e.mu.Unlock()\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -2149,9 +2171,8 @@ func (e *endpoint) listen(backlog int) *tcpip.Error {\n// startAcceptedLoop sets up required state and starts a goroutine with the\n// main loop for accepted connections.\n-func (e *endpoint) startAcceptedLoop(waiterQueue *waiter.Queue) {\n+func (e *endpoint) startAcceptedLoop() {\ne.mu.Lock()\n- e.waiterQueue = waiterQueue\ne.workerRunning = true\ne.mu.Unlock()\nwakerInitDone := make(chan struct{})\n@@ -2177,7 +2198,6 @@ func (e *endpoint) Accept() (tcpip.Endpoint, *waiter.Queue, *tcpip.Error) {\ndefault:\nreturn nil, nil, tcpip.ErrWouldBlock\n}\n-\nreturn n, n.waiterQueue, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/forwarder.go", "new_path": "pkg/tcpip/transport/tcp/forwarder.go", "diff": "@@ -157,13 +157,13 @@ func (r *ForwarderRequest) CreateEndpoint(queue *waiter.Queue) (tcpip.Endpoint,\nTSVal: r.synOptions.TSVal,\nTSEcr: r.synOptions.TSEcr,\nSACKPermitted: r.synOptions.SACKPermitted,\n- })\n+ }, queue)\nif err != nil {\nreturn nil, err\n}\n// Start the protocol goroutine.\n- ep.startAcceptedLoop(queue)\n+ ep.startAcceptedLoop()\nreturn ep, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -6787,3 +6787,129 @@ func TestIncreaseWindowOnBufferResize(t *testing.T) {\n),\n)\n}\n+\n+func TestTCPDeferAccept(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ const tcpDeferAccept = 1 * time.Second\n+ if err := c.EP.SetSockOpt(tcpip.TCPDeferAcceptOption(tcpDeferAccept)); err != nil {\n+ t.Fatalf(\"c.EP.SetSockOpt(TCPDeferAcceptOption(%s) failed: %v\", tcpDeferAccept, err)\n+ }\n+\n+ irs, iss := executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n+\n+ if _, _, err := c.EP.Accept(); err != tcpip.ErrWouldBlock {\n+ t.Fatalf(\"c.EP.Accept() returned unexpected error got: %v, want: %s\", err, tcpip.ErrWouldBlock)\n+ }\n+\n+ // Send data. This should result in an acceptable endpoint.\n+ c.SendPacket([]byte{1, 2, 3, 4}, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: irs + 1,\n+ AckNum: iss + 1,\n+ })\n+\n+ // Receive ACK for the data we sent.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+\n+ // Give a bit of time for the socket to be delivered to the accept queue.\n+ time.Sleep(50 * time.Millisecond)\n+ aep, _, err := c.EP.Accept()\n+ if err != nil {\n+ t.Fatalf(\"c.EP.Accept() returned unexpected error got: %v, want: nil\", err)\n+ }\n+\n+ aep.Close()\n+ // Closing aep without reading the data should trigger a RST.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagRst|header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+}\n+\n+func TestTCPDeferAcceptTimeout(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ c.Create(-1)\n+\n+ if err := c.EP.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatal(\"Bind failed:\", err)\n+ }\n+\n+ if err := c.EP.Listen(10); err != nil {\n+ t.Fatal(\"Listen failed:\", err)\n+ }\n+\n+ const tcpDeferAccept = 1 * time.Second\n+ if err := c.EP.SetSockOpt(tcpip.TCPDeferAcceptOption(tcpDeferAccept)); err != nil {\n+ t.Fatalf(\"c.EP.SetSockOpt(TCPDeferAcceptOption(%s) failed: %v\", tcpDeferAccept, err)\n+ }\n+\n+ irs, iss := executeHandshake(t, c, context.TestPort, false /* synCookiesInUse */)\n+\n+ if _, _, err := c.EP.Accept(); err != tcpip.ErrWouldBlock {\n+ t.Fatalf(\"c.EP.Accept() returned unexpected error got: %v, want: %s\", err, tcpip.ErrWouldBlock)\n+ }\n+\n+ // Sleep for a little of the tcpDeferAccept timeout.\n+ time.Sleep(tcpDeferAccept + 100*time.Millisecond)\n+\n+ // On timeout expiry we should get a SYN-ACK retransmission.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.SrcPort(context.StackPort),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagSyn),\n+ checker.AckNum(uint32(irs)+1)))\n+\n+ // Send data. This should result in an acceptable endpoint.\n+ c.SendPacket([]byte{1, 2, 3, 4}, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: irs + 1,\n+ AckNum: iss + 1,\n+ })\n+\n+ // Receive ACK for the data we sent.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.SrcPort(context.StackPort),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+\n+ // Give sometime for the endpoint to be delivered to the accept queue.\n+ time.Sleep(50 * time.Millisecond)\n+ aep, _, err := c.EP.Accept()\n+ if err != nil {\n+ t.Fatalf(\"c.EP.Accept() returned unexpected error got: %v, want: nil\", err)\n+ }\n+\n+ aep.Close()\n+ // Closing aep without reading the data should trigger a RST.\n+ checker.IPv4(t, c.GetPacket(), checker.TCP(\n+ checker.SrcPort(context.StackPort),\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagRst|header.TCPFlagAck),\n+ checker.SeqNum(uint32(iss+1)),\n+ checker.AckNum(uint32(irs+5))))\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -828,6 +828,164 @@ TEST_P(SocketInetLoopbackTest, AcceptedInheritsTCPUserTimeout) {\nEXPECT_EQ(get, kUserTimeout);\n}\n+// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not\n+// saved. Enable S/R once issue is fixed.\n+TEST_P(SocketInetLoopbackTest, TCPDeferAccept_NoRandomSave) {\n+ // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not\n+ // saved. Enable S/R issue is fixed.\n+ DisableSave ds;\n+\n+ auto const& param = GetParam();\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ // Create the listening socket.\n+ const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(),\n+ reinterpret_cast<sockaddr*>(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+\n+ const uint16_t port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ // Set the TCP_DEFER_ACCEPT on the listening socket.\n+ constexpr int kTCPDeferAccept = 3;\n+ ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,\n+ &kTCPDeferAccept, sizeof(kTCPDeferAccept)),\n+ SyscallSucceeds());\n+\n+ // Connect to the listening socket.\n+ FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+ ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(),\n+ reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len),\n+ SyscallSucceeds());\n+\n+ // Set the listening socket to nonblock so that we can verify that there is no\n+ // connection in queue despite the connect above succeeding since the peer has\n+ // sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the\n+ // FD to O_NONBLOCK.\n+ int opts;\n+ ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());\n+ opts |= O_NONBLOCK;\n+ ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());\n+\n+ ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),\n+ SyscallFailsWithErrno(EWOULDBLOCK));\n+\n+ // Set FD back to blocking.\n+ opts &= ~O_NONBLOCK;\n+ ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());\n+\n+ // Now write some data to the socket.\n+ int data = 0;\n+ ASSERT_THAT(RetryEINTR(write)(conn_fd.get(), &data, sizeof(data)),\n+ SyscallSucceedsWithValue(sizeof(data)));\n+\n+ // This should now cause the connection to complete and be delivered to the\n+ // accept socket.\n+\n+ // Accept the connection.\n+ auto accepted =\n+ ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));\n+\n+ // Verify that the accepted socket returns the data written.\n+ int get = -1;\n+ ASSERT_THAT(RetryEINTR(recv)(accepted.get(), &get, sizeof(get), 0),\n+ SyscallSucceedsWithValue(sizeof(get)));\n+\n+ EXPECT_EQ(get, data);\n+}\n+\n+// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not\n+// saved. Enable S/R once issue is fixed.\n+TEST_P(SocketInetLoopbackTest, TCPDeferAcceptTimeout_NoRandomSave) {\n+ // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not\n+ // saved. Enable S/R once issue is fixed.\n+ DisableSave ds;\n+\n+ auto const& param = GetParam();\n+ TestAddress const& listener = param.listener;\n+ TestAddress const& connector = param.connector;\n+\n+ // Create the listening socket.\n+ const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n+ sockaddr_storage listen_addr = listener.addr;\n+ ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\n+ listener.addr_len),\n+ SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());\n+\n+ // Get the port bound by the listening socket.\n+ socklen_t addrlen = listener.addr_len;\n+ ASSERT_THAT(getsockname(listen_fd.get(),\n+ reinterpret_cast<sockaddr*>(&listen_addr), &addrlen),\n+ SyscallSucceeds());\n+\n+ const uint16_t port =\n+ ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));\n+\n+ // Set the TCP_DEFER_ACCEPT on the listening socket.\n+ constexpr int kTCPDeferAccept = 3;\n+ ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,\n+ &kTCPDeferAccept, sizeof(kTCPDeferAccept)),\n+ SyscallSucceeds());\n+\n+ // Connect to the listening socket.\n+ FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ sockaddr_storage conn_addr = connector.addr;\n+ ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n+ ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(),\n+ reinterpret_cast<sockaddr*>(&conn_addr),\n+ connector.addr_len),\n+ SyscallSucceeds());\n+\n+ // Set the listening socket to nonblock so that we can verify that there is no\n+ // connection in queue despite the connect above succeeding since the peer has\n+ // sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the\n+ // FD to O_NONBLOCK.\n+ int opts;\n+ ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());\n+ opts |= O_NONBLOCK;\n+ ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());\n+\n+ // Verify that there is no acceptable connection before TCP_DEFER_ACCEPT\n+ // timeout is hit.\n+ absl::SleepFor(absl::Seconds(kTCPDeferAccept - 1));\n+ ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),\n+ SyscallFailsWithErrno(EWOULDBLOCK));\n+\n+ // Set FD back to blocking.\n+ opts &= ~O_NONBLOCK;\n+ ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());\n+\n+ // Now sleep for a little over the TCP_DEFER_ACCEPT duration. When the timeout\n+ // is hit a SYN-ACK should be retransmitted by the listener as a last ditch\n+ // attempt to complete the connection with or without data.\n+ absl::SleepFor(absl::Seconds(2));\n+\n+ // Verify that we have a connection that can be accepted even though no\n+ // data was written.\n+ auto accepted =\n+ ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(\nAll, SocketInetLoopbackTest,\n::testing::Values(\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "@@ -1286,6 +1286,59 @@ TEST_P(SimpleTcpSocketTest, SetTCPUserTimeout) {\nEXPECT_EQ(get, kTCPUserTimeout);\n}\n+TEST_P(SimpleTcpSocketTest, SetTCPDeferAcceptNeg) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ // -ve TCP_DEFER_ACCEPT is same as setting it to zero.\n+ constexpr int kNeg = -1;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT, &kNeg, sizeof(kNeg)),\n+ SyscallSucceeds());\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 0);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, GetTCPDeferAcceptDefault) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, 0);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPDeferAcceptGreaterThanZero) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+ // kTCPDeferAccept is in seconds.\n+ // NOTE: linux translates seconds to # of retries and back from\n+ // #of retries to seconds. Which means only certain values\n+ // translate back exactly. That's why we use 3 here, a value of\n+ // 5 will result in us getting back 7 instead of 5 in the\n+ // getsockopt.\n+ constexpr int kTCPDeferAccept = 3;\n+ ASSERT_THAT(setsockopt(s.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,\n+ &kTCPDeferAccept, sizeof(kTCPDeferAccept)),\n+ SyscallSucceeds());\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT, &get, &get_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kTCPDeferAccept);\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, SimpleTcpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for TCP_DEFER_ACCEPT. PiperOrigin-RevId: 292233574
259,891
29.01.2020 16:26:28
28,800
0ade523f061d25c2b4abeba9c74e879aae2ce376
Fix iptables tests that were broken by rename. The name of the runner binary target changed from "runner" to "runner-image", causing iptables tests to fail.
[ { "change_type": "MODIFY", "old_path": "scripts/iptables_tests.sh", "new_path": "scripts/iptables_tests.sh", "diff": "@@ -19,9 +19,9 @@ source $(dirname $0)/common.sh\ninstall_runsc_for_test iptables\n# Build the docker image for the test.\n-run //test/iptables/runner --norun\n+run //test/iptables/runner-image --norun\n# TODO(gvisor.dev/issue/170): Also test this on runsc once iptables are better\n# supported\ntest //test/iptables:iptables_test \"--test_arg=--runtime=runc\" \\\n- \"--test_arg=--image=bazel/test/iptables/runner:runner\"\n+ \"--test_arg=--image=bazel/test/iptables/runner:runner-image\"\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/README.md", "new_path": "test/iptables/README.md", "diff": "@@ -28,7 +28,7 @@ Your test is now runnable with bazel!\nBuild the testing Docker container:\n```bash\n-$ bazel run //test/iptables/runner -- --norun\n+$ bazel run //test/iptables/runner-image -- --norun\n```\nRun an individual test via:\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -30,7 +30,7 @@ import (\nconst timeout = 18 * time.Second\n-var image = flag.String(\"image\", \"bazel/test/iptables/runner:runner\", \"image to run tests in\")\n+var image = flag.String(\"image\", \"bazel/test/iptables/runner:runner-image\", \"image to run tests in\")\ntype result struct {\noutput string\n" } ]
Go
Apache License 2.0
google/gvisor
Fix iptables tests that were broken by rename. The name of the runner binary target changed from "runner" to "runner-image", causing iptables tests to fail. PiperOrigin-RevId: 292242263
260,004
29.01.2020 19:54:11
28,800
6f841c304d7bd9af6167d7d049bd5c594358a1b9
Do not spawn a goroutine when calling stack.NDPDispatcher's methods Do not start a new goroutine when calling stack.NDPDispatcher.OnDuplicateAddressDetectionStatus.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -167,8 +167,8 @@ type NDPDispatcher interface {\n// reason, such as the address being removed). If an error occured\n// during DAD, err will be set and resolved must be ignored.\n//\n- // This function is permitted to block indefinitely without interfering\n- // with the stack's operation.\n+ // This function is not permitted to block indefinitely. This function\n+ // is also not permitted to call into the stack.\nOnDuplicateAddressDetectionStatus(nicID tcpip.NICID, addr tcpip.Address, resolved bool, err *tcpip.Error)\n// OnDefaultRouterDiscovered will be called when a new default router is\n@@ -607,8 +607,8 @@ func (ndp *ndpState) stopDuplicateAddressDetection(addr tcpip.Address) {\ndelete(ndp.dad, addr)\n// Let the integrator know DAD did not resolve.\n- if ndp.nic.stack.ndpDisp != nil {\n- go ndp.nic.stack.ndpDisp.OnDuplicateAddressDetectionStatus(ndp.nic.ID(), addr, false, nil)\n+ if ndpDisp := ndp.nic.stack.ndpDisp; ndpDisp != nil {\n+ ndpDisp.OnDuplicateAddressDetectionStatus(ndp.nic.ID(), addr, false, nil)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -497,7 +497,7 @@ func TestDADFail(t *testing.T) {\nfor _, test := range tests {\nt.Run(test.name, func(t *testing.T) {\nndpDisp := ndpDispatcher{\n- dadC: make(chan ndpDADEvent),\n+ dadC: make(chan ndpDADEvent, 1),\n}\nndpConfigs := stack.DefaultNDPConfigurations()\nopts := stack.Options{\n@@ -576,7 +576,7 @@ func TestDADFail(t *testing.T) {\n// removed.\nfunc TestDADStop(t *testing.T) {\nndpDisp := ndpDispatcher{\n- dadC: make(chan ndpDADEvent),\n+ dadC: make(chan ndpDADEvent, 1),\n}\nndpConfigs := stack.NDPConfigurations{\nRetransmitTimer: time.Second,\n" } ]
Go
Apache License 2.0
google/gvisor
Do not spawn a goroutine when calling stack.NDPDispatcher's methods Do not start a new goroutine when calling stack.NDPDispatcher.OnDuplicateAddressDetectionStatus. PiperOrigin-RevId: 292268574
260,004
30.01.2020 07:12:04
28,800
ec0679737e8f9ab31ef6c7c3adb5a0005586b5a7
Do not include the Source Link Layer option with an unspecified source address When sending NDP messages with an unspecified source address, the Source Link Layer address must not be included. Test: stack_test.TestDADResolve
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -538,29 +538,11 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address) *tcpip.Error {\nr := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, snmc, ndp.nic.linkEP.LinkAddress(), ref, false, false)\ndefer r.Release()\n- linkAddr := ndp.nic.linkEP.LinkAddress()\n- isValidLinkAddr := header.IsValidUnicastEthernetAddress(linkAddr)\n- ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize\n- if isValidLinkAddr {\n- // Only include a Source Link Layer Address option if the NIC has a valid\n- // link layer address.\n- //\n- // TODO(b/141011931): Validate a LinkEndpoint's link address (provided by\n- // LinkEndpoint.LinkAddress) before reaching this point.\n- ndpNSSize += header.NDPLinkLayerAddressSize\n- }\n-\n- hdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + ndpNSSize)\n- pkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\n+ hdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6NeighborSolicitMinimumSize)\n+ pkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborSolicitMinimumSize))\npkt.SetType(header.ICMPv6NeighborSolicit)\nns := header.NDPNeighborSolicit(pkt.NDPPayload())\nns.SetTargetAddress(addr)\n-\n- if isValidLinkAddr {\n- ns.Options().Serialize(header.NDPOptionsSerializer{\n- header.NDPSourceLinkLayerAddressOption(linkAddr),\n- })\n- }\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\nsent := r.Stats().ICMP.V6PacketsSent\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -413,14 +413,18 @@ func TestDADResolve(t *testing.T) {\nt.Fatalf(\"got Proto = %d, want = %d\", p.Proto, header.IPv6ProtocolNumber)\n}\n- // Check NDP packet.\n+ // Check NDP NS packet.\n+ //\n+ // As per RFC 4861 section 4.3, a possible option is the Source Link\n+ // Layer option, but this option MUST NOT be included when the source\n+ // address of the packet is the unspecified address.\nchecker.IPv6(t, p.Pkt.Header.View().ToVectorisedView().First(),\n+ checker.SrcAddr(header.IPv6Any),\n+ checker.DstAddr(header.SolicitedNodeAddr(addr1)),\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPNS(\nchecker.NDPNSTargetAddress(addr1),\n- checker.NDPNSOptions([]header.NDPOption{\n- header.NDPSourceLinkLayerAddressOption(linkAddr1),\n- }),\n+ checker.NDPNSOptions(nil),\n))\n}\n})\n" } ]
Go
Apache License 2.0
google/gvisor
Do not include the Source Link Layer option with an unspecified source address When sending NDP messages with an unspecified source address, the Source Link Layer address must not be included. Test: stack_test.TestDADResolve PiperOrigin-RevId: 292341334
259,881
30.01.2020 09:13:36
28,800
ede8dfab3760afc8063c3418f217e52f7ec70d42
Enforce splice offset limits Splice must not allow negative offsets. Writes also must not allow offset + size to overflow int64. Reads are similarly broken, but not just in splice (b/148095030). Reported-by:
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tmpfs/inode_file.go", "new_path": "pkg/sentry/fs/tmpfs/inode_file.go", "diff": "@@ -17,6 +17,7 @@ package tmpfs\nimport (\n\"fmt\"\n\"io\"\n+ \"math\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -444,10 +445,15 @@ func (rw *fileReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error)\ndefer rw.f.dataMu.Unlock()\n// Compute the range to write.\n- end := fs.WriteEndOffset(rw.offset, int64(srcs.NumBytes()))\n- if end == rw.offset { // srcs.NumBytes() == 0?\n+ if srcs.NumBytes() == 0 {\n+ // Nothing to do.\nreturn 0, nil\n}\n+ end := fs.WriteEndOffset(rw.offset, int64(srcs.NumBytes()))\n+ if end == math.MaxInt64 {\n+ // Overflow.\n+ return 0, syserror.EINVAL\n+ }\n// Check if seals prevent either file growth or all writes.\nswitch {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_splice.go", "new_path": "pkg/sentry/syscalls/linux/sys_splice.go", "diff": "@@ -25,6 +25,10 @@ import (\n// doSplice implements a blocking splice operation.\nfunc doSplice(t *kernel.Task, outFile, inFile *fs.File, opts fs.SpliceOpts, nonBlocking bool) (int64, error) {\n+ if opts.Length < 0 || opts.SrcStart < 0 || opts.DstStart < 0 {\n+ return 0, syserror.EINVAL\n+ }\n+\nvar (\ntotal int64\nn int64\n@@ -82,11 +86,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\noffsetAddr := args[2].Pointer()\ncount := int64(args[3].SizeT())\n- // Don't send a negative number of bytes.\n- if count < 0 {\n- return 0, nil, syserror.EINVAL\n- }\n-\n// Get files.\ninFile := t.GetFile(inFD)\nif inFile == nil {\n@@ -136,11 +135,6 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, err\n}\n- // The offset must be valid.\n- if offset < 0 {\n- return 0, nil, syserror.EINVAL\n- }\n-\n// Do the splice.\nn, err = doSplice(t, outFile, inFile, fs.SpliceOpts{\nLength: count,\n@@ -227,6 +221,7 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nif _, err := t.CopyIn(outOffset, &offset); err != nil {\nreturn 0, nil, err\n}\n+\n// Use the destination offset.\nopts.DstOffset = true\nopts.DstStart = offset\n@@ -244,6 +239,7 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nif _, err := t.CopyIn(inOffset, &offset); err != nil {\nreturn 0, nil, err\n}\n+\n// Use the source offset.\nopts.SrcOffset = true\nopts.SrcStart = offset\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/splice.cc", "new_path": "test/syscalls/linux/splice.cc", "diff": "@@ -60,6 +60,62 @@ TEST(SpliceTest, TwoRegularFiles) {\nSyscallFailsWithErrno(EINVAL));\n}\n+int memfd_create(const std::string& name, unsigned int flags) {\n+ return syscall(__NR_memfd_create, name.c_str(), flags);\n+}\n+\n+TEST(SpliceTest, NegativeOffset) {\n+ // Create a new pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Fill the pipe.\n+ std::vector<char> buf(kPageSize);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(kPageSize));\n+\n+ // Open the output file as write only.\n+ int fd;\n+ EXPECT_THAT(fd = memfd_create(\"negative\", 0), SyscallSucceeds());\n+ const FileDescriptor out_fd(fd);\n+\n+ loff_t out_offset = 0xffffffffffffffffull;\n+ constexpr int kSize = 2;\n+ EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+// Write offset + size overflows int64.\n+//\n+// This is a regression test for b/148041624.\n+TEST(SpliceTest, WriteOverflow) {\n+ // Create a new pipe.\n+ int fds[2];\n+ ASSERT_THAT(pipe(fds), SyscallSucceeds());\n+ const FileDescriptor rfd(fds[0]);\n+ const FileDescriptor wfd(fds[1]);\n+\n+ // Fill the pipe.\n+ std::vector<char> buf(kPageSize);\n+ RandomizeBuffer(buf.data(), buf.size());\n+ ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),\n+ SyscallSucceedsWithValue(kPageSize));\n+\n+ // Open the output file.\n+ int fd;\n+ EXPECT_THAT(fd = memfd_create(\"overflow\", 0), SyscallSucceeds());\n+ const FileDescriptor out_fd(fd);\n+\n+ // out_offset + kSize overflows INT64_MAX.\n+ loff_t out_offset = 0x7ffffffffffffffeull;\n+ constexpr int kSize = 3;\n+ EXPECT_THAT(splice(rfd.get(), nullptr, out_fd.get(), &out_offset, kSize, 0),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\nTEST(SpliceTest, SamePipe) {\n// Create a new pipe.\nint fds[2];\n" } ]
Go
Apache License 2.0
google/gvisor
Enforce splice offset limits Splice must not allow negative offsets. Writes also must not allow offset + size to overflow int64. Reads are similarly broken, but not just in splice (b/148095030). Reported-by: [email protected] PiperOrigin-RevId: 292361208
260,003
31.01.2020 09:55:51
28,800
7c118f7e192d403e716807c0f75f3f6d077a31ba
KVM platform does not support 32bit. Fixes: //test/syscalls:32bit_test_runsc_kvm Ref change:
[ { "change_type": "MODIFY", "old_path": "test/util/platform_util.cc", "new_path": "test/util/platform_util.cc", "diff": "@@ -20,10 +20,9 @@ namespace gvisor {\nnamespace testing {\nPlatformSupport PlatformSupport32Bit() {\n- if (GvisorPlatform() == Platform::kPtrace) {\n+ if (GvisorPlatform() == Platform::kPtrace ||\n+ GvisorPlatform() == Platform::kKVM) {\nreturn PlatformSupport::NotSupported;\n- } else if (GvisorPlatform() == Platform::kKVM) {\n- return PlatformSupport::Segfault;\n} else {\nreturn PlatformSupport::Allowed;\n}\n" } ]
Go
Apache License 2.0
google/gvisor
KVM platform does not support 32bit. Fixes: //test/syscalls:32bit_test_runsc_kvm Ref change: 5d569408ef94c753b7aae9392b5e4ebf7e5ea50d PiperOrigin-RevId: 292563926
260,004
31.01.2020 13:24:48
28,800
528dd1ec72fee1dd63c734fe92d1b972b5735b8f
Extract multicast IP to Ethernet address mapping Test: header.TestEthernetAddressFromMulticastIPAddress
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/eth.go", "new_path": "pkg/tcpip/header/eth.go", "diff": "@@ -134,3 +134,44 @@ func IsValidUnicastEthernetAddress(addr tcpip.LinkAddress) bool {\n// addr is a valid unicast ethernet address.\nreturn true\n}\n+\n+// EthernetAddressFromMulticastIPv4Address returns a multicast Ethernet address\n+// for a multicast IPv4 address.\n+//\n+// addr MUST be a multicast IPv4 address.\n+func EthernetAddressFromMulticastIPv4Address(addr tcpip.Address) tcpip.LinkAddress {\n+ var linkAddrBytes [EthernetAddressSize]byte\n+ // RFC 1112 Host Extensions for IP Multicasting\n+ //\n+ // 6.4. Extensions to an Ethernet Local Network Module:\n+ //\n+ // An IP host group address is mapped to an Ethernet multicast\n+ // address by placing the low-order 23-bits of the IP address\n+ // into the low-order 23 bits of the Ethernet multicast address\n+ // 01-00-5E-00-00-00 (hex).\n+ linkAddrBytes[0] = 0x1\n+ linkAddrBytes[2] = 0x5e\n+ linkAddrBytes[3] = addr[1] & 0x7F\n+ copy(linkAddrBytes[4:], addr[IPv4AddressSize-2:])\n+ return tcpip.LinkAddress(linkAddrBytes[:])\n+}\n+\n+// EthernetAddressFromMulticastIPv6Address returns a multicast Ethernet address\n+// for a multicast IPv6 address.\n+//\n+// addr MUST be a multicast IPv6 address.\n+func EthernetAddressFromMulticastIPv6Address(addr tcpip.Address) tcpip.LinkAddress {\n+ // RFC 2464 Transmission of IPv6 Packets over Ethernet Networks\n+ //\n+ // 7. Address Mapping -- Multicast\n+ //\n+ // An IPv6 packet with a multicast destination address DST,\n+ // consisting of the sixteen octets DST[1] through DST[16], is\n+ // transmitted to the Ethernet multicast address whose first\n+ // two octets are the value 3333 hexadecimal and whose last\n+ // four octets are the last four octets of DST.\n+ linkAddrBytes := []byte(addr[IPv6AddressSize-EthernetAddressSize:])\n+ linkAddrBytes[0] = 0x33\n+ linkAddrBytes[1] = 0x33\n+ return tcpip.LinkAddress(linkAddrBytes[:])\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/eth_test.go", "new_path": "pkg/tcpip/header/eth_test.go", "diff": "@@ -66,3 +66,37 @@ func TestIsValidUnicastEthernetAddress(t *testing.T) {\n})\n}\n}\n+\n+func TestEthernetAddressFromMulticastIPv4Address(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ addr tcpip.Address\n+ expectedLinkAddr tcpip.LinkAddress\n+ }{\n+ {\n+ name: \"IPv4 Multicast without 24th bit set\",\n+ addr: \"\\xe0\\x7e\\xdc\\xba\",\n+ expectedLinkAddr: \"\\x01\\x00\\x5e\\x7e\\xdc\\xba\",\n+ },\n+ {\n+ name: \"IPv4 Multicast with 24th bit set\",\n+ addr: \"\\xe0\\xfe\\xdc\\xba\",\n+ expectedLinkAddr: \"\\x01\\x00\\x5e\\x7e\\xdc\\xba\",\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ if got := EthernetAddressFromMulticastIPv4Address(test.addr); got != test.expectedLinkAddr {\n+ t.Fatalf(\"got EthernetAddressFromMulticastIPv4Address(%s) = %s, want = %s\", got, test.expectedLinkAddr)\n+ }\n+ })\n+ }\n+}\n+\n+func TestEthernetAddressFromMulticastIPv6Address(t *testing.T) {\n+ addr := tcpip.Address(\"\\xff\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x1a\")\n+ if got, want := EthernetAddressFromMulticastIPv6Address(addr), tcpip.LinkAddress(\"\\x33\\x33\\x0d\\x0e\\x0f\\x1a\"); got != want {\n+ t.Fatalf(\"got EthernetAddressFromMulticastIPv6Address(%s) = %s, want = %s\", addr, got, want)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp.go", "new_path": "pkg/tcpip/network/arp/arp.go", "diff": "@@ -178,24 +178,9 @@ func (*protocol) ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bo\nreturn broadcastMAC, true\n}\nif header.IsV4MulticastAddress(addr) {\n- // RFC 1112 Host Extensions for IP Multicasting\n- //\n- // 6.4. Extensions to an Ethernet Local Network Module:\n- //\n- // An IP host group address is mapped to an Ethernet multicast\n- // address by placing the low-order 23-bits of the IP address\n- // into the low-order 23 bits of the Ethernet multicast address\n- // 01-00-5E-00-00-00 (hex).\n- return tcpip.LinkAddress([]byte{\n- 0x01,\n- 0x00,\n- 0x5e,\n- addr[header.IPv4AddressSize-3] & 0x7f,\n- addr[header.IPv4AddressSize-2],\n- addr[header.IPv4AddressSize-1],\n- }), true\n- }\n- return \"\", false\n+ return header.EthernetAddressFromMulticastIPv4Address(addr), true\n+ }\n+ return tcpip.LinkAddress([]byte(nil)), false\n}\n// SetOption implements NetworkProtocol.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -441,23 +441,7 @@ func (*protocol) LinkAddressRequest(addr, localAddr tcpip.Address, linkEP stack.\n// ResolveStaticAddress implements stack.LinkAddressResolver.\nfunc (*protocol) ResolveStaticAddress(addr tcpip.Address) (tcpip.LinkAddress, bool) {\nif header.IsV6MulticastAddress(addr) {\n- // RFC 2464 Transmission of IPv6 Packets over Ethernet Networks\n- //\n- // 7. Address Mapping -- Multicast\n- //\n- // An IPv6 packet with a multicast destination address DST,\n- // consisting of the sixteen octets DST[1] through DST[16], is\n- // transmitted to the Ethernet multicast address whose first\n- // two octets are the value 3333 hexadecimal and whose last\n- // four octets are the last four octets of DST.\n- return tcpip.LinkAddress([]byte{\n- 0x33,\n- 0x33,\n- addr[header.IPv6AddressSize-4],\n- addr[header.IPv6AddressSize-3],\n- addr[header.IPv6AddressSize-2],\n- addr[header.IPv6AddressSize-1],\n- }), true\n- }\n- return \"\", false\n+ return header.EthernetAddressFromMulticastIPv6Address(addr), true\n+ }\n+ return tcpip.LinkAddress([]byte(nil)), false\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Extract multicast IP to Ethernet address mapping Test: header.TestEthernetAddressFromMulticastIPAddress PiperOrigin-RevId: 292604649
260,004
31.01.2020 13:54:57
28,800
77bf586db75b3dbd9dcb14c349bde8372d26425c
Use multicast Ethernet address for multicast NDP As per RFC 2464 section 7, an IPv6 packet with a multicast destination address is transmitted to the mapped Ethernet multicast address. Test: ipv6.TestLinkResolution stack_test.TestDADResolve stack_test.TestRouterSolicitation
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_test.go", "new_path": "pkg/tcpip/header/ipv6_test.go", "diff": "@@ -17,6 +17,7 @@ package header_test\nimport (\n\"bytes\"\n\"crypto/sha256\"\n+ \"fmt\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n@@ -300,3 +301,31 @@ func TestScopeForIPv6Address(t *testing.T) {\n})\n}\n}\n+\n+func TestSolicitedNodeAddr(t *testing.T) {\n+ tests := []struct {\n+ addr tcpip.Address\n+ want tcpip.Address\n+ }{\n+ {\n+ addr: \"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\xa0\",\n+ want: \"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x0e\\x0f\\xa0\",\n+ },\n+ {\n+ addr: \"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\xdd\\x0e\\x0f\\xa0\",\n+ want: \"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x0e\\x0f\\xa0\",\n+ },\n+ {\n+ addr: \"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\xdd\\x01\\x02\\x03\",\n+ want: \"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x01\\x02\\x03\",\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(fmt.Sprintf(\"%s\", test.addr), func(t *testing.T) {\n+ if got := header.SolicitedNodeAddr(test.addr); got != test.want {\n+ t.Fatalf(\"got header.SolicitedNodeAddr(%s) = %s, want = %s\", test.addr, got, test.want)\n+ }\n+ })\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/link/channel/channel.go", "new_path": "pkg/tcpip/link/channel/channel.go", "diff": "@@ -30,6 +30,7 @@ type PacketInfo struct {\nPkt tcpip.PacketBuffer\nProto tcpip.NetworkProtocolNumber\nGSO *stack.GSO\n+ Route stack.Route\n}\n// Endpoint is link layer endpoint that stores outbound packets in a channel\n@@ -38,7 +39,7 @@ type Endpoint struct {\ndispatcher stack.NetworkDispatcher\nmtu uint32\nlinkAddr tcpip.LinkAddress\n- GSO bool\n+ LinkEPCapabilities stack.LinkEndpointCapabilities\n// c is where outbound packets are queued.\nc chan PacketInfo\n@@ -122,11 +123,7 @@ func (e *Endpoint) MTU() uint32 {\n// Capabilities implements stack.LinkEndpoint.Capabilities.\nfunc (e *Endpoint) Capabilities() stack.LinkEndpointCapabilities {\n- caps := stack.LinkEndpointCapabilities(0)\n- if e.GSO {\n- caps |= stack.CapabilityHardwareGSO\n- }\n- return caps\n+ return e.LinkEPCapabilities\n}\n// GSOMaxSize returns the maximum GSO packet size.\n@@ -146,11 +143,16 @@ func (e *Endpoint) LinkAddress() tcpip.LinkAddress {\n}\n// WritePacket stores outbound packets into the channel.\n-func (e *Endpoint) WritePacket(_ *stack.Route, gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) *tcpip.Error {\n+func (e *Endpoint) WritePacket(r *stack.Route, gso *stack.GSO, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) *tcpip.Error {\n+ // Clone r then release its resource so we only get the relevant fields from\n+ // stack.Route without holding a reference to a NIC's endpoint.\n+ route := r.Clone()\n+ route.Release()\np := PacketInfo{\nPkt: pkt,\nProto: protocol,\nGSO: gso,\n+ Route: route,\n}\nselect {\n@@ -162,7 +164,11 @@ func (e *Endpoint) WritePacket(_ *stack.Route, gso *stack.GSO, protocol tcpip.Ne\n}\n// WritePackets stores outbound packets into the channel.\n-func (e *Endpoint) WritePackets(_ *stack.Route, gso *stack.GSO, pkts []tcpip.PacketBuffer, protocol tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n+func (e *Endpoint) WritePackets(r *stack.Route, gso *stack.GSO, pkts []tcpip.PacketBuffer, protocol tcpip.NetworkProtocolNumber) (int, *tcpip.Error) {\n+ // Clone r then release its resource so we only get the relevant fields from\n+ // stack.Route without holding a reference to a NIC's endpoint.\n+ route := r.Clone()\n+ route.Release()\npayloadView := pkts[0].Data.ToView()\nn := 0\npacketLoop:\n@@ -176,6 +182,7 @@ packetLoop:\n},\nProto: protocol,\nGSO: gso,\n+ Route: route,\n}\nselect {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "@@ -408,10 +408,14 @@ func (*protocol) LinkAddressProtocol() tcpip.NetworkProtocolNumber {\n// LinkAddressRequest implements stack.LinkAddressResolver.\nfunc (*protocol) LinkAddressRequest(addr, localAddr tcpip.Address, linkEP stack.LinkEndpoint) *tcpip.Error {\nsnaddr := header.SolicitedNodeAddr(addr)\n+\n+ // TODO(b/148672031): Use stack.FindRoute instead of manually creating the\n+ // route here. Note, we would need the nicID to do this properly so the right\n+ // NIC (associated to linkEP) is used to send the NDP NS message.\nr := &stack.Route{\nLocalAddress: localAddr,\nRemoteAddress: snaddr,\n- RemoteLinkAddress: broadcastMAC,\n+ RemoteLinkAddress: header.EthernetAddressFromMulticastIPv6Address(snaddr),\n}\nhdr := buffer.NewPrependable(int(linkEP.MaxHeaderLength()) + header.IPv6MinimumSize + header.ICMPv6NeighborAdvertSize)\npkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborAdvertSize))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -272,6 +272,7 @@ func (c *testContext) cleanup() {\ntype routeArgs struct {\nsrc, dst *channel.Endpoint\ntyp header.ICMPv6Type\n+ remoteLinkAddr tcpip.LinkAddress\n}\nfunc routeICMPv6Packet(t *testing.T, args routeArgs, fn func(*testing.T, header.ICMPv6)) {\n@@ -292,6 +293,11 @@ func routeICMPv6Packet(t *testing.T, args routeArgs, fn func(*testing.T, header.\nt.Errorf(\"unexpected protocol number %d\", pi.Proto)\nreturn\n}\n+\n+ if len(args.remoteLinkAddr) != 0 && args.remoteLinkAddr != pi.Route.RemoteLinkAddress {\n+ t.Errorf(\"got remote link address = %s, want = %s\", pi.Route.RemoteLinkAddress, args.remoteLinkAddr)\n+ }\n+\nipv6 := header.IPv6(pi.Pkt.Header.View())\ntransProto := tcpip.TransportProtocolNumber(ipv6.NextHeader())\nif transProto != header.ICMPv6ProtocolNumber {\n@@ -339,7 +345,7 @@ func TestLinkResolution(t *testing.T) {\nt.Fatalf(\"ep.Write(_) = _, <non-nil>, %s, want = _, <non-nil>, tcpip.ErrNoLinkAddress\", err)\n}\nfor _, args := range []routeArgs{\n- {src: c.linkEP0, dst: c.linkEP1, typ: header.ICMPv6NeighborSolicit},\n+ {src: c.linkEP0, dst: c.linkEP1, typ: header.ICMPv6NeighborSolicit, remoteLinkAddr: header.EthernetAddressFromMulticastIPv6Address(header.SolicitedNodeAddr(lladdr1))},\n{src: c.linkEP1, dst: c.linkEP0, typ: header.ICMPv6NeighborAdvert},\n} {\nrouteICMPv6Packet(t, args, func(t *testing.T, icmpv6 header.ICMPv6) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -538,6 +538,14 @@ func (ndp *ndpState) sendDADPacket(addr tcpip.Address) *tcpip.Error {\nr := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, snmc, ndp.nic.linkEP.LinkAddress(), ref, false, false)\ndefer r.Release()\n+ // Route should resolve immediately since snmc is a multicast address so a\n+ // remote link address can be calculated without a resolution process.\n+ if c, err := r.Resolve(nil); err != nil {\n+ log.Fatalf(\"ndp: error when resolving route to send NDP NS for DAD (%s -> %s on NIC(%d)): %s\", header.IPv6Any, snmc, ndp.nic.ID(), err)\n+ } else if c != nil {\n+ log.Fatalf(\"ndp: route resolution not immediate for route to send NDP NS for DAD (%s -> %s on NIC(%d))\", header.IPv6Any, snmc, ndp.nic.ID())\n+ }\n+\nhdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + header.ICMPv6NeighborSolicitMinimumSize)\npkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborSolicitMinimumSize))\npkt.SetType(header.ICMPv6NeighborSolicit)\n@@ -1197,6 +1205,15 @@ func (ndp *ndpState) startSolicitingRouters() {\nr := makeRoute(header.IPv6ProtocolNumber, header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.linkEP.LinkAddress(), ref, false, false)\ndefer r.Release()\n+ // Route should resolve immediately since\n+ // header.IPv6AllRoutersMulticastAddress is a multicast address so a\n+ // remote link address can be calculated without a resolution process.\n+ if c, err := r.Resolve(nil); err != nil {\n+ log.Fatalf(\"ndp: error when resolving route to send NDP RS (%s -> %s on NIC(%d)): %s\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID(), err)\n+ } else if c != nil {\n+ log.Fatalf(\"ndp: route resolution not immediate for route to send NDP RS (%s -> %s on NIC(%d))\", header.IPv6Any, header.IPv6AllRoutersMulticastAddress, ndp.nic.ID())\n+ }\n+\npayloadSize := header.ICMPv6HeaderSize + header.NDPRSMinimumSize\nhdr := buffer.NewPrependable(header.IPv6MinimumSize + payloadSize)\npkt := header.ICMPv6(hdr.Prepend(payloadSize))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -336,6 +336,7 @@ func TestDADResolve(t *testing.T) {\nopts.NDPConfigs.DupAddrDetectTransmits = test.dupAddrDetectTransmits\ne := channel.New(int(test.dupAddrDetectTransmits), 1280, linkAddr1)\n+ e.LinkEPCapabilities |= stack.CapabilityResolutionRequired\ns := stack.New(opts)\nif err := s.CreateNIC(nicID, e); err != nil {\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n@@ -413,6 +414,12 @@ func TestDADResolve(t *testing.T) {\nt.Fatalf(\"got Proto = %d, want = %d\", p.Proto, header.IPv6ProtocolNumber)\n}\n+ // Make sure the right remote link address is used.\n+ snmc := header.SolicitedNodeAddr(addr1)\n+ if want := header.EthernetAddressFromMulticastIPv6Address(snmc); p.Route.RemoteLinkAddress != want {\n+ t.Errorf(\"got remote link address = %s, want = %s\", p.Route.RemoteLinkAddress, want)\n+ }\n+\n// Check NDP NS packet.\n//\n// As per RFC 4861 section 4.3, a possible option is the Source Link\n@@ -420,7 +427,7 @@ func TestDADResolve(t *testing.T) {\n// address of the packet is the unspecified address.\nchecker.IPv6(t, p.Pkt.Header.View().ToVectorisedView().First(),\nchecker.SrcAddr(header.IPv6Any),\n- checker.DstAddr(header.SolicitedNodeAddr(addr1)),\n+ checker.DstAddr(snmc),\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPNS(\nchecker.NDPNSTargetAddress(addr1),\n@@ -3292,6 +3299,7 @@ func TestRouterSolicitation(t *testing.T) {\nt.Run(test.name, func(t *testing.T) {\nt.Parallel()\ne := channel.New(int(test.maxRtrSolicit), 1280, linkAddr1)\n+ e.LinkEPCapabilities |= stack.CapabilityResolutionRequired\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\nctx, _ := context.WithTimeout(context.Background(), timeout)\n@@ -3304,6 +3312,12 @@ func TestRouterSolicitation(t *testing.T) {\nif p.Proto != header.IPv6ProtocolNumber {\nt.Fatalf(\"got Proto = %d, want = %d\", p.Proto, header.IPv6ProtocolNumber)\n}\n+\n+ // Make sure the right remote link address is used.\n+ if want := header.EthernetAddressFromMulticastIPv6Address(header.IPv6AllRoutersMulticastAddress); p.Route.RemoteLinkAddress != want {\n+ t.Errorf(\"got remote link address = %s, want = %s\", p.Route.RemoteLinkAddress, want)\n+ }\n+\nchecker.IPv6(t,\np.Pkt.Header.View(),\nchecker.SrcAddr(header.IPv6Any),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/route.go", "new_path": "pkg/tcpip/stack/route.go", "diff": "@@ -225,7 +225,9 @@ func (r *Route) Release() {\n// Clone Clone a route such that the original one can be released and the new\n// one will remain valid.\nfunc (r *Route) Clone() Route {\n+ if r.ref != nil {\nr.ref.incRef()\n+ }\nreturn *r\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -1082,7 +1082,11 @@ func (c *Context) SACKEnabled() bool {\n// SetGSOEnabled enables or disables generic segmentation offload.\nfunc (c *Context) SetGSOEnabled(enable bool) {\n- c.linkEP.GSO = enable\n+ if enable {\n+ c.linkEP.LinkEPCapabilities |= stack.CapabilityHardwareGSO\n+ } else {\n+ c.linkEP.LinkEPCapabilities &^= stack.CapabilityHardwareGSO\n+ }\n}\n// MSSWithoutOptions returns the value for the MSS used by the stack when no\n" } ]
Go
Apache License 2.0
google/gvisor
Use multicast Ethernet address for multicast NDP As per RFC 2464 section 7, an IPv6 packet with a multicast destination address is transmitted to the mapped Ethernet multicast address. Test: - ipv6.TestLinkResolution - stack_test.TestDADResolve - stack_test.TestRouterSolicitation PiperOrigin-RevId: 292610529
259,860
31.01.2020 14:14:52
28,800
6c3072243dfbf70062de5f610e14fd6ed2ce5f32
Implement file locks for regular tmpfs files in VFSv2. Add a file lock implementation that can be embedded into various filesystem implementations. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "new_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "diff": "@@ -38,6 +38,7 @@ go_library(\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/fs\",\n\"//pkg/sentry/fs/fsutil\",\n+ \"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/pipe\",\n@@ -47,6 +48,7 @@ go_library(\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n+ \"//pkg/sentry/vfs/lock\",\n\"//pkg/sync\",\n\"//pkg/syserror\",\n\"//pkg/usermem\",\n@@ -86,6 +88,7 @@ go_test(\n\"//pkg/context\",\n\"//pkg/fspath\",\n\"//pkg/sentry/contexttest\",\n+ \"//pkg/sentry/fs/lock\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/contexttest\",\n\"//pkg/sentry/vfs\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n@@ -192,6 +193,28 @@ func (fd *regularFileFD) Sync(ctx context.Context) error {\nreturn nil\n}\n+// LockBSD implements vfs.FileDescriptionImpl.LockBSD.\n+func (fd *regularFileFD) LockBSD(ctx context.Context, uid lock.UniqueID, t lock.LockType, block lock.Blocker) error {\n+ return fd.inode().lockBSD(uid, t, block)\n+}\n+\n+// UnlockBSD implements vfs.FileDescriptionImpl.UnlockBSD.\n+func (fd *regularFileFD) UnlockBSD(ctx context.Context, uid lock.UniqueID) error {\n+ fd.inode().unlockBSD(uid)\n+ return nil\n+}\n+\n+// LockPOSIX implements vfs.FileDescriptionImpl.LockPOSIX.\n+func (fd *regularFileFD) LockPOSIX(ctx context.Context, uid lock.UniqueID, t lock.LockType, rng lock.LockRange, block lock.Blocker) error {\n+ return fd.inode().lockPOSIX(uid, t, rng, block)\n+}\n+\n+// UnlockPOSIX implements vfs.FileDescriptionImpl.UnlockPOSIX.\n+func (fd *regularFileFD) UnlockPOSIX(ctx context.Context, uid lock.UniqueID, rng lock.LockRange) error {\n+ fd.inode().unlockPOSIX(uid, rng)\n+ return nil\n+}\n+\n// regularFileReadWriter implements safemem.Reader and Safemem.Writer.\ntype regularFileReadWriter struct {\nfile *regularFile\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file_test.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file_test.go", "diff": "@@ -24,9 +24,11 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -260,6 +262,60 @@ func TestPWrite(t *testing.T) {\n}\n}\n+func TestLocks(t *testing.T) {\n+ ctx := contexttest.Context(t)\n+ fd, cleanup, err := newFileFD(ctx, 0644)\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ defer cleanup()\n+\n+ var (\n+ uid1 lock.UniqueID\n+ uid2 lock.UniqueID\n+ // Non-blocking.\n+ block lock.Blocker\n+ )\n+\n+ uid1 = 123\n+ uid2 = 456\n+\n+ if err := fd.Impl().LockBSD(ctx, uid1, lock.ReadLock, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockBSD failed: err = %v\", err)\n+ }\n+ if err := fd.Impl().LockBSD(ctx, uid2, lock.ReadLock, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockBSD failed: err = %v\", err)\n+ }\n+ if got, want := fd.Impl().LockBSD(ctx, uid2, lock.WriteLock, block), syserror.ErrWouldBlock; got != want {\n+ t.Fatalf(\"fd.Impl().LockBSD failed: got = %v, want = %v\", got, want)\n+ }\n+ if err := fd.Impl().UnlockBSD(ctx, uid1); err != nil {\n+ t.Fatalf(\"fd.Impl().UnlockBSD failed: err = %v\", err)\n+ }\n+ if err := fd.Impl().LockBSD(ctx, uid2, lock.WriteLock, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockBSD failed: err = %v\", err)\n+ }\n+\n+ rng1 := lock.LockRange{0, 1}\n+ rng2 := lock.LockRange{1, 2}\n+\n+ if err := fd.Impl().LockPOSIX(ctx, uid1, lock.ReadLock, rng1, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockPOSIX failed: err = %v\", err)\n+ }\n+ if err := fd.Impl().LockPOSIX(ctx, uid2, lock.ReadLock, rng2, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockPOSIX failed: err = %v\", err)\n+ }\n+ if err := fd.Impl().LockPOSIX(ctx, uid1, lock.WriteLock, rng1, block); err != nil {\n+ t.Fatalf(\"fd.Impl().LockPOSIX failed: err = %v\", err)\n+ }\n+ if got, want := fd.Impl().LockPOSIX(ctx, uid2, lock.ReadLock, rng1, block), syserror.ErrWouldBlock; got != want {\n+ t.Fatalf(\"fd.Impl().LockPOSIX failed: got = %v, want = %v\", got, want)\n+ }\n+ if err := fd.Impl().UnlockPOSIX(ctx, uid1, rng1); err != nil {\n+ t.Fatalf(\"fd.Impl().UnlockPOSIX failed: err = %v\", err)\n+ }\n+}\n+\nfunc TestPRead(t *testing.T) {\nctx := contexttest.Context(t)\nfd, cleanup, err := newFileFD(ctx, 0644)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -30,10 +30,12 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n+ fslock \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\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/vfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs/lock\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -153,6 +155,9 @@ type inode struct {\nrdevMajor uint32\nrdevMinor uint32\n+ // Advisory file locks, which lock at the inode level.\n+ locks lock.FileLocks\n+\nimpl interface{} // immutable\n}\n@@ -352,6 +357,44 @@ func (i *inode) setStat(stat linux.Statx) error {\nreturn nil\n}\n+// TODO(gvisor.dev/issue/1480): support file locking for file types other than regular.\n+func (i *inode) lockBSD(uid fslock.UniqueID, t fslock.LockType, block fslock.Blocker) error {\n+ switch i.impl.(type) {\n+ case *regularFile:\n+ return i.locks.LockBSD(uid, t, block)\n+ }\n+ return syserror.EBADF\n+}\n+\n+// TODO(gvisor.dev/issue/1480): support file locking for file types other than regular.\n+func (i *inode) unlockBSD(uid fslock.UniqueID) error {\n+ switch i.impl.(type) {\n+ case *regularFile:\n+ i.locks.UnlockBSD(uid)\n+ return nil\n+ }\n+ return syserror.EBADF\n+}\n+\n+// TODO(gvisor.dev/issue/1480): support file locking for file types other than regular.\n+func (i *inode) lockPOSIX(uid fslock.UniqueID, t fslock.LockType, rng fslock.LockRange, block fslock.Blocker) error {\n+ switch i.impl.(type) {\n+ case *regularFile:\n+ return i.locks.LockPOSIX(uid, t, rng, block)\n+ }\n+ return syserror.EBADF\n+}\n+\n+// TODO(gvisor.dev/issue/1480): support file locking for file types other than regular.\n+func (i *inode) unlockPOSIX(uid fslock.UniqueID, rng fslock.LockRange) error {\n+ switch i.impl.(type) {\n+ case *regularFile:\n+ i.locks.UnlockPOSIX(uid, rng)\n+ return nil\n+ }\n+ return syserror.EBADF\n+}\n+\n// allocatedBlocksForSize returns the number of 512B blocks needed to\n// accommodate the given size in bytes, as appropriate for struct\n// stat::st_blocks and struct statx::stx_blocks. (Note that this 512B block\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/vfs/lock/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"lock\",\n+ srcs = [\"lock.go\"],\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/sentry/fs/lock\",\n+ \"//pkg/syserror\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/vfs/lock/lock.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package lock provides POSIX and BSD style file locking for VFS2 file\n+// implementations.\n+//\n+// The actual implementations can be found in the lock package under\n+// sentry/fs/lock.\n+package lock\n+\n+import (\n+ fslock \"gvisor.dev/gvisor/pkg/sentry/fs/lock\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// FileLocks supports POSIX and BSD style locks, which correspond to fcntl(2)\n+// and flock(2) respectively in Linux. It can be embedded into various file\n+// implementations for VFS2 that support locking.\n+//\n+// Note that in Linux these two types of locks are _not_ cooperative, because\n+// race and deadlock conditions make merging them prohibitive. We do the same\n+// and keep them oblivious to each other.\n+type FileLocks struct {\n+ // bsd is a set of BSD-style advisory file wide locks, see flock(2).\n+ bsd fslock.Locks\n+\n+ // posix is a set of POSIX-style regional advisory locks, see fcntl(2).\n+ posix fslock.Locks\n+}\n+\n+// LockBSD tries to acquire a BSD-style lock on the entire file.\n+func (fl *FileLocks) LockBSD(uid fslock.UniqueID, t fslock.LockType, block fslock.Blocker) error {\n+ if fl.bsd.LockRegion(uid, t, fslock.LockRange{0, fslock.LockEOF}, block) {\n+ return nil\n+ }\n+ return syserror.ErrWouldBlock\n+}\n+\n+// UnlockBSD releases a BSD-style lock on the entire file.\n+//\n+// This operation is always successful, even if there did not exist a lock on\n+// the requested region held by uid in the first place.\n+func (fl *FileLocks) UnlockBSD(uid fslock.UniqueID) {\n+ fl.bsd.UnlockRegion(uid, fslock.LockRange{0, fslock.LockEOF})\n+}\n+\n+// LockPOSIX tries to acquire a POSIX-style lock on a file region.\n+func (fl *FileLocks) LockPOSIX(uid fslock.UniqueID, t fslock.LockType, rng fslock.LockRange, block fslock.Blocker) error {\n+ if fl.posix.LockRegion(uid, t, rng, block) {\n+ return nil\n+ }\n+ return syserror.ErrWouldBlock\n+}\n+\n+// UnlockPOSIX releases a POSIX-style lock on a file region.\n+//\n+// This operation is always successful, even if there did not exist a lock on\n+// the requested region held by uid in the first place.\n+func (fl *FileLocks) UnlockPOSIX(uid fslock.UniqueID, rng fslock.LockRange) {\n+ fl.posix.UnlockRegion(uid, rng)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement file locks for regular tmpfs files in VFSv2. Add a file lock implementation that can be embedded into various filesystem implementations. Updates #1480 PiperOrigin-RevId: 292614758
259,858
31.01.2020 14:44:50
28,800
04cccaaeeed22a28a42fc4c1406b43a966a5d886
Fix logic around AMD/Intel cases. If the support is Ignored, then the call is still executed. We simply rely on it to fall through to the int3. Therefore, we must also bail on the vendor check.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/32bit.cc", "new_path": "test/syscalls/linux/32bit.cc", "diff": "@@ -102,7 +102,8 @@ TEST(Syscall32Bit, Int80) {\n}\nTEST(Syscall32Bit, Sysenter) {\n- if (PlatformSupport32Bit() == PlatformSupport::Allowed &&\n+ if ((PlatformSupport32Bit() == PlatformSupport::Allowed ||\n+ PlatformSupport32Bit() == PlatformSupport::Ignored) &&\nGetCPUVendor() == CPUVendor::kAMD) {\n// SYSENTER is an illegal instruction in compatibility mode on AMD.\nEXPECT_EXIT(ExitGroup32(kSysenter, kExitCode),\n@@ -133,7 +134,8 @@ TEST(Syscall32Bit, Sysenter) {\n}\nTEST(Syscall32Bit, Syscall) {\n- if (PlatformSupport32Bit() == PlatformSupport::Allowed &&\n+ if ((PlatformSupport32Bit() == PlatformSupport::Allowed ||\n+ PlatformSupport32Bit() == PlatformSupport::Ignored) &&\nGetCPUVendor() == CPUVendor::kIntel) {\n// SYSCALL is an illegal instruction in compatibility mode on Intel.\nEXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n" } ]
Go
Apache License 2.0
google/gvisor
Fix logic around AMD/Intel cases. If the support is Ignored, then the call is still executed. We simply rely on it to fall through to the int3. Therefore, we must also bail on the vendor check. PiperOrigin-RevId: 292620558
259,854
31.01.2020 15:08:17
28,800
02997af5abd62d778fca4d01b047a6bdebab2090
Fix method comment to match method name.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -271,8 +271,8 @@ func (l *listenContext) createConnectingEndpoint(s *segment, iss seqnum.Value, i\nreturn n, nil\n}\n-// createEndpoint creates a new endpoint in connected state and then performs\n-// the TCP 3-way handshake.\n+// createEndpointAndPerformHandshake creates a new endpoint in connected state\n+// and then performs the TCP 3-way handshake.\nfunc (l *listenContext) createEndpointAndPerformHandshake(s *segment, opts *header.TCPSynOptions, queue *waiter.Queue) (*endpoint, *tcpip.Error) {\n// Create new endpoint.\nirs := s.sequenceNumber\n" } ]
Go
Apache License 2.0
google/gvisor
Fix method comment to match method name. PiperOrigin-RevId: 292624867
259,881
03.02.2020 11:39:01
28,800
4d1a648c7c5db8a51416bff647260a1be3b5c12e
Allow mlock in system call filters Go 1.14 has a workaround for a Linux 5.2-5.4 bug which requires mlock'ing the g stack to prevent register corruption. We need to allow this syscall until it is removed from Go.
[ { "change_type": "MODIFY", "old_path": "runsc/boot/filter/config.go", "new_path": "runsc/boot/filter/config.go", "diff": "@@ -174,6 +174,18 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_LSEEK: {},\nsyscall.SYS_MADVISE: {},\nsyscall.SYS_MINCORE: {},\n+ // Used by the Go runtime as a temporarily workaround for a Linux\n+ // 5.2-5.4 bug.\n+ //\n+ // See src/runtime/os_linux_x86.go.\n+ //\n+ // TODO(b/148688965): Remove once this is gone from Go.\n+ syscall.SYS_MLOCK: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4096),\n+ },\n+ },\nsyscall.SYS_MMAP: []seccomp.Rule{\n{\nseccomp.AllowAny{},\n" } ]
Go
Apache License 2.0
google/gvisor
Allow mlock in system call filters Go 1.14 has a workaround for a Linux 5.2-5.4 bug which requires mlock'ing the g stack to prevent register corruption. We need to allow this syscall until it is removed from Go. PiperOrigin-RevId: 292967478
259,972
03.02.2020 12:03:38
28,800
9742daf3c201771d257c0d043347f4eebf3088e0
Add packetdrill tests that use docker.
[ { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/BUILD", "diff": "+load(\"defs.bzl\", \"packetdrill_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+packetdrill_test(\n+ name = \"fin_wait2_timeout\",\n+ scripts = [\"fin_wait2_timeout.pkt\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/Dockerfile", "diff": "+FROM ubuntu:bionic\n+\n+RUN apt-get update\n+RUN apt-get install -y net-tools git iptables iputils-ping netcat tcpdump jq tar\n+RUN hash -r\n+RUN git clone --branch packetdrill-v2.0 \\\n+ https://github.com/google/packetdrill.git\n+RUN cd packetdrill/gtests/net/packetdrill && ./configure && \\\n+ apt-get install -y bison flex make && make\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/defs.bzl", "diff": "+\"\"\"Defines a rule for packetdrill test targets.\"\"\"\n+\n+def _packetdrill_test_impl(ctx):\n+ test_runner = ctx.executable._test_runner\n+ runner = ctx.actions.declare_file(\"%s-runner\" % ctx.label.name)\n+\n+ script_paths = []\n+ for script in ctx.files.scripts:\n+ script_paths.append(script.short_path)\n+ runner_content = \"\\n\".join([\n+ \"#!/bin/bash\",\n+ # This test will run part in a distinct user namespace. This can cause\n+ # permission problems, because all runfiles may not be owned by the\n+ # current user, and no other users will be mapped in that namespace.\n+ # Make sure that everything is readable here.\n+ \"find . -type f -exec chmod a+rx {} \\\\;\",\n+ \"find . -type d -exec chmod a+rx {} \\\\;\",\n+ \"%s %s --init_script %s -- %s\\n\" % (\n+ test_runner.short_path,\n+ \" \".join(ctx.attr.flags),\n+ ctx.files._init_script[0].short_path,\n+ \" \".join(script_paths),\n+ ),\n+ ])\n+ ctx.actions.write(runner, runner_content, is_executable = True)\n+\n+ transitive_files = depset()\n+ if hasattr(ctx.attr._test_runner, \"data_runfiles\"):\n+ transitive_files = depset(ctx.attr._test_runner.data_runfiles.files)\n+ runfiles = ctx.runfiles(\n+ files = [test_runner] + ctx.files._init_script + ctx.files.scripts,\n+ transitive_files = transitive_files,\n+ collect_default = True,\n+ collect_data = True,\n+ )\n+ return [DefaultInfo(executable = runner, runfiles = runfiles)]\n+\n+_packetdrill_test = rule(\n+ attrs = {\n+ \"_test_runner\": attr.label(\n+ executable = True,\n+ cfg = \"host\",\n+ allow_files = True,\n+ default = \"packetdrill_test.sh\",\n+ ),\n+ \"_init_script\": attr.label(\n+ allow_single_file = True,\n+ default = \"packetdrill_setup.sh\",\n+ ),\n+ \"flags\": attr.string_list(\n+ mandatory = False,\n+ default = [],\n+ ),\n+ \"scripts\": attr.label_list(\n+ mandatory = True,\n+ allow_files = True,\n+ ),\n+ },\n+ test = True,\n+ implementation = _packetdrill_test_impl,\n+)\n+\n+_PACKETDRILL_TAGS = [\"local\", \"manual\"]\n+\n+def packetdrill_linux_test(name, **kwargs):\n+ if \"tags\" not in kwargs:\n+ kwargs[\"tags\"] = _PACKETDRILL_TAGS\n+ _packetdrill_test(\n+ name = name + \"_linux_test\",\n+ flags = [\"--dut_platform\", \"linux\"],\n+ **kwargs\n+ )\n+\n+def packetdrill_netstack_test(name, **kwargs):\n+ if \"tags\" not in kwargs:\n+ kwargs[\"tags\"] = _PACKETDRILL_TAGS\n+ _packetdrill_test(\n+ name = name + \"_netstack_test\",\n+ flags = [\"--dut_platform\", \"netstack\"],\n+ **kwargs\n+ )\n+\n+def packetdrill_test(**kwargs):\n+ packetdrill_linux_test(**kwargs)\n+ packetdrill_netstack_test(**kwargs)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/fin_wait2_timeout.pkt", "diff": "+// Test that a socket in FIN_WAIT_2 eventually times out and a subsequent\n+// packet generates a RST.\n+\n+0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3\n++0 bind(3, ..., ...) = 0\n+\n++0 listen(3, 1) = 0\n+\n+// Establish a connection without timestamps.\n++0 < S 0:0(0) win 32792 <mss 1460,sackOK,nop,nop,nop,wscale 7>\n++0 > S. 0:0(0) ack 1 <...>\n++0 < P. 1:1(0) ack 1 win 257\n+\n++0.100 accept(3, ..., ...) = 4\n+// set FIN_WAIT2 timeout to 1 seconds.\n++0.100 setsockopt(4, SOL_TCP, TCP_LINGER2, [1], 4) = 0\n++0 close(4) = 0\n+\n++0 > F. 1:1(0) ack 1 <...>\n++0 < . 1:1(0) ack 2 win 257\n+\n++1.1 < . 1:1(0) ack 2 win 257\n++0 > R 2:2(0) win 0\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/packetdrill_setup.sh", "diff": "+#!/bin/bash\n+\n+# 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+# This script runs both within the sentry context and natively. It should tweak\n+# TCP parameters to match expectations found in the script files.\n+sysctl -q net.ipv4.tcp_sack=1\n+sysctl -q net.ipv4.tcp_rmem=\"4096 2097152 $((8*1024*1024))\"\n+sysctl -q net.ipv4.tcp_wmem=\"4096 2097152 $((8*1024*1024))\"\n+\n+# There may be errors from the above, but they will show up in the test logs and\n+# we always want to proceed from this point. It's possible that values were\n+# already set correctly and the nodes were not available in the namespace.\n+exit 0\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/packetdrill/packetdrill_test.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2020 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# Run a packetdrill test. Two docker containers are made, one for the\n+# Device-Under-Test (DUT) and one for the test runner. Each is attached with\n+# two networks, one for control packets that aid the test and one for test\n+# packets which are sent as part of the test and observed for correctness.\n+\n+set -euxo pipefail\n+\n+function failure() {\n+ local lineno=$1\n+ local msg=$2\n+ local filename=\"$0\"\n+ echo \"FAIL: $filename:$lineno: $msg\"\n+}\n+trap 'failure ${LINENO} \"$BASH_COMMAND\"' ERR\n+\n+declare -r LONGOPTS=\"dut_platform:,init_script:\"\n+\n+# Don't use declare below so that the error from getopt will end the script.\n+PARSED=$(getopt --options \"\" --longoptions=$LONGOPTS --name \"$0\" -- \"$@\")\n+\n+eval set -- \"$PARSED\"\n+\n+while true; do\n+ case \"$1\" in\n+ --dut_platform)\n+ declare -r DUT_PLATFORM=\"$2\"\n+ shift 2\n+ ;;\n+ --init_script)\n+ declare -r INIT_SCRIPT=\"$2\"\n+ shift 2\n+ ;;\n+ --)\n+ shift\n+ break\n+ ;;\n+ *)\n+ echo \"Programming error\"\n+ exit 3\n+ esac\n+done\n+\n+# All the other arguments are scripts.\n+declare -r scripts=\"$@\"\n+\n+# Check that the required flags are defined in a way that is safe for \"set -u\".\n+if [[ \"${DUT_PLATFORM-}\" == \"netstack\" ]]; then\n+ declare -r RUNTIME=\"--runtime runsc-d\"\n+elif [[ \"${DUT_PLATFORM-}\" == \"linux\" ]]; then\n+ declare -r RUNTIME=\"\"\n+else\n+ echo \"FAIL: Bad or missing --dut_platform argument: ${DUT_PLATFORM-}\"\n+ exit 2\n+fi\n+if [[ ! -x \"${INIT_SCRIPT-}\" ]]; then\n+ echo \"FAIL: Bad or missing --init_script: ${INIT_SCRIPT-}\"\n+ exit 2\n+fi\n+\n+# Variables specific to the control network and interface start with CTRL_.\n+# Variables specific to the test network and interface start with TEST_.\n+# Variables specific to the DUT start with DUT_.\n+# Variables specific to the test runner start with TEST_RUNNER_.\n+declare -r PACKETDRILL=\"/packetdrill/gtests/net/packetdrill/packetdrill\"\n+# Use random numbers so that test networks don't collide.\n+declare -r CTRL_NET=\"ctrl_net-${RANDOM}${RANDOM}\"\n+declare -r TEST_NET=\"test_net-${RANDOM}${RANDOM}\"\n+declare -r tolerance_usecs=100000\n+# On both DUT and test runner, testing packets are on the eth2 interface.\n+declare -r TEST_DEVICE=\"eth2\"\n+# Number of bits in the *_NET_PREFIX variables.\n+declare -r NET_MASK=\"24\"\n+function new_net_prefix() {\n+ # Class C, 192.0.0.0 to 223.255.255.255, transitionally has mask 24.\n+ echo \"$(shuf -i 192-223 -n 1).$(shuf -i 0-255 -n 1).$(shuf -i 0-255 -n 1)\"\n+}\n+# Last bits of the DUT's IP address.\n+declare -r DUT_NET_SUFFIX=\".10\"\n+# Control port.\n+declare -r CTRL_PORT=\"40000\"\n+# Last bits of the test runner's IP address.\n+declare -r TEST_RUNNER_NET_SUFFIX=\".20\"\n+declare -r TIMEOUT=\"60\"\n+declare -r IMAGE_TAG=\"gcr.io/gvisor-presubmit/packetdrill\"\n+\n+# Make sure that docker is installed.\n+docker --version\n+\n+function finish {\n+ local cleanup_success=1\n+ for net in \"${CTRL_NET}\" \"${TEST_NET}\"; do\n+ # Kill all processes attached to ${net}.\n+ for docker_command in \"kill\" \"rm\"; do\n+ (docker network inspect \"${net}\" \\\n+ --format '{{range $key, $value := .Containers}}{{$key}} {{end}}' \\\n+ | xargs -r docker \"${docker_command}\") || \\\n+ cleanup_success=0\n+ done\n+ # Remove the network.\n+ docker network rm \"${net}\" || \\\n+ cleanup_success=0\n+ done\n+\n+ if ((!$cleanup_success)); then\n+ echo \"FAIL: Cleanup command failed\"\n+ exit 4\n+ fi\n+}\n+trap finish EXIT\n+\n+# Subnet for control packets between test runner and DUT.\n+declare CTRL_NET_PREFIX=$(new_net_prefix)\n+while ! docker network create \\\n+ \"--subnet=${CTRL_NET_PREFIX}.0/${NET_MASK}\" \"${CTRL_NET}\"; do\n+ sleep 0.1\n+ declare CTRL_NET_PREFIX=$(new_net_prefix)\n+done\n+\n+# Subnet for the packets that are part of the test.\n+declare TEST_NET_PREFIX=$(new_net_prefix)\n+while ! docker network create \\\n+ \"--subnet=${TEST_NET_PREFIX}.0/${NET_MASK}\" \"${TEST_NET}\"; do\n+ sleep 0.1\n+ declare TEST_NET_PREFIX=$(new_net_prefix)\n+done\n+\n+docker pull \"${IMAGE_TAG}\"\n+\n+# Create the DUT container and connect to network.\n+DUT=$(docker create ${RUNTIME} --privileged --rm \\\n+ --stop-timeout ${TIMEOUT} -it ${IMAGE_TAG})\n+docker network connect \"${CTRL_NET}\" \\\n+ --ip \"${CTRL_NET_PREFIX}${DUT_NET_SUFFIX}\" \"${DUT}\" \\\n+ || (docker kill ${DUT}; docker rm ${DUT}; false)\n+docker network connect \"${TEST_NET}\" \\\n+ --ip \"${TEST_NET_PREFIX}${DUT_NET_SUFFIX}\" \"${DUT}\" \\\n+ || (docker kill ${DUT}; docker rm ${DUT}; false)\n+docker start \"${DUT}\"\n+\n+# Create the test runner container and connect to network.\n+TEST_RUNNER=$(docker create --privileged --rm \\\n+ --stop-timeout ${TIMEOUT} -it ${IMAGE_TAG})\n+docker network connect \"${CTRL_NET}\" \\\n+ --ip \"${CTRL_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \"${TEST_RUNNER}\" \\\n+ || (docker kill ${TEST_RUNNER}; docker rm ${REST_RUNNER}; false)\n+docker network connect \"${TEST_NET}\" \\\n+ --ip \"${TEST_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \"${TEST_RUNNER}\" \\\n+ || (docker kill ${TEST_RUNNER}; docker rm ${REST_RUNNER}; false)\n+docker start \"${TEST_RUNNER}\"\n+\n+# Run tcpdump in the test runner unbuffered, without dns resolution, just on the\n+# interface with the test packets.\n+docker exec -t ${TEST_RUNNER} tcpdump -U -n -i \"${TEST_DEVICE}\" &\n+\n+# Start a packetdrill server on the test_runner. The packetdrill server sends\n+# packets and asserts that they are received.\n+docker exec -d \"${TEST_RUNNER}\" \\\n+ ${PACKETDRILL} --wire_server --wire_server_dev=\"${TEST_DEVICE}\" \\\n+ --wire_server_ip=\"${CTRL_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \\\n+ --wire_server_port=\"${CTRL_PORT}\" \\\n+ --local_ip=\"${TEST_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \\\n+ --remote_ip=\"${TEST_NET_PREFIX}${DUT_NET_SUFFIX}\"\n+\n+# Because the Linux kernel receives the SYN-ACK but didn't send the SYN it will\n+# issue a RST. To prevent this IPtables can be used to filter those out.\n+docker exec \"${TEST_RUNNER}\" \\\n+ iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP\n+\n+# Wait for the packetdrill server on the test runner to come. Attempt to\n+# connect to it from the DUT every 100 milliseconds until success.\n+while ! docker exec \"${DUT}\" \\\n+ nc -zv \"${CTRL_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \"${CTRL_PORT}\"; do\n+ sleep 0.1\n+done\n+\n+# Copy the packetdrill setup script to the DUT.\n+docker cp -L \"${INIT_SCRIPT}\" \"${DUT}:packetdrill_setup.sh\"\n+\n+# Copy the packetdrill scripts to the DUT.\n+declare -a dut_scripts\n+for script in $scripts; do\n+ docker cp -L \"${script}\" \"${DUT}:$(basename ${script})\"\n+ dut_scripts+=(\"/$(basename ${script})\")\n+done\n+\n+# Start a packetdrill client on the DUT. The packetdrill client runs POSIX\n+# socket commands and also sends instructions to the server.\n+docker exec -t \"${DUT}\" \\\n+ ${PACKETDRILL} --wire_client --wire_client_dev=\"${TEST_DEVICE}\" \\\n+ --wire_server_ip=\"${CTRL_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \\\n+ --wire_server_port=\"${CTRL_PORT}\" \\\n+ --local_ip=\"${TEST_NET_PREFIX}${DUT_NET_SUFFIX}\" \\\n+ --remote_ip=\"${TEST_NET_PREFIX}${TEST_RUNNER_NET_SUFFIX}\" \\\n+ --init_scripts=/packetdrill_setup.sh \\\n+ --tolerance_usecs=\"${tolerance_usecs}\" \"${dut_scripts[@]}\"\n+\n+echo PASS: No errors.\n" } ]
Go
Apache License 2.0
google/gvisor
Add packetdrill tests that use docker. PiperOrigin-RevId: 292973224
260,003
03.02.2020 15:30:28
28,800
e7846e50f2df070a15dd33235b334e2223f715f3
Reduce run time for //test/syscalls:socket_inet_loopback_test_runsc_ptrace. * Tests are picked for a shard differently. It now picks one test from each block, instead of picking the whole block. This makes the same kind of tests spreads across different shards. * Reduce the number of connect() calls in TCPListenClose.
[ { "change_type": "MODIFY", "old_path": "runsc/testutil/testutil.go", "new_path": "runsc/testutil/testutil.go", "diff": "@@ -434,43 +434,40 @@ func IsStatic(filename string) (bool, error) {\nreturn true, nil\n}\n-// TestBoundsForShard calculates the beginning and end indices for the test\n-// based on the TEST_SHARD_INDEX and TEST_TOTAL_SHARDS environment vars. The\n-// returned ints are the beginning (inclusive) and end (exclusive) of the\n-// subslice corresponding to the shard. If either of the env vars are not\n-// present, then the function will return bounds that include all tests. If\n-// there are more shards than there are tests, then the returned list may be\n-// empty.\n-func TestBoundsForShard(numTests int) (int, int, error) {\n+// TestIndicesForShard returns indices for this test shard based on the\n+// TEST_SHARD_INDEX and TEST_TOTAL_SHARDS environment vars.\n+//\n+// If either of the env vars are not present, then the function will return all\n+// tests. If there are more shards than there are tests, then the returned list\n+// may be empty.\n+func TestIndicesForShard(numTests int) ([]int, error) {\nvar (\n- begin = 0\n- end = numTests\n+ shardIndex = 0\n+ shardTotal = 1\n)\n- indexStr, totalStr := os.Getenv(\"TEST_SHARD_INDEX\"), os.Getenv(\"TEST_TOTAL_SHARDS\")\n- if indexStr == \"\" || totalStr == \"\" {\n- return begin, end, nil\n- }\n+ indexStr, totalStr := os.Getenv(\"TEST_SHARD_INDEX\"), os.Getenv(\"TEST_TOTAL_SHARDS\")\n+ if indexStr != \"\" && totalStr != \"\" {\n// Parse index and total to ints.\n- shardIndex, err := strconv.Atoi(indexStr)\n+ var err error\n+ shardIndex, err = strconv.Atoi(indexStr)\nif err != nil {\n- return 0, 0, fmt.Errorf(\"invalid TEST_SHARD_INDEX %q: %v\", indexStr, err)\n+ return nil, fmt.Errorf(\"invalid TEST_SHARD_INDEX %q: %v\", indexStr, err)\n}\n- shardTotal, err := strconv.Atoi(totalStr)\n+ shardTotal, err = strconv.Atoi(totalStr)\nif err != nil {\n- return 0, 0, fmt.Errorf(\"invalid TEST_TOTAL_SHARDS %q: %v\", totalStr, err)\n+ return nil, fmt.Errorf(\"invalid TEST_TOTAL_SHARDS %q: %v\", totalStr, err)\n+ }\n}\n// Calculate!\n- shardSize := int(math.Ceil(float64(numTests) / float64(shardTotal)))\n- begin = shardIndex * shardSize\n- end = ((shardIndex + 1) * shardSize)\n- if begin > numTests {\n- // Nothing to run.\n- return 0, 0, nil\n+ var indices []int\n+ numBlocks := int(math.Ceil(float64(numTests) / float64(shardTotal)))\n+ for i := 0; i < numBlocks; i++ {\n+ pick := i*shardTotal + shardIndex\n+ if pick < numTests {\n+ indices = append(indices, pick)\n}\n- if end > numTests {\n- end = numTests\n}\n- return begin, end, nil\n+ return indices, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "test/runtimes/runner.go", "new_path": "test/runtimes/runner.go", "diff": "@@ -20,7 +20,6 @@ import (\n\"flag\"\n\"fmt\"\n\"io\"\n- \"log\"\n\"os\"\n\"sort\"\n\"strings\"\n@@ -101,17 +100,15 @@ func getTests(d dockerutil.Docker, blacklist map[string]struct{}) ([]testing.Int\n// shard.\ntests := strings.Fields(list)\nsort.Strings(tests)\n- begin, end, err := testutil.TestBoundsForShard(len(tests))\n+ indices, err := testutil.TestIndicesForShard(len(tests))\nif err != nil {\nreturn nil, fmt.Errorf(\"TestsForShard() failed: %v\", err)\n}\n- log.Printf(\"Got bounds [%d:%d) for shard out of %d total tests\", begin, end, len(tests))\n- tests = tests[begin:end]\nvar itests []testing.InternalTest\n- for _, tc := range tests {\n+ for _, tci := range indices {\n// Capture tc in this scope.\n- tc := tc\n+ tc := tests[tci]\nitests = append(itests, testing.InternalTest{\nName: tc,\nF: func(t *testing.T) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -325,6 +325,12 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\nTestAddress const& listener = param.listener;\nTestAddress const& connector = param.connector;\n+ constexpr int kAcceptCount = 32;\n+ constexpr int kBacklog = kAcceptCount * 2;\n+ constexpr int kFDs = 128;\n+ constexpr int kThreadCount = 4;\n+ constexpr int kFDsPerThread = kFDs / kThreadCount;\n+\n// Create the listening socket.\nFileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(listener.family(), SOCK_STREAM, IPPROTO_TCP));\n@@ -332,7 +338,7 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\nASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),\nlistener.addr_len),\nSyscallSucceeds());\n- ASSERT_THAT(listen(listen_fd.get(), 1001), SyscallSucceeds());\n+ ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());\n// Get the port bound by the listening socket.\nsocklen_t addrlen = listener.addr_len;\n@@ -345,9 +351,6 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\nDisableSave ds; // Too many system calls.\nsockaddr_storage conn_addr = connector.addr;\nASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));\n- constexpr int kFDs = 2048;\n- constexpr int kThreadCount = 4;\n- constexpr int kFDsPerThread = kFDs / kThreadCount;\nFileDescriptor clients[kFDs];\nstd::unique_ptr<ScopedThread> threads[kThreadCount];\nfor (int i = 0; i < kFDs; i++) {\n@@ -371,7 +374,7 @@ TEST_P(SocketInetLoopbackTest, TCPListenClose) {\nfor (int i = 0; i < kThreadCount; i++) {\nthreads[i]->Join();\n}\n- for (int i = 0; i < 32; i++) {\n+ for (int i = 0; i < kAcceptCount; i++) {\nauto accepted =\nASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/syscall_test_runner.go", "new_path": "test/syscalls/syscall_test_runner.go", "diff": "@@ -450,17 +450,16 @@ func main() {\n}\n// Get subset of tests corresponding to shard.\n- begin, end, err := testutil.TestBoundsForShard(len(testCases))\n+ indices, err := testutil.TestIndicesForShard(len(testCases))\nif err != nil {\nfatalf(\"TestsForShard() failed: %v\", err)\n}\n- testCases = testCases[begin:end]\n// Run the tests.\nvar tests []testing.InternalTest\n- for _, tc := range testCases {\n+ for _, tci := range indices {\n// Capture tc.\n- tc := tc\n+ tc := testCases[tci]\ntestName := fmt.Sprintf(\"%s_%s\", tc.Suite, tc.Name)\ntests = append(tests, testing.InternalTest{\nName: testName,\n" } ]
Go
Apache License 2.0
google/gvisor
Reduce run time for //test/syscalls:socket_inet_loopback_test_runsc_ptrace. * Tests are picked for a shard differently. It now picks one test from each block, instead of picking the whole block. This makes the same kind of tests spreads across different shards. * Reduce the number of connect() calls in TCPListenClose. PiperOrigin-RevId: 293019281
259,847
03.02.2020 15:30:42
28,800
6cd7901d7d5f9639e95fff3d8927ba8856a83f91
Add 1 Kokoro job per runtime test.
[ { "change_type": "ADD", "old_path": null, "new_path": "kokoro/runtime_tests/go1.12.cfg", "diff": "+build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+\n+env_vars {\n+ key: \"RUNTIME_TEST_NAME\"\n+ value: \"go1.12\"\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "kokoro/runtime_tests/java11.cfg", "diff": "+build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+\n+env_vars {\n+ key: \"RUNTIME_TEST_NAME\"\n+ value: \"java11\"\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "kokoro/runtime_tests/nodejs12.4.0.cfg", "diff": "+build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+\n+env_vars {\n+ key: \"RUNTIME_TEST_NAME\"\n+ value: \"nodejs12.4.0\"\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "kokoro/runtime_tests/php7.3.6.cfg", "diff": "+build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+\n+env_vars {\n+ key: \"RUNTIME_TEST_NAME\"\n+ value: \"php7.3.6\"\n+}\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "kokoro/runtime_tests/python3.7.3.cfg", "diff": "+build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+\n+env_vars {\n+ key: \"RUNTIME_TEST_NAME\"\n+ value: \"python3.7.3\"\n+}\n\\ No newline at end of file\n" }, { "change_type": "RENAME", "old_path": "scripts/runtime_tests.sh", "new_path": "kokoro/runtime_tests/runtime_tests.sh", "diff": "" } ]
Go
Apache License 2.0
google/gvisor
Add 1 Kokoro job per runtime test. PiperOrigin-RevId: 293019326
259,853
03.02.2020 16:15:16
28,800
f37e913a358820ea98013772dd2880cc8a3c9218
seccomp: allow to filter syscalls by instruction pointer
[ { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp.go", "new_path": "pkg/seccomp/seccomp.go", "diff": "@@ -219,24 +219,36 @@ func addSyscallArgsCheck(p *bpf.ProgramBuilder, rules []Rule, action linux.BPFAc\nswitch a := arg.(type) {\ncase AllowAny:\ncase AllowValue:\n+ dataOffsetLow := seccompDataOffsetArgLow(i)\n+ dataOffsetHigh := seccompDataOffsetArgHigh(i)\n+ if i == RuleIP {\n+ dataOffsetLow = seccompDataOffsetIPLow\n+ dataOffsetHigh = seccompDataOffsetIPHigh\n+ }\nhigh, low := uint32(a>>32), uint32(a)\n// assert arg_low == low\n- p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, seccompDataOffsetArgLow(i))\n+ p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, dataOffsetLow)\np.AddJumpFalseLabel(bpf.Jmp|bpf.Jeq|bpf.K, low, 0, ruleViolationLabel(ruleSetIdx, sysno, ruleidx))\n// assert arg_high == high\n- p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, seccompDataOffsetArgHigh(i))\n+ p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, dataOffsetHigh)\np.AddJumpFalseLabel(bpf.Jmp|bpf.Jeq|bpf.K, high, 0, ruleViolationLabel(ruleSetIdx, sysno, ruleidx))\nlabelled = true\ncase GreaterThan:\n+ dataOffsetLow := seccompDataOffsetArgLow(i)\n+ dataOffsetHigh := seccompDataOffsetArgHigh(i)\n+ if i == RuleIP {\n+ dataOffsetLow = seccompDataOffsetIPLow\n+ dataOffsetHigh = seccompDataOffsetIPHigh\n+ }\nlabelGood := fmt.Sprintf(\"gt%v\", i)\nhigh, low := uint32(a>>32), uint32(a)\n// assert arg_high < high\n- p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, seccompDataOffsetArgHigh(i))\n+ p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, dataOffsetHigh)\np.AddJumpFalseLabel(bpf.Jmp|bpf.Jge|bpf.K, high, 0, ruleViolationLabel(ruleSetIdx, sysno, ruleidx))\n// arg_high > high\np.AddJumpFalseLabel(bpf.Jmp|bpf.Jeq|bpf.K, high, 0, ruleLabel(ruleSetIdx, sysno, ruleidx, labelGood))\n// arg_low < low\n- p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, seccompDataOffsetArgLow(i))\n+ p.AddStmt(bpf.Ld|bpf.Abs|bpf.W, dataOffsetLow)\np.AddJumpFalseLabel(bpf.Jmp|bpf.Jgt|bpf.K, low, 0, ruleViolationLabel(ruleSetIdx, sysno, ruleidx))\np.AddLabel(ruleLabel(ruleSetIdx, sysno, ruleidx, labelGood))\nlabelled = true\n" }, { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp_rules.go", "new_path": "pkg/seccomp/seccomp_rules.go", "diff": "@@ -62,7 +62,11 @@ func (a AllowValue) String() (s string) {\n// rule := Rule {\n// AllowValue(linux.ARCH_GET_FS | linux.ARCH_SET_FS), // arg0\n// }\n-type Rule [6]interface{}\n+type Rule [7]interface{} // 6 arguments + RIP\n+\n+// RuleIP indicates what rules in the Rule array have to be applied to\n+// instruction pointer.\n+const RuleIP = 6\nfunc (r Rule) String() (s string) {\nif len(r) == 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/seccomp/seccomp_test.go", "new_path": "pkg/seccomp/seccomp_test.go", "diff": "@@ -388,6 +388,33 @@ func TestBasic(t *testing.T) {\n},\n},\n},\n+ {\n+ ruleSets: []RuleSet{\n+ {\n+ Rules: SyscallRules{\n+ 1: []Rule{\n+ {\n+ RuleIP: AllowValue(0x7aabbccdd),\n+ },\n+ },\n+ },\n+ Action: linux.SECCOMP_RET_ALLOW,\n+ },\n+ },\n+ defaultAction: linux.SECCOMP_RET_TRAP,\n+ specs: []spec{\n+ {\n+ desc: \"IP: Syscall instruction pointer allowed\",\n+ data: seccompData{nr: 1, arch: linux.AUDIT_ARCH_X86_64, args: [6]uint64{}, instructionPointer: 0x7aabbccdd},\n+ want: linux.SECCOMP_RET_ALLOW,\n+ },\n+ {\n+ desc: \"IP: Syscall instruction pointer disallowed\",\n+ data: seccompData{nr: 1, arch: linux.AUDIT_ARCH_X86_64, args: [6]uint64{}, instructionPointer: 0x711223344},\n+ want: linux.SECCOMP_RET_TRAP,\n+ },\n+ },\n+ },\n} {\ninstrs, err := BuildProgram(test.ruleSets, test.defaultAction)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
seccomp: allow to filter syscalls by instruction pointer PiperOrigin-RevId: 293029446
259,992
04.02.2020 08:20:10
28,800
d7cd484091543827678f1548b8e5668a7a86e13f
Add support for sentry internal pipe for gofer mounts Internal pipes are supported similarly to how internal UDS is done. It is also controlled by the same flag. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/BUILD", "new_path": "pkg/sentry/fs/gofer/BUILD", "diff": "@@ -9,6 +9,7 @@ go_library(\n\"cache_policy.go\",\n\"context_file.go\",\n\"device.go\",\n+ \"fifo.go\",\n\"file.go\",\n\"file_state.go\",\n\"fs.go\",\n@@ -38,6 +39,7 @@ go_library(\n\"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fs/host\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/kernel/pipe\",\n\"//pkg/sentry/kernel/time\",\n\"//pkg/sentry/memmap\",\n\"//pkg/sentry/socket/unix/transport\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/cache_policy.go", "new_path": "pkg/sentry/fs/gofer/cache_policy.go", "diff": "@@ -127,6 +127,9 @@ func (cp cachePolicy) revalidate(ctx context.Context, name string, parent, child\nchildIops, ok := child.InodeOperations.(*inodeOperations)\nif !ok {\n+ if _, ok := child.InodeOperations.(*fifo); ok {\n+ return false\n+ }\npanic(fmt.Sprintf(\"revalidating inode operations of unknown type %T\", child.InodeOperations))\n}\nparentIops, ok := parent.InodeOperations.(*inodeOperations)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fs/gofer/fifo.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package gofer\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+)\n+\n+// +stateify savable\n+type fifo struct {\n+ fs.InodeOperations\n+ fileIops *inodeOperations\n+}\n+\n+var _ fs.InodeOperations = (*fifo)(nil)\n+\n+// Rename implements fs.InodeOperations. It forwards the call to the underlying\n+// file inode to handle the file rename. Note that file key remains the same\n+// after the rename to keep the endpoint mapping.\n+func (i *fifo) Rename(ctx context.Context, inode *fs.Inode, oldParent *fs.Inode, oldName string, newParent *fs.Inode, newName string, replacement bool) error {\n+ return i.fileIops.Rename(ctx, inode, oldParent, oldName, newParent, newName, replacement)\n+}\n+\n+// StatFS implements fs.InodeOperations.\n+func (i *fifo) StatFS(ctx context.Context) (fs.Info, error) {\n+ return i.fileIops.StatFS(ctx)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/gofer_test.go", "new_path": "pkg/sentry/fs/gofer/gofer_test.go", "diff": "@@ -61,7 +61,7 @@ func rootTest(t *testing.T, name string, cp cachePolicy, fn func(context.Context\nctx := contexttest.Context(t)\nsattr, rootInodeOperations := newInodeOperations(ctx, s, contextFile{\nfile: rootFile,\n- }, root.QID, p9.AttrMaskAll(), root.Attr, false /* socket */)\n+ }, root.QID, p9.AttrMaskAll(), root.Attr)\nm := fs.NewMountSource(ctx, s, &filesystem{}, fs.MountSourceFlags{})\nrootInode := fs.NewInode(ctx, rootInodeOperations, m, sattr)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/path.go", "new_path": "pkg/sentry/fs/gofer/path.go", "diff": "@@ -23,14 +23,24 @@ import (\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/sentry/device\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n)\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.\nconst maxFilenameLen = (1 << 16) - 1\n+func changeType(mode p9.FileMode, newType p9.FileMode) p9.FileMode {\n+ if newType&^p9.FileModeMask != 0 {\n+ panic(fmt.Sprintf(\"newType contained more bits than just file mode: %x\", newType))\n+ }\n+ clear := mode &^ p9.FileModeMask\n+ return clear | newType\n+}\n+\n// Lookup loads an Inode at name into a Dirent based on the session's cache\n// policy.\nfunc (i *inodeOperations) Lookup(ctx context.Context, dir *fs.Inode, name string) (*fs.Dirent, error) {\n@@ -69,8 +79,25 @@ func (i *inodeOperations) Lookup(ctx context.Context, dir *fs.Inode, name string\nreturn nil, err\n}\n+ if i.session().overrides != nil {\n+ // Check if file belongs to a internal named pipe. Note that it doesn't need\n+ // to check for sockets because it's done in newInodeOperations below.\n+ deviceKey := device.MultiDeviceKey{\n+ Device: p9attr.RDev,\n+ SecondaryDevice: i.session().connID,\n+ Inode: qids[0].Path,\n+ }\n+ unlock := i.session().overrides.lock()\n+ if pipeInode := i.session().overrides.getPipe(deviceKey); pipeInode != nil {\n+ unlock()\n+ pipeInode.IncRef()\n+ return fs.NewDirent(ctx, pipeInode, name), nil\n+ }\n+ unlock()\n+ }\n+\n// Construct the Inode operations.\n- sattr, node := newInodeOperations(ctx, i.fileState.s, newFile, qids[0], mask, p9attr, false)\n+ sattr, node := newInodeOperations(ctx, i.fileState.s, newFile, qids[0], mask, p9attr)\n// Construct a positive Dirent.\nreturn fs.NewDirent(ctx, fs.NewInode(ctx, node, dir.MountSource, sattr), name), nil\n@@ -138,7 +165,7 @@ func (i *inodeOperations) Create(ctx context.Context, dir *fs.Inode, name string\nqid := qids[0]\n// Construct the InodeOperations.\n- sattr, iops := newInodeOperations(ctx, i.fileState.s, unopened, qid, mask, p9attr, false)\n+ sattr, iops := newInodeOperations(ctx, i.fileState.s, unopened, qid, mask, p9attr)\n// Construct the positive Dirent.\nd := fs.NewDirent(ctx, fs.NewInode(ctx, iops, dir.MountSource, sattr), name)\n@@ -223,82 +250,115 @@ func (i *inodeOperations) Bind(ctx context.Context, dir *fs.Inode, name string,\nreturn nil, syserror.ENAMETOOLONG\n}\n- if i.session().endpoints == nil {\n+ if i.session().overrides == nil {\nreturn nil, syscall.EOPNOTSUPP\n}\n- // Create replaces the directory fid with the newly created/opened\n- // file, so clone this directory so it doesn't change out from under\n- // this node.\n- _, newFile, err := i.fileState.file.walk(ctx, nil)\n+ // Stabilize the override map while creation is in progress.\n+ unlock := i.session().overrides.lock()\n+ defer unlock()\n+\n+ sattr, iops, err := i.createEndpointFile(ctx, dir, name, perm, p9.ModeSocket)\nif err != nil {\nreturn nil, err\n}\n- // We're not going to use newFile after return.\n- defer newFile.close(ctx)\n- // Stabilize the endpoint map while creation is in progress.\n- unlock := i.session().endpoints.lock()\n- defer unlock()\n+ // Construct the positive Dirent.\n+ childDir := fs.NewDirent(ctx, fs.NewInode(ctx, iops, dir.MountSource, sattr), name)\n+ i.session().overrides.addBoundEndpoint(iops.fileState.key, childDir, ep)\n+ return childDir, nil\n+}\n+\n+// CreateFifo implements fs.InodeOperations.CreateFifo.\n+func (i *inodeOperations) CreateFifo(ctx context.Context, dir *fs.Inode, name string, perm fs.FilePermissions) error {\n+ if len(name) > maxFilenameLen {\n+ return syserror.ENAMETOOLONG\n+ }\n- // Create a regular file in the gofer and then mark it as a socket by\n- // adding this inode key in the 'endpoints' map.\nowner := fs.FileOwnerFromContext(ctx)\n- hostFile, err := newFile.create(ctx, name, p9.ReadWrite, p9.FileMode(perm.LinuxMode()), p9.UID(owner.UID), p9.GID(owner.GID))\n- if err != nil {\n- return nil, err\n+ mode := p9.FileMode(perm.LinuxMode()) | p9.ModeNamedPipe\n+\n+ // N.B. FIFOs use major/minor numbers 0.\n+ if _, err := i.fileState.file.mknod(ctx, name, mode, 0, 0, p9.UID(owner.UID), p9.GID(owner.GID)); err != nil {\n+ if i.session().overrides == nil || err != syscall.EPERM {\n+ return err\n+ }\n+ // If gofer doesn't support mknod, check if we can create an internal fifo.\n+ return i.createInternalFifo(ctx, dir, name, owner, perm)\n}\n- // We're not going to use this file.\n- hostFile.Close()\ni.touchModificationAndStatusChangeTime(ctx, dir)\n-\n- // Get the attributes of the file to create inode key.\n- qid, mask, attr, err := getattr(ctx, newFile)\n- if err != nil {\n- return nil, err\n+ return nil\n}\n- key := device.MultiDeviceKey{\n- Device: attr.RDev,\n- SecondaryDevice: i.session().connID,\n- Inode: qid.Path,\n+func (i *inodeOperations) createInternalFifo(ctx context.Context, dir *fs.Inode, name string, owner fs.FileOwner, perm fs.FilePermissions) error {\n+ if i.session().overrides == nil {\n+ return syserror.EPERM\n}\n- // Create child dirent.\n+ // Stabilize the override map while creation is in progress.\n+ unlock := i.session().overrides.lock()\n+ defer unlock()\n- // Get an unopened p9.File for the file we created so that it can be\n- // cloned and re-opened multiple times after creation.\n- _, unopened, err := i.fileState.file.walk(ctx, []string{name})\n+ sattr, fileOps, err := i.createEndpointFile(ctx, dir, name, perm, p9.ModeNamedPipe)\nif err != nil {\n- return nil, err\n+ return err\n}\n- // Construct the InodeOperations.\n- sattr, iops := newInodeOperations(ctx, i.fileState.s, unopened, qid, mask, attr, true)\n+ // First create a pipe.\n+ p := pipe.NewPipe(true /* isNamed */, pipe.DefaultPipeSize, usermem.PageSize)\n+\n+ // Wrap the fileOps with our Fifo.\n+ iops := &fifo{\n+ InodeOperations: pipe.NewInodeOperations(ctx, perm, p),\n+ fileIops: fileOps,\n+ }\n+ inode := fs.NewInode(ctx, iops, dir.MountSource, sattr)\n// Construct the positive Dirent.\nchildDir := fs.NewDirent(ctx, fs.NewInode(ctx, iops, dir.MountSource, sattr), name)\n- i.session().endpoints.add(key, childDir, ep)\n- return childDir, nil\n+ i.session().overrides.addPipe(fileOps.fileState.key, childDir, inode)\n+ return nil\n}\n-// CreateFifo implements fs.InodeOperations.CreateFifo.\n-func (i *inodeOperations) CreateFifo(ctx context.Context, dir *fs.Inode, name string, perm fs.FilePermissions) error {\n- if len(name) > maxFilenameLen {\n- return syserror.ENAMETOOLONG\n+// Caller must hold Session.endpoint lock.\n+func (i *inodeOperations) createEndpointFile(ctx context.Context, dir *fs.Inode, name string, perm fs.FilePermissions, fileType p9.FileMode) (fs.StableAttr, *inodeOperations, error) {\n+ _, dirClone, err := i.fileState.file.walk(ctx, nil)\n+ if err != nil {\n+ return fs.StableAttr{}, nil, err\n}\n+ // We're not going to use dirClone after return.\n+ defer dirClone.close(ctx)\n+ // Create a regular file in the gofer and then mark it as a socket by\n+ // adding this inode key in the 'overrides' map.\nowner := fs.FileOwnerFromContext(ctx)\n- mode := p9.FileMode(perm.LinuxMode()) | p9.ModeNamedPipe\n-\n- // N.B. FIFOs use major/minor numbers 0.\n- if _, err := i.fileState.file.mknod(ctx, name, mode, 0, 0, p9.UID(owner.UID), p9.GID(owner.GID)); err != nil {\n- return err\n+ hostFile, err := dirClone.create(ctx, name, p9.ReadWrite, p9.FileMode(perm.LinuxMode()), p9.UID(owner.UID), p9.GID(owner.GID))\n+ if err != nil {\n+ return fs.StableAttr{}, nil, err\n}\n+ // We're not going to use this file.\n+ hostFile.Close()\ni.touchModificationAndStatusChangeTime(ctx, dir)\n- return nil\n+\n+ // Get the attributes of the file to create inode key.\n+ qid, mask, attr, err := getattr(ctx, dirClone)\n+ if err != nil {\n+ return fs.StableAttr{}, nil, err\n+ }\n+\n+ // Get an unopened p9.File for the file we created so that it can be\n+ // cloned and re-opened multiple times after creation.\n+ _, unopened, err := i.fileState.file.walk(ctx, []string{name})\n+ if err != nil {\n+ return fs.StableAttr{}, nil, err\n+ }\n+\n+ // Construct new inode with file type overridden.\n+ attr.Mode = changeType(attr.Mode, fileType)\n+ sattr, iops := newInodeOperations(ctx, i.fileState.s, unopened, qid, mask, attr)\n+ return sattr, iops, nil\n}\n// Remove implements InodeOperations.Remove.\n@@ -307,20 +367,23 @@ func (i *inodeOperations) Remove(ctx context.Context, dir *fs.Inode, name string\nreturn syserror.ENAMETOOLONG\n}\n- var key device.MultiDeviceKey\n- removeSocket := false\n- if i.session().endpoints != nil {\n- // Find out if file being deleted is a socket that needs to be\n+ var key *device.MultiDeviceKey\n+ if i.session().overrides != nil {\n+ // Find out if file being deleted is a socket or pipe that needs to be\n// removed from endpoint map.\nif d, err := i.Lookup(ctx, dir, name); err == nil {\ndefer d.DecRef()\n- if fs.IsSocket(d.Inode.StableAttr) {\n- child := d.Inode.InodeOperations.(*inodeOperations)\n- key = child.fileState.key\n- removeSocket = true\n- // Stabilize the endpoint map while deletion is in progress.\n- unlock := i.session().endpoints.lock()\n+ if fs.IsSocket(d.Inode.StableAttr) || fs.IsPipe(d.Inode.StableAttr) {\n+ switch iops := d.Inode.InodeOperations.(type) {\n+ case *inodeOperations:\n+ key = &iops.fileState.key\n+ case *fifo:\n+ key = &iops.fileIops.fileState.key\n+ }\n+\n+ // Stabilize the override map while deletion is in progress.\n+ unlock := i.session().overrides.lock()\ndefer unlock()\n}\n}\n@@ -329,8 +392,8 @@ func (i *inodeOperations) Remove(ctx context.Context, dir *fs.Inode, name string\nif err := i.fileState.file.unlinkAt(ctx, name, 0); err != nil {\nreturn err\n}\n- if removeSocket {\n- i.session().endpoints.remove(key)\n+ if key != nil {\n+ i.session().overrides.remove(*key)\n}\ni.touchModificationAndStatusChangeTime(ctx, dir)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/session.go", "new_path": "pkg/sentry/fs/gofer/session.go", "diff": "@@ -33,60 +33,107 @@ import (\nvar DefaultDirentCacheSize uint64 = fs.DefaultDirentCacheSize\n// +stateify savable\n-type endpointMaps struct {\n- // mu protexts the direntMap, the keyMap, and the pathMap below.\n- mu sync.RWMutex `state:\"nosave\"`\n+type overrideInfo struct {\n+ dirent *fs.Dirent\n+\n+ // endpoint is set when dirent points to a socket. inode must not be set.\n+ endpoint transport.BoundEndpoint\n+\n+ // inode is set when dirent points to a pipe. endpoint must not be set.\n+ inode *fs.Inode\n+}\n- // direntMap links sockets to their dirents.\n- // It is filled concurrently with the keyMap and is stored upon save.\n- // Before saving, this map is used to populate the pathMap.\n- direntMap map[transport.BoundEndpoint]*fs.Dirent\n+func (l *overrideInfo) inodeType() fs.InodeType {\n+ switch {\n+ case l.endpoint != nil:\n+ return fs.Socket\n+ case l.inode != nil:\n+ return fs.Pipe\n+ }\n+ panic(\"endpoint or node must be set\")\n+}\n- // keyMap links MultiDeviceKeys (containing inode IDs) to their sockets.\n+// +stateify savable\n+type overrideMaps struct {\n+ // mu protexts the keyMap, and the pathMap below.\n+ mu sync.RWMutex `state:\"nosave\"`\n+\n+ // keyMap links MultiDeviceKeys (containing inode IDs) to their sockets/pipes.\n// It is not stored during save because the inode ID may change upon restore.\n- keyMap map[device.MultiDeviceKey]transport.BoundEndpoint `state:\"nosave\"`\n+ keyMap map[device.MultiDeviceKey]*overrideInfo `state:\"nosave\"`\n- // pathMap links the sockets to their paths.\n+ // pathMap links the sockets/pipes to their paths.\n// It is filled before saving from the direntMap and is stored upon save.\n// Upon restore, this map is used to re-populate the keyMap.\n- pathMap map[transport.BoundEndpoint]string\n+ pathMap map[*overrideInfo]string\n+}\n+\n+// addBoundEndpoint adds the bound endpoint to the map.\n+// A reference is taken on the dirent argument.\n+//\n+// Precondition: maps must have been locked with 'lock'.\n+func (e *overrideMaps) addBoundEndpoint(key device.MultiDeviceKey, d *fs.Dirent, ep transport.BoundEndpoint) {\n+ d.IncRef()\n+ e.keyMap[key] = &overrideInfo{dirent: d, endpoint: ep}\n}\n-// add adds the endpoint to the maps.\n+// addPipe adds the pipe inode to the map.\n// A reference is taken on the dirent argument.\n//\n// Precondition: maps must have been locked with 'lock'.\n-func (e *endpointMaps) add(key device.MultiDeviceKey, d *fs.Dirent, ep transport.BoundEndpoint) {\n- e.keyMap[key] = ep\n+func (e *overrideMaps) addPipe(key device.MultiDeviceKey, d *fs.Dirent, inode *fs.Inode) {\nd.IncRef()\n- e.direntMap[ep] = d\n+ e.keyMap[key] = &overrideInfo{dirent: d, inode: inode}\n}\n// remove deletes the key from the maps.\n//\n// Precondition: maps must have been locked with 'lock'.\n-func (e *endpointMaps) remove(key device.MultiDeviceKey) {\n- endpoint := e.get(key)\n+func (e *overrideMaps) remove(key device.MultiDeviceKey) {\n+ endpoint := e.keyMap[key]\ndelete(e.keyMap, key)\n-\n- d := e.direntMap[endpoint]\n- d.DecRef()\n- delete(e.direntMap, endpoint)\n+ endpoint.dirent.DecRef()\n}\n// lock blocks other addition and removal operations from happening while\n// the backing file is being created or deleted. Returns a function that unlocks\n// the endpoint map.\n-func (e *endpointMaps) lock() func() {\n+func (e *overrideMaps) lock() func() {\ne.mu.Lock()\nreturn func() { e.mu.Unlock() }\n}\n-// get returns the endpoint mapped to the given key.\n+// getBoundEndpoint returns the bound endpoint mapped to the given key.\n+//\n+// Precondition: maps must have been locked.\n+func (e *overrideMaps) getBoundEndpoint(key device.MultiDeviceKey) transport.BoundEndpoint {\n+ if v := e.keyMap[key]; v != nil {\n+ return v.endpoint\n+ }\n+ return nil\n+}\n+\n+// getPipe returns the pipe inode mapped to the given key.\n//\n-// Precondition: maps must have been locked for reading.\n-func (e *endpointMaps) get(key device.MultiDeviceKey) transport.BoundEndpoint {\n- return e.keyMap[key]\n+// Precondition: maps must have been locked.\n+func (e *overrideMaps) getPipe(key device.MultiDeviceKey) *fs.Inode {\n+ if v := e.keyMap[key]; v != nil {\n+ return v.inode\n+ }\n+ return nil\n+}\n+\n+// getType returns the inode type if there is a corresponding endpoint for the\n+// given key. Returns false otherwise.\n+func (e *overrideMaps) getType(key device.MultiDeviceKey) (fs.InodeType, bool) {\n+ e.mu.Lock()\n+ v := e.keyMap[key]\n+ e.mu.Unlock()\n+\n+ if v != nil {\n+ return v.inodeType(), true\n+ }\n+ return 0, false\n}\n// session holds state for each 9p session established during sys_mount.\n@@ -137,16 +184,16 @@ type session struct {\n// mounter is the EUID/EGID that mounted this file system.\nmounter fs.FileOwner `state:\"wait\"`\n- // endpoints is used to map inodes that represent socket files to their\n- // corresponding endpoint. Socket files are created as regular files in the\n- // gofer and their presence in this map indicate that they should indeed be\n- // socket files. This allows unix domain sockets to be used with paths that\n- // belong to a gofer.\n+ // overrides is used to map inodes that represent socket/pipes files to their\n+ // corresponding endpoint/iops. These files are created as regular files in\n+ // the gofer and their presence in this map indicate that they should indeed\n+ // be socket/pipe files. This allows unix domain sockets and named pipes to\n+ // be used with paths that belong to a gofer.\n//\n// TODO(gvisor.dev/issue/1200): there are few possible races with someone\n// stat'ing the file and another deleting it concurrently, where the file\n// will not be reported as socket file.\n- endpoints *endpointMaps `state:\"wait\"`\n+ overrides *overrideMaps `state:\"wait\"`\n}\n// Destroy tears down the session.\n@@ -179,15 +226,21 @@ func (s *session) SaveInodeMapping(inode *fs.Inode, path string) {\n// This is very unintuitive. We *CANNOT* trust the inode's StableAttrs,\n// because overlay copyUp may have changed them out from under us.\n// So much for \"immutable\".\n- sattr := inode.InodeOperations.(*inodeOperations).fileState.sattr\n- s.inodeMappings[sattr.InodeID] = path\n+ switch iops := inode.InodeOperations.(type) {\n+ case *inodeOperations:\n+ s.inodeMappings[iops.fileState.sattr.InodeID] = path\n+ case *fifo:\n+ s.inodeMappings[iops.fileIops.fileState.sattr.InodeID] = path\n+ default:\n+ panic(fmt.Sprintf(\"Invalid type: %T\", iops))\n+ }\n}\n-// newInodeOperations creates a new 9p fs.InodeOperations backed by a p9.File and attributes\n-// (p9.QID, p9.AttrMask, p9.Attr).\n+// newInodeOperations creates a new 9p fs.InodeOperations backed by a p9.File\n+// and attributes (p9.QID, p9.AttrMask, p9.Attr).\n//\n// Endpoints lock must not be held if socket == false.\n-func newInodeOperations(ctx context.Context, s *session, file contextFile, qid p9.QID, valid p9.AttrMask, attr p9.Attr, socket bool) (fs.StableAttr, *inodeOperations) {\n+func newInodeOperations(ctx context.Context, s *session, file contextFile, qid p9.QID, valid p9.AttrMask, attr p9.Attr) (fs.StableAttr, *inodeOperations) {\ndeviceKey := device.MultiDeviceKey{\nDevice: attr.RDev,\nSecondaryDevice: s.connID,\n@@ -201,17 +254,11 @@ func newInodeOperations(ctx context.Context, s *session, file contextFile, qid p\nBlockSize: bsize(attr),\n}\n- if s.endpoints != nil {\n- if socket {\n- sattr.Type = fs.Socket\n- } else {\n- // If unix sockets are allowed on this filesystem, check if this file is\n- // supposed to be a socket file.\n- unlock := s.endpoints.lock()\n- if s.endpoints.get(deviceKey) != nil {\n- sattr.Type = fs.Socket\n- }\n- unlock()\n+ if s.overrides != nil && sattr.Type == fs.RegularFile {\n+ // If overrides are allowed on this filesystem, check if this file is\n+ // supposed to be of a different type, e.g. socket.\n+ if t, ok := s.overrides.getType(deviceKey); ok {\n+ sattr.Type = t\n}\n}\n@@ -267,7 +314,7 @@ func Root(ctx context.Context, dev string, filesystem fs.Filesystem, superBlockF\ns.EnableLeakCheck(\"gofer.session\")\nif o.privateunixsocket {\n- s.endpoints = newEndpointMaps()\n+ s.overrides = newOverrideMaps()\n}\n// Construct the MountSource with the session and superBlockFlags.\n@@ -305,26 +352,24 @@ func Root(ctx context.Context, dev string, filesystem fs.Filesystem, superBlockF\nreturn nil, err\n}\n- sattr, iops := newInodeOperations(ctx, &s, s.attach, qid, valid, attr, false)\n+ sattr, iops := newInodeOperations(ctx, &s, s.attach, qid, valid, attr)\nreturn fs.NewInode(ctx, iops, m, sattr), nil\n}\n-// newEndpointMaps creates a new endpointMaps.\n-func newEndpointMaps() *endpointMaps {\n- return &endpointMaps{\n- direntMap: make(map[transport.BoundEndpoint]*fs.Dirent),\n- keyMap: make(map[device.MultiDeviceKey]transport.BoundEndpoint),\n- pathMap: make(map[transport.BoundEndpoint]string),\n+// newOverrideMaps creates a new overrideMaps.\n+func newOverrideMaps() *overrideMaps {\n+ return &overrideMaps{\n+ keyMap: make(map[device.MultiDeviceKey]*overrideInfo),\n+ pathMap: make(map[*overrideInfo]string),\n}\n}\n-// fillKeyMap populates key and dirent maps upon restore from saved\n-// pathmap.\n+// fillKeyMap populates key and dirent maps upon restore from saved pathmap.\nfunc (s *session) fillKeyMap(ctx context.Context) error {\n- unlock := s.endpoints.lock()\n+ unlock := s.overrides.lock()\ndefer unlock()\n- for ep, dirPath := range s.endpoints.pathMap {\n+ for ep, dirPath := range s.overrides.pathMap {\n_, file, err := s.attach.walk(ctx, splitAbsolutePath(dirPath))\nif err != nil {\nreturn fmt.Errorf(\"error filling endpointmaps, failed to walk to %q: %v\", dirPath, err)\n@@ -341,25 +386,25 @@ func (s *session) fillKeyMap(ctx context.Context) error {\nInode: qid.Path,\n}\n- s.endpoints.keyMap[key] = ep\n+ s.overrides.keyMap[key] = ep\n}\nreturn nil\n}\n-// fillPathMap populates paths for endpoints from dirents in direntMap\n+// fillPathMap populates paths for overrides from dirents in direntMap\n// before save.\nfunc (s *session) fillPathMap() error {\n- unlock := s.endpoints.lock()\n+ unlock := s.overrides.lock()\ndefer unlock()\n- for ep, dir := range s.endpoints.direntMap {\n- mountRoot := dir.MountRoot()\n+ for _, endpoint := range s.overrides.keyMap {\n+ mountRoot := endpoint.dirent.MountRoot()\ndefer mountRoot.DecRef()\n- dirPath, _ := dir.FullName(mountRoot)\n+ dirPath, _ := endpoint.dirent.FullName(mountRoot)\nif dirPath == \"\" {\nreturn fmt.Errorf(\"error getting path from dirent\")\n}\n- s.endpoints.pathMap[ep] = dirPath\n+ s.overrides.pathMap[endpoint] = dirPath\n}\nreturn nil\n}\n@@ -368,7 +413,7 @@ func (s *session) fillPathMap() error {\nfunc (s *session) restoreEndpointMaps(ctx context.Context) error {\n// When restoring, only need to create the keyMap because the dirent and path\n// maps got stored through the save.\n- s.endpoints.keyMap = make(map[device.MultiDeviceKey]transport.BoundEndpoint)\n+ s.overrides.keyMap = make(map[device.MultiDeviceKey]*overrideInfo)\nif err := s.fillKeyMap(ctx); err != nil {\nreturn fmt.Errorf(\"failed to insert sockets into endpoint map: %v\", err)\n}\n@@ -376,6 +421,6 @@ func (s *session) restoreEndpointMaps(ctx context.Context) error {\n// Re-create pathMap because it can no longer be trusted as socket paths can\n// change while process continues to run. Empty pathMap will be re-filled upon\n// next save.\n- s.endpoints.pathMap = make(map[transport.BoundEndpoint]string)\n+ s.overrides.pathMap = make(map[*overrideInfo]string)\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/session_state.go", "new_path": "pkg/sentry/fs/gofer/session_state.go", "diff": "@@ -25,9 +25,9 @@ import (\n// beforeSave is invoked by stateify.\nfunc (s *session) beforeSave() {\n- if s.endpoints != nil {\n+ if s.overrides != nil {\nif err := s.fillPathMap(); err != nil {\n- panic(\"failed to save paths to endpoint map before saving\" + err.Error())\n+ panic(\"failed to save paths to override map before saving\" + err.Error())\n}\n}\n}\n@@ -74,10 +74,10 @@ func (s *session) afterLoad() {\npanic(fmt.Sprintf(\"new attach name %v, want %v\", opts.aname, s.aname))\n}\n- // Check if endpointMaps exist when uds sockets are enabled\n- // (only pathmap will actualy have been saved).\n- if opts.privateunixsocket != (s.endpoints != nil) {\n- panic(fmt.Sprintf(\"new privateunixsocket option %v, want %v\", opts.privateunixsocket, s.endpoints != nil))\n+ // Check if overrideMaps exist when uds sockets are enabled (only pathmaps\n+ // will actually have been saved).\n+ if opts.privateunixsocket != (s.overrides != nil) {\n+ panic(fmt.Sprintf(\"new privateunixsocket option %v, want %v\", opts.privateunixsocket, s.overrides != nil))\n}\nif args.Flags != s.superBlockFlags {\npanic(fmt.Sprintf(\"new mount flags %v, want %v\", args.Flags, s.superBlockFlags))\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/socket.go", "new_path": "pkg/sentry/fs/gofer/socket.go", "diff": "@@ -32,15 +32,15 @@ func (i *inodeOperations) BoundEndpoint(inode *fs.Inode, path string) transport.\nreturn nil\n}\n- if i.session().endpoints != nil {\n- unlock := i.session().endpoints.lock()\n+ if i.session().overrides != nil {\n+ unlock := i.session().overrides.lock()\ndefer unlock()\n- ep := i.session().endpoints.get(i.fileState.key)\n+ ep := i.session().overrides.getBoundEndpoint(i.fileState.key)\nif ep != nil {\nreturn ep\n}\n- // Not found in endpoints map, it may be a gofer backed unix socket...\n+ // Not found in overrides map, it may be a gofer backed unix socket...\n}\ninode.IncRef()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -225,7 +225,6 @@ syscall_test(\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:mknod_test\",\n- use_tmpfs = True, # mknod is not supported over gofer.\n)\nsyscall_test(\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for sentry internal pipe for gofer mounts Internal pipes are supported similarly to how internal UDS is done. It is also controlled by the same flag. Fixes #1102 PiperOrigin-RevId: 293150045
259,992
04.02.2020 11:47:41
28,800
dcffddf0cae026411e7e678744a1e39dc2b513cf
Remove argument from vfs.MountNamespace.DecRef() Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs.go", "new_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs.go", "diff": "@@ -86,7 +86,7 @@ func NewAccessor(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth\n// Release must be called when a is no longer in use.\nfunc (a *Accessor) Release() {\na.root.DecRef()\n- a.mntns.DecRef(a.vfsObj)\n+ a.mntns.DecRef()\n}\n// accessorContext implements context.Context by extending an existing\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs_test.go", "new_path": "pkg/sentry/fsimpl/devtmpfs/devtmpfs_test.go", "diff": "@@ -45,7 +45,7 @@ func TestDevtmpfs(t *testing.T) {\nif err != nil {\nt.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n}\n- defer mntns.DecRef(vfsObj)\n+ defer mntns.DecRef()\nroot := mntns.Root()\ndefer root.DecRef()\ndevpop := vfs.PathOperation{\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/testutil/testutil.go", "new_path": "pkg/sentry/fsimpl/testutil/testutil.go", "diff": "@@ -98,7 +98,7 @@ func (s *System) WithTemporaryContext(ctx context.Context) *System {\n// Destroy release resources associated with a test system.\nfunc (s *System) Destroy() {\ns.Root.DecRef()\n- s.mns.DecRef(s.VFS) // Reference on mns passed to NewSystem.\n+ s.mns.DecRef() // Reference on mns passed to NewSystem.\n}\n// ReadToEnd reads the contents of fd until EOF to a string.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go", "new_path": "pkg/sentry/fsimpl/tmpfs/benchmark_test.go", "diff": "@@ -183,7 +183,7 @@ func BenchmarkVFS2MemfsStat(b *testing.B) {\nif err != nil {\nb.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n}\n- defer mntns.DecRef(vfsObj)\n+ defer mntns.DecRef()\nvar filePathBuilder strings.Builder\nfilePathBuilder.WriteByte('/')\n@@ -374,7 +374,7 @@ func BenchmarkVFS2MemfsMountStat(b *testing.B) {\nif err != nil {\nb.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n}\n- defer mntns.DecRef(vfsObj)\n+ defer mntns.DecRef()\nvar filePathBuilder strings.Builder\nfilePathBuilder.WriteByte('/')\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file_test.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file_test.go", "diff": "@@ -51,7 +51,7 @@ func newTmpfsRoot(ctx context.Context) (*vfs.VirtualFilesystem, vfs.VirtualDentr\nroot := mntns.Root()\nreturn vfsObj, root, func() {\nroot.DecRef()\n- mntns.DecRef(vfsObj)\n+ mntns.DecRef()\n}, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -423,7 +423,8 @@ func (mntns *MountNamespace) IncRef() {\n}\n// DecRef decrements mntns' reference count.\n-func (mntns *MountNamespace) DecRef(vfs *VirtualFilesystem) {\n+func (mntns *MountNamespace) DecRef() {\n+ vfs := mntns.root.fs.VirtualFilesystem()\nif refs := atomic.AddInt64(&mntns.refs, -1); refs == 0 {\nvfs.mountMu.Lock()\nvfs.mounts.seq.BeginWrite()\n" } ]
Go
Apache License 2.0
google/gvisor
Remove argument from vfs.MountNamespace.DecRef() Updates #1035 PiperOrigin-RevId: 293194631
259,858
04.02.2020 12:39:58
28,800
f5072caaf85b9f067d737a874804c04e2b9039b8
Fix safecopy test. This is failing in Go1.14 due to new checkptr constraints. This version should avoid hitting this constraints by doing "dangerous" pointer math less dangerously?
[ { "change_type": "MODIFY", "old_path": "pkg/safecopy/safecopy_test.go", "new_path": "pkg/safecopy/safecopy_test.go", "diff": "@@ -138,10 +138,14 @@ func TestSwapUint32Success(t *testing.T) {\nfunc TestSwapUint32AlignmentError(t *testing.T) {\n// Test that SwapUint32 returns an AlignmentError when passed an unaligned\n// address.\n- data := new(struct{ val uint64 })\n- addr := uintptr(unsafe.Pointer(&data.val)) + 1\n- want := AlignmentError{Addr: addr, Alignment: 4}\n- if _, err := SwapUint32(unsafe.Pointer(addr), 1); err != want {\n+ data := make([]byte, 8) // 2 * sizeof(uint32).\n+ alignedIndex := uintptr(0)\n+ if offset := uintptr(unsafe.Pointer(&data[0])) % 4; offset != 0 {\n+ alignedIndex = 4 - offset\n+ }\n+ ptr := unsafe.Pointer(&data[alignedIndex+1])\n+ want := AlignmentError{Addr: uintptr(ptr), Alignment: 4}\n+ if _, err := SwapUint32(ptr, 1); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n}\n}\n@@ -171,10 +175,14 @@ func TestSwapUint64Success(t *testing.T) {\nfunc TestSwapUint64AlignmentError(t *testing.T) {\n// Test that SwapUint64 returns an AlignmentError when passed an unaligned\n// address.\n- data := new(struct{ val1, val2 uint64 })\n- addr := uintptr(unsafe.Pointer(&data.val1)) + 1\n- want := AlignmentError{Addr: addr, Alignment: 8}\n- if _, err := SwapUint64(unsafe.Pointer(addr), 1); err != want {\n+ data := make([]byte, 16) // 2 * sizeof(uint64).\n+ alignedIndex := uintptr(0)\n+ if offset := uintptr(unsafe.Pointer(&data[0])) % 8; offset != 0 {\n+ alignedIndex = 8 - offset\n+ }\n+ ptr := unsafe.Pointer(&data[alignedIndex+1])\n+ want := AlignmentError{Addr: uintptr(ptr), Alignment: 8}\n+ if _, err := SwapUint64(ptr, 1); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n}\n}\n@@ -201,10 +209,14 @@ func TestCompareAndSwapUint32Success(t *testing.T) {\nfunc TestCompareAndSwapUint32AlignmentError(t *testing.T) {\n// Test that CompareAndSwapUint32 returns an AlignmentError when passed an\n// unaligned address.\n- data := new(struct{ val uint64 })\n- addr := uintptr(unsafe.Pointer(&data.val)) + 1\n- want := AlignmentError{Addr: addr, Alignment: 4}\n- if _, err := CompareAndSwapUint32(unsafe.Pointer(addr), 0, 1); err != want {\n+ data := make([]byte, 8) // 2 * sizeof(uint32).\n+ alignedIndex := uintptr(0)\n+ if offset := uintptr(unsafe.Pointer(&data[0])) % 4; offset != 0 {\n+ alignedIndex = 4 - offset\n+ }\n+ ptr := unsafe.Pointer(&data[alignedIndex+1])\n+ want := AlignmentError{Addr: uintptr(ptr), Alignment: 4}\n+ if _, err := CompareAndSwapUint32(ptr, 0, 1); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n}\n}\n@@ -252,8 +264,8 @@ func TestCopyInSegvError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- src := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ src := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\ndst := randBuf(pageSize)\nn, err := CopyIn(dst, src)\nif n != bytesBeforeFault {\n@@ -276,8 +288,8 @@ func TestCopyInBusError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGBUS\", bytesBeforeFault), func(t *testing.T) {\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- src := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ src := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\ndst := randBuf(pageSize)\nn, err := CopyIn(dst, src)\nif n != bytesBeforeFault {\n@@ -300,8 +312,8 @@ func TestCopyOutSegvError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nsrc := randBuf(pageSize)\nn, err := CopyOut(dst, src)\nif n != bytesBeforeFault {\n@@ -324,8 +336,8 @@ func TestCopyOutBusError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nsrc := randBuf(pageSize)\nn, err := CopyOut(dst, src)\nif n != bytesBeforeFault {\n@@ -348,8 +360,8 @@ func TestCopySourceSegvError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- src := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ src := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\ndst := randBuf(pageSize)\nn, err := Copy(unsafe.Pointer(&dst[0]), src, pageSize)\nif n != uintptr(bytesBeforeFault) {\n@@ -372,8 +384,8 @@ func TestCopySourceBusError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGBUS\", bytesBeforeFault), func(t *testing.T) {\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- src := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ src := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\ndst := randBuf(pageSize)\nn, err := Copy(unsafe.Pointer(&dst[0]), src, pageSize)\nif n != uintptr(bytesBeforeFault) {\n@@ -396,8 +408,8 @@ func TestCopyDestinationSegvError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nsrc := randBuf(pageSize)\nn, err := Copy(dst, unsafe.Pointer(&src[0]), pageSize)\nif n != uintptr(bytesBeforeFault) {\n@@ -420,8 +432,8 @@ func TestCopyDestinationBusError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting copy %d bytes before SIGBUS\", bytesBeforeFault), func(t *testing.T) {\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nsrc := randBuf(pageSize)\nn, err := Copy(dst, unsafe.Pointer(&src[0]), pageSize)\nif n != uintptr(bytesBeforeFault) {\n@@ -444,8 +456,8 @@ func TestZeroOutSegvError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting write %d bytes before SIGSEGV\", bytesBeforeFault), func(t *testing.T) {\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nn, err := ZeroOut(dst, pageSize)\nif n != uintptr(bytesBeforeFault) {\nt.Errorf(\"Unexpected write length: got %v, want %v\", n, bytesBeforeFault)\n@@ -467,8 +479,8 @@ func TestZeroOutBusError(t *testing.T) {\nfor bytesBeforeFault := 0; bytesBeforeFault <= 2*maxRegisterSize; bytesBeforeFault++ {\nt.Run(fmt.Sprintf(\"starting write %d bytes before SIGBUS\", bytesBeforeFault), func(t *testing.T) {\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n- dst := unsafe.Pointer(secondPage - uintptr(bytesBeforeFault))\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n+ dst := unsafe.Pointer(&mapping[pageSize-bytesBeforeFault])\nn, err := ZeroOut(dst, pageSize)\nif n != uintptr(bytesBeforeFault) {\nt.Errorf(\"Unexpected write length: got %v, want %v\", n, bytesBeforeFault)\n@@ -488,7 +500,7 @@ func TestSwapUint32SegvError(t *testing.T) {\n// Test that SwapUint32 returns a SegvError when reaching a page that\n// signals SIGSEGV.\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := SwapUint32(unsafe.Pointer(secondPage), 1)\nif want := (SegvError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n@@ -500,7 +512,7 @@ func TestSwapUint32BusError(t *testing.T) {\n// Test that SwapUint32 returns a BusError when reaching a page that\n// signals SIGBUS.\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := SwapUint32(unsafe.Pointer(secondPage), 1)\nif want := (BusError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n@@ -512,7 +524,7 @@ func TestSwapUint64SegvError(t *testing.T) {\n// Test that SwapUint64 returns a SegvError when reaching a page that\n// signals SIGSEGV.\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := SwapUint64(unsafe.Pointer(secondPage), 1)\nif want := (SegvError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n@@ -524,7 +536,7 @@ func TestSwapUint64BusError(t *testing.T) {\n// Test that SwapUint64 returns a BusError when reaching a page that\n// signals SIGBUS.\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := SwapUint64(unsafe.Pointer(secondPage), 1)\nif want := (BusError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n@@ -536,7 +548,7 @@ func TestCompareAndSwapUint32SegvError(t *testing.T) {\n// Test that CompareAndSwapUint32 returns a SegvError when reaching a page\n// that signals SIGSEGV.\nwithSegvErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := CompareAndSwapUint32(unsafe.Pointer(secondPage), 0, 1)\nif want := (SegvError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n@@ -548,7 +560,7 @@ func TestCompareAndSwapUint32BusError(t *testing.T) {\n// Test that CompareAndSwapUint32 returns a BusError when reaching a page\n// that signals SIGBUS.\nwithBusErrorTestMapping(t, func(mapping []byte) {\n- secondPage := uintptr(unsafe.Pointer(&mapping[0])) + pageSize\n+ secondPage := uintptr(unsafe.Pointer(&mapping[pageSize]))\n_, err := CompareAndSwapUint32(unsafe.Pointer(secondPage), 0, 1)\nif want := (BusError{secondPage}); err != want {\nt.Errorf(\"Unexpected error: got %v, want %v\", err, want)\n" }, { "change_type": "MODIFY", "old_path": "pkg/safecopy/safecopy_unsafe.go", "new_path": "pkg/safecopy/safecopy_unsafe.go", "diff": "@@ -16,6 +16,7 @@ package safecopy\nimport (\n\"fmt\"\n+ \"runtime\"\n\"syscall\"\n\"unsafe\"\n)\n@@ -35,7 +36,7 @@ const maxRegisterSize = 16\n// successfully copied.\n//\n//go:noescape\n-func memcpy(dst, src unsafe.Pointer, n uintptr) (fault unsafe.Pointer, sig int32)\n+func memcpy(dst, src uintptr, n uintptr) (fault uintptr, sig int32)\n// memclr sets the n bytes following ptr to zeroes. If a SIGSEGV or SIGBUS\n// signal is received during the write, it returns the address that caused the\n@@ -47,7 +48,7 @@ func memcpy(dst, src unsafe.Pointer, n uintptr) (fault unsafe.Pointer, sig int32\n// successfully written.\n//\n//go:noescape\n-func memclr(ptr unsafe.Pointer, n uintptr) (fault unsafe.Pointer, sig int32)\n+func memclr(ptr uintptr, n uintptr) (fault uintptr, sig int32)\n// swapUint32 atomically stores new into *ptr and returns (the previous *ptr\n// value, 0). If a SIGSEGV or SIGBUS signal is received during the swap, the\n@@ -90,29 +91,35 @@ func loadUint32(ptr unsafe.Pointer) (val uint32, sig int32)\n// CopyIn copies len(dst) bytes from src to dst. It returns the number of bytes\n// copied and an error if SIGSEGV or SIGBUS is received while reading from src.\nfunc CopyIn(dst []byte, src unsafe.Pointer) (int, error) {\n+ n, err := copyIn(dst, uintptr(src))\n+ runtime.KeepAlive(src)\n+ return n, err\n+}\n+\n+// copyIn is the underlying definition for CopyIn.\n+func copyIn(dst []byte, src uintptr) (int, error) {\ntoCopy := uintptr(len(dst))\nif len(dst) == 0 {\nreturn 0, nil\n}\n- fault, sig := memcpy(unsafe.Pointer(&dst[0]), src, toCopy)\n+ fault, sig := memcpy(uintptr(unsafe.Pointer(&dst[0])), src, toCopy)\nif sig == 0 {\nreturn len(dst), nil\n}\n- faultN, srcN := uintptr(fault), uintptr(src)\n- if faultN < srcN || faultN >= srcN+toCopy {\n- panic(fmt.Sprintf(\"CopyIn raised signal %d at %#x, which is outside source [%#x, %#x)\", sig, faultN, srcN, srcN+toCopy))\n+ if fault < src || fault >= src+toCopy {\n+ panic(fmt.Sprintf(\"CopyIn raised signal %d at %#x, which is outside source [%#x, %#x)\", sig, fault, src, src+toCopy))\n}\n// memcpy might have ended the copy up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to copy up to the fault.\nvar done int\n- if faultN-srcN > maxRegisterSize {\n- done = int(faultN - srcN - maxRegisterSize)\n+ if fault-src > maxRegisterSize {\n+ done = int(fault - src - maxRegisterSize)\n}\n- n, err := CopyIn(dst[done:int(faultN-srcN)], unsafe.Pointer(srcN+uintptr(done)))\n+ n, err := copyIn(dst[done:int(fault-src)], src+uintptr(done))\ndone += n\nif err != nil {\nreturn done, err\n@@ -124,29 +131,35 @@ func CopyIn(dst []byte, src unsafe.Pointer) (int, error) {\n// bytes done and an error if SIGSEGV or SIGBUS is received while writing to\n// dst.\nfunc CopyOut(dst unsafe.Pointer, src []byte) (int, error) {\n+ n, err := copyOut(uintptr(dst), src)\n+ runtime.KeepAlive(dst)\n+ return n, err\n+}\n+\n+// copyOut is the underlying definition for CopyOut.\n+func copyOut(dst uintptr, src []byte) (int, error) {\ntoCopy := uintptr(len(src))\nif toCopy == 0 {\nreturn 0, nil\n}\n- fault, sig := memcpy(dst, unsafe.Pointer(&src[0]), toCopy)\n+ fault, sig := memcpy(dst, uintptr(unsafe.Pointer(&src[0])), toCopy)\nif sig == 0 {\nreturn len(src), nil\n}\n- faultN, dstN := uintptr(fault), uintptr(dst)\n- if faultN < dstN || faultN >= dstN+toCopy {\n- panic(fmt.Sprintf(\"CopyOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, faultN, dstN, dstN+toCopy))\n+ if fault < dst || fault >= dst+toCopy {\n+ panic(fmt.Sprintf(\"CopyOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, fault, dst, dst+toCopy))\n}\n// memcpy might have ended the copy up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to copy up to the fault.\nvar done int\n- if faultN-dstN > maxRegisterSize {\n- done = int(faultN - dstN - maxRegisterSize)\n+ if fault-dst > maxRegisterSize {\n+ done = int(fault - dst - maxRegisterSize)\n}\n- n, err := CopyOut(unsafe.Pointer(dstN+uintptr(done)), src[done:int(faultN-dstN)])\n+ n, err := copyOut(dst+uintptr(done), src[done:int(fault-dst)])\ndone += n\nif err != nil {\nreturn done, err\n@@ -161,6 +174,14 @@ func CopyOut(dst unsafe.Pointer, src []byte) (int, error) {\n// Data is copied in order; if [src, src+toCopy) and [dst, dst+toCopy) overlap,\n// the resulting contents of dst are unspecified.\nfunc Copy(dst, src unsafe.Pointer, toCopy uintptr) (uintptr, error) {\n+ n, err := copyN(uintptr(dst), uintptr(src), toCopy)\n+ runtime.KeepAlive(dst)\n+ runtime.KeepAlive(src)\n+ return n, err\n+}\n+\n+// copyN is the underlying definition for Copy.\n+func copyN(dst, src uintptr, toCopy uintptr) (uintptr, error) {\nif toCopy == 0 {\nreturn 0, nil\n}\n@@ -171,17 +192,16 @@ func Copy(dst, src unsafe.Pointer, toCopy uintptr) (uintptr, error) {\n}\n// Did the fault occur while reading from src or writing to dst?\n- faultN, srcN, dstN := uintptr(fault), uintptr(src), uintptr(dst)\nfaultAfterSrc := ^uintptr(0)\n- if faultN >= srcN {\n- faultAfterSrc = faultN - srcN\n+ if fault >= src {\n+ faultAfterSrc = fault - src\n}\nfaultAfterDst := ^uintptr(0)\n- if faultN >= dstN {\n- faultAfterDst = faultN - dstN\n+ if fault >= dst {\n+ faultAfterDst = fault - dst\n}\nif faultAfterSrc >= toCopy && faultAfterDst >= toCopy {\n- panic(fmt.Sprintf(\"Copy raised signal %d at %#x, which is outside source [%#x, %#x) and destination [%#x, %#x)\", sig, faultN, srcN, srcN+toCopy, dstN, dstN+toCopy))\n+ panic(fmt.Sprintf(\"Copy raised signal %d at %#x, which is outside source [%#x, %#x) and destination [%#x, %#x)\", sig, fault, src, src+toCopy, dst, dst+toCopy))\n}\nfaultedAfter := faultAfterSrc\nif faultedAfter > faultAfterDst {\n@@ -195,7 +215,7 @@ func Copy(dst, src unsafe.Pointer, toCopy uintptr) (uintptr, error) {\nif faultedAfter > maxRegisterSize {\ndone = faultedAfter - maxRegisterSize\n}\n- n, err := Copy(unsafe.Pointer(dstN+done), unsafe.Pointer(srcN+done), faultedAfter-done)\n+ n, err := copyN(dst+done, src+done, faultedAfter-done)\ndone += n\nif err != nil {\nreturn done, err\n@@ -206,6 +226,13 @@ func Copy(dst, src unsafe.Pointer, toCopy uintptr) (uintptr, error) {\n// ZeroOut writes toZero zero bytes to dst. It returns the number of bytes\n// written and an error if SIGSEGV or SIGBUS is received while writing to dst.\nfunc ZeroOut(dst unsafe.Pointer, toZero uintptr) (uintptr, error) {\n+ n, err := zeroOut(uintptr(dst), toZero)\n+ runtime.KeepAlive(dst)\n+ return n, err\n+}\n+\n+// zeroOut is the underlying definition for ZeroOut.\n+func zeroOut(dst uintptr, toZero uintptr) (uintptr, error) {\nif toZero == 0 {\nreturn 0, nil\n}\n@@ -215,19 +242,18 @@ func ZeroOut(dst unsafe.Pointer, toZero uintptr) (uintptr, error) {\nreturn toZero, nil\n}\n- faultN, dstN := uintptr(fault), uintptr(dst)\n- if faultN < dstN || faultN >= dstN+toZero {\n- panic(fmt.Sprintf(\"ZeroOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, faultN, dstN, dstN+toZero))\n+ if fault < dst || fault >= dst+toZero {\n+ panic(fmt.Sprintf(\"ZeroOut raised signal %d at %#x, which is outside destination [%#x, %#x)\", sig, fault, dst, dst+toZero))\n}\n// memclr might have ended the write up to maxRegisterSize bytes before\n// fault, if an instruction caused a memory access that straddled two\n// pages, and the second one faulted. Try to write up to the fault.\nvar done uintptr\n- if faultN-dstN > maxRegisterSize {\n- done = faultN - dstN - maxRegisterSize\n+ if fault-dst > maxRegisterSize {\n+ done = fault - dst - maxRegisterSize\n}\n- n, err := ZeroOut(unsafe.Pointer(dstN+done), faultN-dstN-done)\n+ n, err := zeroOut(dst+done, fault-dst-done)\ndone += n\nif err != nil {\nreturn done, err\n@@ -243,7 +269,7 @@ func SwapUint32(ptr unsafe.Pointer, new uint32) (uint32, error) {\nreturn 0, AlignmentError{addr, 4}\n}\nold, sig := swapUint32(ptr, new)\n- return old, errorFromFaultSignal(ptr, sig)\n+ return old, errorFromFaultSignal(uintptr(ptr), sig)\n}\n// SwapUint64 is equivalent to sync/atomic.SwapUint64, except that it returns\n@@ -254,7 +280,7 @@ func SwapUint64(ptr unsafe.Pointer, new uint64) (uint64, error) {\nreturn 0, AlignmentError{addr, 8}\n}\nold, sig := swapUint64(ptr, new)\n- return old, errorFromFaultSignal(ptr, sig)\n+ return old, errorFromFaultSignal(uintptr(ptr), sig)\n}\n// CompareAndSwapUint32 is equivalent to atomicbitops.CompareAndSwapUint32,\n@@ -265,7 +291,7 @@ func CompareAndSwapUint32(ptr unsafe.Pointer, old, new uint32) (uint32, error) {\nreturn 0, AlignmentError{addr, 4}\n}\nprev, sig := compareAndSwapUint32(ptr, old, new)\n- return prev, errorFromFaultSignal(ptr, sig)\n+ return prev, errorFromFaultSignal(uintptr(ptr), sig)\n}\n// LoadUint32 is like sync/atomic.LoadUint32, but operates with user memory. It\n@@ -277,17 +303,17 @@ func LoadUint32(ptr unsafe.Pointer) (uint32, error) {\nreturn 0, AlignmentError{addr, 4}\n}\nval, sig := loadUint32(ptr)\n- return val, errorFromFaultSignal(ptr, sig)\n+ return val, errorFromFaultSignal(uintptr(ptr), sig)\n}\n-func errorFromFaultSignal(addr unsafe.Pointer, sig int32) error {\n+func errorFromFaultSignal(addr uintptr, sig int32) error {\nswitch sig {\ncase 0:\nreturn nil\ncase int32(syscall.SIGSEGV):\n- return SegvError{uintptr(addr)}\n+ return SegvError{addr}\ncase int32(syscall.SIGBUS):\n- return BusError{uintptr(addr)}\n+ return BusError{addr}\ndefault:\npanic(fmt.Sprintf(\"safecopy got unexpected signal %d at address %#x\", sig, addr))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix safecopy test. This is failing in Go1.14 due to new checkptr constraints. This version should avoid hitting this constraints by doing "dangerous" pointer math less dangerously? PiperOrigin-RevId: 293205764
259,881
04.02.2020 13:05:30
28,800
6823b5e244a5748032130574ae3a25a0a36bbbf5
timer_create(2) should return 0 on success The timer ID is copied out to the argument. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_timer.go", "new_path": "pkg/sentry/syscalls/linux/sys_timer.go", "diff": "@@ -146,7 +146,7 @@ func TimerCreate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.S\nreturn 0, nil, err\n}\n- return uintptr(id), nil, nil\n+ return 0, nil, nil\n}\n// TimerSettime implements linux syscall timer_settime(2).\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/timers.cc", "new_path": "test/syscalls/linux/timers.cc", "diff": "@@ -297,9 +297,13 @@ class IntervalTimer {\nPosixErrorOr<IntervalTimer> TimerCreate(clockid_t clockid,\nconst struct sigevent& sev) {\nint timerid;\n- if (syscall(SYS_timer_create, clockid, &sev, &timerid) < 0) {\n+ int ret = syscall(SYS_timer_create, clockid, &sev, &timerid);\n+ if (ret < 0) {\nreturn PosixError(errno, \"timer_create\");\n}\n+ if (ret > 0) {\n+ return PosixError(EINVAL, \"timer_create should never return positive\");\n+ }\nMaybeSave();\nreturn IntervalTimer(timerid);\n}\n@@ -317,6 +321,18 @@ TEST(IntervalTimerTest, IsInitiallyStopped) {\nEXPECT_EQ(0, its.it_value.tv_nsec);\n}\n+// Kernel can create multiple timers without issue.\n+//\n+// Regression test for gvisor.dev/issue/1738.\n+TEST(IntervalTimerTest, MultipleTimers) {\n+ struct sigevent sev = {};\n+ sev.sigev_notify = SIGEV_NONE;\n+ const auto timer1 =\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerCreate(CLOCK_MONOTONIC, sev));\n+ const auto timer2 =\n+ ASSERT_NO_ERRNO_AND_VALUE(TimerCreate(CLOCK_MONOTONIC, sev));\n+}\n+\nTEST(IntervalTimerTest, SingleShotSilent) {\nstruct sigevent sev = {};\nsev.sigev_notify = SIGEV_NONE;\n" } ]
Go
Apache License 2.0
google/gvisor
timer_create(2) should return 0 on success The timer ID is copied out to the argument. Fixes #1738 PiperOrigin-RevId: 293210801
259,992
04.02.2020 13:15:05
28,800
6d8bf405bc5e887247534172713bf7d2f5252734
Allow mlock in fsgofer system call filters Go 1.14 has a workaround for a Linux 5.2-5.4 bug which requires mlock'ing the g stack to prevent register corruption. We need to allow this syscall until it is removed from Go.
[ { "change_type": "MODIFY", "old_path": "runsc/fsgofer/filter/config.go", "new_path": "runsc/fsgofer/filter/config.go", "diff": "@@ -128,6 +128,18 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_MADVISE: {},\nunix.SYS_MEMFD_CREATE: {}, /// Used by flipcall.PacketWindowAllocator.Init().\nsyscall.SYS_MKDIRAT: {},\n+ // Used by the Go runtime as a temporarily workaround for a Linux\n+ // 5.2-5.4 bug.\n+ //\n+ // See src/runtime/os_linux_x86.go.\n+ //\n+ // TODO(b/148688965): Remove once this is gone from Go.\n+ syscall.SYS_MLOCK: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ seccomp.AllowValue(4096),\n+ },\n+ },\nsyscall.SYS_MMAP: []seccomp.Rule{\n{\nseccomp.AllowAny{},\n" } ]
Go
Apache License 2.0
google/gvisor
Allow mlock in fsgofer system call filters Go 1.14 has a workaround for a Linux 5.2-5.4 bug which requires mlock'ing the g stack to prevent register corruption. We need to allow this syscall until it is removed from Go. PiperOrigin-RevId: 293212935
259,858
04.02.2020 14:36:43
28,800
95ce8bb4c7ecb23e47e68c60b1de0b99ad8a856d
Automatically propagate tags for stateify and marshal. Note that files will need to be appropriately segmented in order for the mechanism to work, in suffixes implying special tags. This only needs to happen for cases where marshal or state structures are defined, which should be rare and mostly architecture specific.
[ { "change_type": "MODIFY", "old_path": "tools/build/defs.bzl", "new_path": "tools/build/defs.bzl", "diff": "@@ -8,6 +8,7 @@ load(\"@rules_pkg//:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\nload(\"@io_bazel_rules_docker//go:image.bzl\", _go_image = \"go_image\")\nload(\"@io_bazel_rules_docker//container:container.bzl\", _container_image = \"container_image\")\nload(\"@pydeps//:requirements.bzl\", _py_requirement = \"requirement\")\n+load(\"//tools/build:tags.bzl\", _go_suffixes = \"go_suffixes\")\ncontainer_image = _container_image\ncc_binary = _cc_binary\n@@ -18,6 +19,7 @@ cc_test = _cc_test\ncc_toolchain = \"@bazel_tools//tools/cpp:current_cc_toolchain\"\ngo_image = _go_image\ngo_embed_data = _go_embed_data\n+go_suffixes = _go_suffixes\ngtest = \"@com_google_googletest//:gtest\"\nloopback = \"//tools/build:loopback\"\nproto_library = native.proto_library\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/build/tags.bzl", "diff": "+\"\"\"List of special Go suffixes.\"\"\"\n+\n+go_suffixes = [\n+ \"_386\",\n+ \"_386_unsafe\",\n+ \"_amd64\",\n+ \"_amd64_unsafe\",\n+ \"_aarch64\",\n+ \"_aarch64_unsafe\",\n+ \"_arm\",\n+ \"_arm_unsafe\",\n+ \"_arm64\",\n+ \"_arm64_unsafe\",\n+ \"_mips\",\n+ \"_mips_unsafe\",\n+ \"_mipsle\",\n+ \"_mipsle_unsafe\",\n+ \"_mips64\",\n+ \"_mips64_unsafe\",\n+ \"_mips64le\",\n+ \"_mips64le_unsafe\",\n+ \"_ppc64\",\n+ \"_ppc64_unsafe\",\n+ \"_ppc64le\",\n+ \"_ppc64le_unsafe\",\n+ \"_riscv64\",\n+ \"_riscv64_unsafe\",\n+ \"_s390x\",\n+ \"_s390x_unsafe\",\n+ \"_sparc64\",\n+ \"_sparc64_unsafe\",\n+ \"_wasm\",\n+ \"_wasm_unsafe\",\n+ \"_linux\",\n+ \"_linux_unsafe\",\n+]\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -7,7 +7,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\n-load(\"//tools/build:defs.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n+load(\"//tools/build:defs.bzl\", \"go_suffixes\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n# Delegate directly.\ncc_binary = _cc_binary\n@@ -45,6 +45,34 @@ def go_binary(name, **kwargs):\n**kwargs\n)\n+def calculate_sets(srcs):\n+ \"\"\"Calculates special Go sets for templates.\n+\n+ Args:\n+ srcs: the full set of Go sources.\n+\n+ Returns:\n+ A dictionary of the form:\n+\n+ \"\": [src1.go, src2.go]\n+ \"suffix\": [src3suffix.go, src4suffix.go]\n+\n+ Note that suffix will typically start with '_'.\n+ \"\"\"\n+ result = dict()\n+ for file in srcs:\n+ if not file.endswith(\".go\"):\n+ continue\n+ target = \"\"\n+ for suffix in go_suffixes:\n+ if file.endswith(suffix + \".go\"):\n+ target = suffix\n+ if not target in result:\n+ result[target] = [file]\n+ else:\n+ result[target].append(file)\n+ return result\n+\ndef go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = False, **kwargs):\n\"\"\"Wraps the standard go_library and does stateification and marshalling.\n@@ -70,28 +98,35 @@ def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = F\nmarshal: whether marshal is enabled (default: false).\n**kwargs: standard go_library arguments.\n\"\"\"\n+ all_srcs = srcs\n+ all_deps = deps\nif stateify:\n# Only do stateification for non-state packages without manual autogen.\n+ # First, we need to segregate the input files via the special suffixes,\n+ # and calculate the final output set.\n+ state_sets = calculate_sets(srcs)\n+ for (suffix, srcs) in state_sets.items():\ngo_stateify(\n- name = name + \"_state_autogen\",\n- srcs = [src for src in srcs if src.endswith(\".go\")],\n+ name = name + suffix + \"_state_autogen\",\n+ srcs = srcs,\nimports = imports,\npackage = name,\n- arch = select_arch(),\n- out = name + \"_state_autogen.go\",\n+ out = name + suffix + \"_state_autogen.go\",\n)\n- all_srcs = srcs + [name + \"_state_autogen.go\"]\n- if \"//pkg/state\" not in deps:\n- all_deps = deps + [\"//pkg/state\"]\n- else:\n- all_deps = deps\n- else:\n- all_deps = deps\n- all_srcs = srcs\n+ all_srcs = all_srcs + [\n+ name + suffix + \"_state_autogen.go\"\n+ for suffix in state_sets.keys()\n+ ]\n+ if \"//pkg/state\" not in all_deps:\n+ all_deps = all_deps + [\"//pkg/state\"]\n+\nif marshal:\n+ # See above.\n+ marshal_sets = calculate_sets(srcs)\n+ for (suffix, srcs) in marshal_sets.items():\ngo_marshal(\n- name = name + \"_abi_autogen\",\n- srcs = [src for src in srcs if src.endswith(\".go\")],\n+ name = name + suffix + \"_abi_autogen\",\n+ srcs = srcs,\ndebug = False,\nimports = imports,\npackage = name,\n@@ -102,7 +137,10 @@ def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = F\nif not dep in all_deps\n]\nall_deps = all_deps + extra_deps\n- all_srcs = srcs + [name + \"_abi_autogen_unsafe.go\"]\n+ all_srcs = all_srcs + [\n+ name + suffix + \"_abi_autogen_unsafe.go\"\n+ for suffix in marshal_sets.keys()\n+ ]\n_go_library(\nname = name,\n@@ -115,10 +153,13 @@ def go_library(name, srcs, deps = [], imports = [], stateify = True, marshal = F\n# Ignore importpath for go_test.\nkwargs.pop(\"importpath\", None)\n+ # See above.\n+ marshal_sets = calculate_sets(srcs)\n+ for (suffix, srcs) in marshal_sets.items():\n_go_test(\n- name = name + \"_abi_autogen_test\",\n- srcs = [name + \"_abi_autogen_test.go\"],\n- library = \":\" + name,\n+ name = name + suffix + \"_abi_autogen_test\",\n+ srcs = [name + suffix + \"_abi_autogen_test.go\"],\n+ library = \":\" + name + suffix,\ndeps = marshal_test_deps,\n**kwargs\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/go_marshal/gomarshal/BUILD", "new_path": "tools/go_marshal/gomarshal/BUILD", "diff": "@@ -14,4 +14,5 @@ go_library(\nvisibility = [\n\"//:sandbox\",\n],\n+ deps = [\"//tools/tags\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/go_marshal/gomarshal/generator.go", "new_path": "tools/go_marshal/gomarshal/generator.go", "diff": "@@ -23,6 +23,9 @@ import (\n\"go/token\"\n\"os\"\n\"sort\"\n+ \"strings\"\n+\n+ \"gvisor.dev/gvisor/tools/tags\"\n)\nconst (\n@@ -104,6 +107,14 @@ func NewGenerator(srcs []string, out, outTest, pkg string, imports []string) (*G\nfunc (g *Generator) writeHeader() error {\nvar b sourceBuffer\nb.emit(\"// Automatically generated marshal implementation. See tools/go_marshal.\\n\\n\")\n+\n+ // Emit build tags.\n+ if t := tags.Aggregate(g.inputs); len(t) > 0 {\n+ b.emit(strings.Join(t.Lines(), \"\\n\"))\n+ b.emit(\"\\n\")\n+ }\n+\n+ // Package header.\nb.emit(\"package %s\\n\\n\", g.pkg)\nif err := b.write(g.output); err != nil {\nreturn err\n" }, { "change_type": "MODIFY", "old_path": "tools/go_stateify/BUILD", "new_path": "tools/go_stateify/BUILD", "diff": "@@ -6,4 +6,5 @@ go_binary(\nname = \"stateify\",\nsrcs = [\"main.go\"],\nvisibility = [\"//visibility:public\"],\n+ deps = [\"//tools/tags\"],\n)\n" }, { "change_type": "MODIFY", "old_path": "tools/go_stateify/defs.bzl", "new_path": "tools/go_stateify/defs.bzl", "diff": "@@ -7,7 +7,6 @@ def _go_stateify_impl(ctx):\n# Run the stateify command.\nargs = [\"-output=%s\" % output.path]\nargs.append(\"-pkg=%s\" % ctx.attr.package)\n- args.append(\"-arch=%s\" % ctx.attr.arch)\nif ctx.attr._statepkg:\nargs.append(\"-statepkg=%s\" % ctx.attr._statepkg)\nif ctx.attr.imports:\n@@ -47,15 +46,8 @@ for statified types.\ndoc = \"The package name for the input sources.\",\nmandatory = True,\n),\n- \"arch\": attr.string(\n- doc = \"Target platform.\",\n- mandatory = True,\n- ),\n\"out\": attr.output(\n- doc = \"\"\"\n-The name of the generated file output. This must not conflict with any other\n-files and must be added to the srcs of the relevant go_library.\n-\"\"\",\n+ doc = \"Name of the generator output file.\",\nmandatory = True,\n),\n\"_tool\": attr.label(\n" }, { "change_type": "MODIFY", "old_path": "tools/go_stateify/main.go", "new_path": "tools/go_stateify/main.go", "diff": "@@ -22,12 +22,12 @@ import (\n\"go/ast\"\n\"go/parser\"\n\"go/token\"\n- \"io/ioutil\"\n\"os\"\n- \"path/filepath\"\n\"reflect\"\n\"strings\"\n\"sync\"\n+\n+ \"gvisor.dev/gvisor/tools/tags\"\n)\nvar (\n@@ -35,113 +35,8 @@ var (\nimports = flag.String(\"imports\", \"\", \"extra imports for the output file\")\noutput = flag.String(\"output\", \"\", \"output file\")\nstatePkg = flag.String(\"statepkg\", \"\", \"state import package; defaults to empty\")\n- arch = flag.String(\"arch\", \"\", \"specify the target platform\")\n)\n-// The known architectures.\n-var okgoarch = []string{\n- \"386\",\n- \"amd64\",\n- \"arm\",\n- \"arm64\",\n- \"mips\",\n- \"mipsle\",\n- \"mips64\",\n- \"mips64le\",\n- \"ppc64\",\n- \"ppc64le\",\n- \"riscv64\",\n- \"s390x\",\n- \"sparc64\",\n- \"wasm\",\n-}\n-\n-// readfile returns the content of the named file.\n-func readfile(file string) string {\n- data, err := ioutil.ReadFile(file)\n- if err != nil {\n- panic(fmt.Sprintf(\"readfile err: %v\", err))\n- }\n- return string(data)\n-}\n-\n-// matchfield reports whether the field (x,y,z) matches this build.\n-// all the elements in the field must be satisfied.\n-func matchfield(f string, goarch string) bool {\n- for _, tag := range strings.Split(f, \",\") {\n- if !matchtag(tag, goarch) {\n- return false\n- }\n- }\n- return true\n-}\n-\n-// matchtag reports whether the tag (x or !x) matches this build.\n-func matchtag(tag string, goarch string) bool {\n- if tag == \"\" {\n- return false\n- }\n- if tag[0] == '!' {\n- if len(tag) == 1 || tag[1] == '!' {\n- return false\n- }\n- return !matchtag(tag[1:], goarch)\n- }\n- return tag == goarch\n-}\n-\n-// canBuild reports whether we can build this file for target platform by\n-// checking file name and build tags. The code is derived from the Go source\n-// cmd.dist.build.shouldbuild.\n-func canBuild(file, goTargetArch string) bool {\n- name := filepath.Base(file)\n- excluded := func(list []string, ok string) bool {\n- for _, x := range list {\n- if x == ok || (ok == \"android\" && x == \"linux\") || (ok == \"illumos\" && x == \"solaris\") {\n- continue\n- }\n- i := strings.Index(name, x)\n- if i <= 0 || name[i-1] != '_' {\n- continue\n- }\n- i += len(x)\n- if i == len(name) || name[i] == '.' || name[i] == '_' {\n- return true\n- }\n- }\n- return false\n- }\n- if excluded(okgoarch, goTargetArch) {\n- return false\n- }\n-\n- // Check file contents for // +build lines.\n- for _, p := range strings.Split(readfile(file), \"\\n\") {\n- p = strings.TrimSpace(p)\n- if p == \"\" {\n- continue\n- }\n- if !strings.HasPrefix(p, \"//\") {\n- break\n- }\n- if !strings.Contains(p, \"+build\") {\n- continue\n- }\n- fields := strings.Fields(p[2:])\n- if len(fields) < 1 || fields[0] != \"+build\" {\n- continue\n- }\n- for _, p := range fields[1:] {\n- if matchfield(p, goTargetArch) {\n- goto fieldmatch\n- }\n- }\n- return false\n- fieldmatch:\n- }\n- return true\n-}\n-\n// resolveTypeName returns a qualified type name.\nfunc resolveTypeName(name string, typ ast.Expr) (field string, qualified string) {\nfor done := false; !done; {\n@@ -329,8 +224,15 @@ func main() {\nfmt.Fprintf(outputFile, \" m.Save(\\\"%s\\\", &x.%s)\\n\", name, name)\n}\n- // Emit the package name.\n+ // Automated warning.\nfmt.Fprint(outputFile, \"// automatically generated by stateify.\\n\\n\")\n+\n+ // Emit build tags.\n+ if t := tags.Aggregate(flag.Args()); len(t) > 0 {\n+ fmt.Fprintf(outputFile, \"%s\\n\\n\", strings.Join(t.Lines(), \"\\n\"))\n+ }\n+\n+ // Emit the package name.\nfmt.Fprintf(outputFile, \"package %s\\n\\n\", *pkg)\n// Emit the imports lazily.\n@@ -364,10 +266,6 @@ func main() {\nos.Exit(1)\n}\n- if !canBuild(filename, *arch) {\n- continue\n- }\n-\nfiles = append(files, f)\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/tags/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"tags\",\n+ srcs = [\"tags.go\"],\n+ marshal = False,\n+ stateify = False,\n+ visibility = [\"//tools:__subpackages__\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/tags/tags.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package tags is a utility for parsing build tags.\n+package tags\n+\n+import (\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"strings\"\n+)\n+\n+// OrSet is a set of tags on a single line.\n+//\n+// Note that tags may include \",\", and we don't distinguish this case in the\n+// logic below. Ideally, this constraints can be split into separate top-level\n+// build tags in order to resolve any issues.\n+type OrSet []string\n+\n+// Line returns the line for this or.\n+func (or OrSet) Line() string {\n+ return fmt.Sprintf(\"// +build %s\", strings.Join([]string(or), \" \"))\n+}\n+\n+// AndSet is the set of all OrSets.\n+type AndSet []OrSet\n+\n+// Lines returns the lines to be printed.\n+func (and AndSet) Lines() (ls []string) {\n+ for _, or := range and {\n+ ls = append(ls, or.Line())\n+ }\n+ return\n+}\n+\n+// Join joins this AndSet with another.\n+func (and AndSet) Join(other AndSet) AndSet {\n+ return append(and, other...)\n+}\n+\n+// Tags returns the unique set of +build tags.\n+//\n+// Derived form the runtime's canBuild.\n+func Tags(file string) (tags AndSet) {\n+ data, err := ioutil.ReadFile(file)\n+ if err != nil {\n+ return nil\n+ }\n+ // Check file contents for // +build lines.\n+ for _, p := range strings.Split(string(data), \"\\n\") {\n+ p = strings.TrimSpace(p)\n+ if p == \"\" {\n+ continue\n+ }\n+ if !strings.HasPrefix(p, \"//\") {\n+ break\n+ }\n+ if !strings.Contains(p, \"+build\") {\n+ continue\n+ }\n+ fields := strings.Fields(p[2:])\n+ if len(fields) < 1 || fields[0] != \"+build\" {\n+ continue\n+ }\n+ tags = append(tags, OrSet(fields[1:]))\n+ }\n+ return tags\n+}\n+\n+// Aggregate aggregates all tags from a set of files.\n+//\n+// Note that these may be in conflict, in which case the build will fail.\n+func Aggregate(files []string) (tags AndSet) {\n+ for _, file := range files {\n+ tags = tags.Join(Tags(file))\n+ }\n+ return tags\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Automatically propagate tags for stateify and marshal. Note that files will need to be appropriately segmented in order for the mechanism to work, in suffixes implying special tags. This only needs to happen for cases where marshal or state structures are defined, which should be rare and mostly architecture specific. PiperOrigin-RevId: 293231579
259,854
04.02.2020 15:20:30
28,800
a26a954946ad2e7910d3ad7578960a93b73a1f9b
Add socket connection stress test. Tests 65k connection attempts on common types of sockets to check for port leaks. Also fixes a bug where dual-stack sockets wouldn't properly re-queue segments received while closing.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -989,6 +989,10 @@ func (e *endpoint) transitionToStateCloseLocked() {\n// to any other listening endpoint. We reply with RST if we cannot find one.\nfunc (e *endpoint) tryDeliverSegmentFromClosedEndpoint(s *segment) {\nep := e.stack.FindTransportEndpoint(e.NetProto, e.TransProto, e.ID, &s.route)\n+ if ep == nil && e.NetProto == header.IPv6ProtocolNumber && e.EndpointInfo.TransportEndpointInfo.ID.LocalAddress.To4() != \"\" {\n+ // Dual-stack socket, try IPv4.\n+ ep = e.stack.FindTransportEndpoint(header.IPv4ProtocolNumber, e.TransProto, e.ID, &s.route)\n+ }\nif ep == nil {\nreplyWithReset(s)\ns.decRef()\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -45,6 +45,15 @@ syscall_test(test = \"//test/syscalls/linux:brk_test\")\nsyscall_test(test = \"//test/syscalls/linux:socket_test\")\n+syscall_test(\n+ size = \"large\",\n+ shard_count = 50,\n+ # Takes too long for TSAN. Since this is kind of a stress test that doesn't\n+ # involve much concurrency, TSAN's usefulness here is limited anyway.\n+ tags = [\"nogotsan\"],\n+ test = \"//test/syscalls/linux:socket_stress_test\",\n+)\n+\nsyscall_test(\nadd_overlay = True,\ntest = \"//test/syscalls/linux:chdir_test\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -136,6 +136,7 @@ cc_library(\n\"@com_google_absl//absl/strings\",\n\"@com_google_absl//absl/strings:str_format\",\n\"@com_google_absl//absl/time\",\n+ \"@com_google_absl//absl/types:optional\",\n\"//test/util:file_descriptor\",\n\"//test/util:posix_error\",\n\"//test/util:temp_path\",\n@@ -2151,6 +2152,22 @@ cc_library(\nalwayslink = 1,\n)\n+cc_binary(\n+ name = \"socket_stress_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"socket_generic_stress.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":ip_socket_test_util\",\n+ \":socket_test_util\",\n+ gtest,\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ ],\n+)\n+\ncc_library(\nname = \"socket_unix_dgram_test_cases\",\ntestonly = 1,\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip_socket_test_util.cc", "new_path": "test/syscalls/linux/ip_socket_test_util.cc", "diff": "@@ -79,6 +79,33 @@ SocketPairKind DualStackTCPAcceptBindSocketPair(int type) {\n/* dual_stack = */ true)};\n}\n+SocketPairKind IPv6TCPAcceptBindPersistentListenerSocketPair(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv6 TCP socket\");\n+ return SocketPairKind{description, AF_INET6, type | SOCK_STREAM, IPPROTO_TCP,\n+ TCPAcceptBindPersistentListenerSocketPairCreator(\n+ AF_INET6, type | SOCK_STREAM, 0,\n+ /* dual_stack = */ false)};\n+}\n+\n+SocketPairKind IPv4TCPAcceptBindPersistentListenerSocketPair(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"connected IPv4 TCP socket\");\n+ return SocketPairKind{description, AF_INET, type | SOCK_STREAM, IPPROTO_TCP,\n+ TCPAcceptBindPersistentListenerSocketPairCreator(\n+ AF_INET, type | SOCK_STREAM, 0,\n+ /* dual_stack = */ false)};\n+}\n+\n+SocketPairKind DualStackTCPAcceptBindPersistentListenerSocketPair(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"connected dual stack TCP socket\");\n+ return SocketPairKind{description, AF_INET6, type | SOCK_STREAM, IPPROTO_TCP,\n+ TCPAcceptBindPersistentListenerSocketPairCreator(\n+ AF_INET6, type | SOCK_STREAM, 0,\n+ /* dual_stack = */ true)};\n+}\n+\nSocketPairKind IPv6UDPBidirectionalBindSocketPair(int type) {\nstd::string description =\nabsl::StrCat(DescribeSocketType(type), \"connected IPv6 UDP socket\");\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/ip_socket_test_util.h", "new_path": "test/syscalls/linux/ip_socket_test_util.h", "diff": "@@ -50,6 +50,21 @@ SocketPairKind IPv4TCPAcceptBindSocketPair(int type);\n// given type bound to the IPv4 loopback.\nSocketPairKind DualStackTCPAcceptBindSocketPair(int type);\n+// IPv6TCPAcceptBindPersistentListenerSocketPair is like\n+// IPv6TCPAcceptBindSocketPair except it uses a persistent listening socket to\n+// create all socket pairs.\n+SocketPairKind IPv6TCPAcceptBindPersistentListenerSocketPair(int type);\n+\n+// IPv4TCPAcceptBindPersistentListenerSocketPair is like\n+// IPv4TCPAcceptBindSocketPair except it uses a persistent listening socket to\n+// create all socket pairs.\n+SocketPairKind IPv4TCPAcceptBindPersistentListenerSocketPair(int type);\n+\n+// DualStackTCPAcceptBindPersistentListenerSocketPair is like\n+// DualStackTCPAcceptBindSocketPair except it uses a persistent listening socket\n+// to create all socket pairs.\n+SocketPairKind DualStackTCPAcceptBindPersistentListenerSocketPair(int type);\n+\n// IPv6UDPBidirectionalBindSocketPair returns a SocketPairKind that represents\n// SocketPairs created with bind() and connect() syscalls with AF_INET6 and the\n// given type bound to the IPv6 loopback.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/syscalls/linux/socket_generic_stress.cc", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <stdio.h>\n+#include <sys/ioctl.h>\n+#include <sys/socket.h>\n+#include <sys/un.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+// Test fixture for tests that apply to pairs of connected sockets.\n+using ConnectStressTest = SocketPairTest;\n+\n+TEST_P(ConnectStressTest, Reset65kTimes) {\n+ for (int i = 0; i < 1 << 16; ++i) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // Send some data to ensure that the connection gets reset and the port gets\n+ // released immediately. This avoids either end entering TIME-WAIT.\n+ char sent_data[100] = {};\n+ ASSERT_THAT(write(sockets->first_fd(), sent_data, sizeof(sent_data)),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+ }\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ AllConnectedSockets, ConnectStressTest,\n+ ::testing::Values(IPv6UDPBidirectionalBindSocketPair(0),\n+ IPv4UDPBidirectionalBindSocketPair(0),\n+ DualStackUDPBidirectionalBindSocketPair(0),\n+\n+ // Without REUSEADDR, we get port exhaustion on Linux.\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR,\n+ &kSockOptOn)(IPv6TCPAcceptBindSocketPair(0)),\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR,\n+ &kSockOptOn)(IPv4TCPAcceptBindSocketPair(0)),\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(\n+ DualStackTCPAcceptBindSocketPair(0))));\n+\n+// Test fixture for tests that apply to pairs of connected sockets created with\n+// a persistent listener (if applicable).\n+using PersistentListenerConnectStressTest = SocketPairTest;\n+\n+TEST_P(PersistentListenerConnectStressTest, 65kTimes) {\n+ for (int i = 0; i < 1 << 16; ++i) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ }\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(\n+ AllConnectedSockets, PersistentListenerConnectStressTest,\n+ ::testing::Values(\n+ IPv6UDPBidirectionalBindSocketPair(0),\n+ IPv4UDPBidirectionalBindSocketPair(0),\n+ DualStackUDPBidirectionalBindSocketPair(0),\n+\n+ // Without REUSEADDR, we get port exhaustion on Linux.\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(\n+ IPv6TCPAcceptBindPersistentListenerSocketPair(0)),\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(\n+ IPv4TCPAcceptBindPersistentListenerSocketPair(0)),\n+ SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &kSockOptOn)(\n+ DualStackTCPAcceptBindPersistentListenerSocketPair(0))));\n+\n+} // namespace testing\n+} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.cc", "new_path": "test/syscalls/linux/socket_test_util.cc", "diff": "#include <poll.h>\n#include <sys/socket.h>\n+#include <memory>\n+\n#include \"gtest/gtest.h\"\n#include \"absl/memory/memory.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/time/clock.h\"\n+#include \"absl/types/optional.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n@@ -109,7 +112,10 @@ Creator<SocketPair> AcceptBindSocketPairCreator(bool abstract, int domain,\nMaybeSave(); // Unlinked path.\n}\n- return absl::make_unique<AddrFDSocketPair>(connected, accepted, bind_addr,\n+ // accepted is before connected to destruct connected before accepted.\n+ // Destructors for nonstatic member objects are called in the reverse order\n+ // in which they appear in the class declaration.\n+ return absl::make_unique<AddrFDSocketPair>(accepted, connected, bind_addr,\nextra_addr);\n};\n}\n@@ -311,11 +317,16 @@ PosixErrorOr<T> BindIP(int fd, bool dual_stack) {\n}\ntemplate <typename T>\n-PosixErrorOr<std::unique_ptr<AddrFDSocketPair>> CreateTCPAcceptBindSocketPair(\n- int bound, int connected, int type, bool dual_stack) {\n- ASSIGN_OR_RETURN_ERRNO(T bind_addr, BindIP<T>(bound, dual_stack));\n- RETURN_ERROR_IF_SYSCALL_FAIL(listen(bound, /* backlog = */ 5));\n+PosixErrorOr<T> TCPBindAndListen(int fd, bool dual_stack) {\n+ ASSIGN_OR_RETURN_ERRNO(T addr, BindIP<T>(fd, dual_stack));\n+ RETURN_ERROR_IF_SYSCALL_FAIL(listen(fd, /* backlog = */ 5));\n+ return addr;\n+}\n+template <typename T>\n+PosixErrorOr<std::unique_ptr<AddrFDSocketPair>>\n+CreateTCPConnectAcceptSocketPair(int bound, int connected, int type,\n+ bool dual_stack, T bind_addr) {\nint connect_result = 0;\nRETURN_ERROR_IF_SYSCALL_FAIL(\n(connect_result = RetryEINTR(connect)(\n@@ -358,16 +369,27 @@ PosixErrorOr<std::unique_ptr<AddrFDSocketPair>> CreateTCPAcceptBindSocketPair(\nabsl::SleepFor(absl::Seconds(1));\n}\n- // Cleanup no longer needed resources.\n- RETURN_ERROR_IF_SYSCALL_FAIL(close(bound));\n- MaybeSave(); // Successful close.\n-\nT extra_addr = {};\nLocalhostAddr(&extra_addr, dual_stack);\nreturn absl::make_unique<AddrFDSocketPair>(connected, accepted, bind_addr,\nextra_addr);\n}\n+template <typename T>\n+PosixErrorOr<std::unique_ptr<AddrFDSocketPair>> CreateTCPAcceptBindSocketPair(\n+ int bound, int connected, int type, bool dual_stack) {\n+ ASSIGN_OR_RETURN_ERRNO(T bind_addr, TCPBindAndListen<T>(bound, dual_stack));\n+\n+ auto result = CreateTCPConnectAcceptSocketPair(bound, connected, type,\n+ dual_stack, bind_addr);\n+\n+ // Cleanup no longer needed resources.\n+ RETURN_ERROR_IF_SYSCALL_FAIL(close(bound));\n+ MaybeSave(); // Successful close.\n+\n+ return result;\n+}\n+\nCreator<SocketPair> TCPAcceptBindSocketPairCreator(int domain, int type,\nint protocol,\nbool dual_stack) {\n@@ -389,6 +411,63 @@ Creator<SocketPair> TCPAcceptBindSocketPairCreator(int domain, int type,\n};\n}\n+Creator<SocketPair> TCPAcceptBindPersistentListenerSocketPairCreator(\n+ int domain, int type, int protocol, bool dual_stack) {\n+ // These are lazily initialized below, on the first call to the returned\n+ // lambda. These values are private to each returned lambda, but shared across\n+ // invocations of a specific lambda.\n+ //\n+ // The sharing allows pairs created with the same parameters to share a\n+ // listener. This prevents future connects from failing if the connecting\n+ // socket selects a port which had previously been used by a listening socket\n+ // that still has some connections in TIME-WAIT.\n+ //\n+ // The lazy initialization is to avoid creating sockets during parameter\n+ // enumeration. This is important because parameters are enumerated during the\n+ // build process where networking may not be available.\n+ auto listener = std::make_shared<absl::optional<int>>(absl::optional<int>());\n+ auto addr4 = std::make_shared<absl::optional<sockaddr_in>>(\n+ absl::optional<sockaddr_in>());\n+ auto addr6 = std::make_shared<absl::optional<sockaddr_in6>>(\n+ absl::optional<sockaddr_in6>());\n+\n+ return [=]() -> PosixErrorOr<std::unique_ptr<AddrFDSocketPair>> {\n+ int connected;\n+ RETURN_ERROR_IF_SYSCALL_FAIL(connected = socket(domain, type, protocol));\n+ MaybeSave(); // Successful socket creation.\n+\n+ // Share the listener across invocations.\n+ if (!listener->has_value()) {\n+ int fd = socket(domain, type, protocol);\n+ if (fd < 0) {\n+ return PosixError(errno, absl::StrCat(\"socket(\", domain, \", \", type,\n+ \", \", protocol, \")\"));\n+ }\n+ listener->emplace(fd);\n+ MaybeSave(); // Successful socket creation.\n+ }\n+\n+ // Bind the listener once, but create a new connect/accept pair each\n+ // time.\n+ if (domain == AF_INET) {\n+ if (!addr4->has_value()) {\n+ addr4->emplace(\n+ TCPBindAndListen<sockaddr_in>(listener->value(), dual_stack)\n+ .ValueOrDie());\n+ }\n+ return CreateTCPConnectAcceptSocketPair(listener->value(), connected,\n+ type, dual_stack, addr4->value());\n+ }\n+ if (!addr6->has_value()) {\n+ addr6->emplace(\n+ TCPBindAndListen<sockaddr_in6>(listener->value(), dual_stack)\n+ .ValueOrDie());\n+ }\n+ return CreateTCPConnectAcceptSocketPair(listener->value(), connected, type,\n+ dual_stack, addr6->value());\n+ };\n+}\n+\ntemplate <typename T>\nPosixErrorOr<std::unique_ptr<AddrFDSocketPair>> CreateUDPBoundSocketPair(\nint sock1, int sock2, int type, bool dual_stack) {\n@@ -518,8 +597,8 @@ size_t CalculateUnixSockAddrLen(const char* sun_path) {\nif (sun_path[0] == 0) {\nreturn sizeof(sockaddr_un);\n}\n- // Filesystem addresses use the address length plus the 2 byte sun_family and\n- // null terminator.\n+ // Filesystem addresses use the address length plus the 2 byte sun_family\n+ // and null terminator.\nreturn strlen(sun_path) + 3;\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_test_util.h", "new_path": "test/syscalls/linux/socket_test_util.h", "diff": "@@ -273,6 +273,12 @@ Creator<SocketPair> TCPAcceptBindSocketPairCreator(int domain, int type,\nint protocol,\nbool dual_stack);\n+// TCPAcceptBindPersistentListenerSocketPairCreator is like\n+// TCPAcceptBindSocketPairCreator, except it uses the same listening socket to\n+// create all SocketPairs.\n+Creator<SocketPair> TCPAcceptBindPersistentListenerSocketPairCreator(\n+ int domain, int type, int protocol, bool dual_stack);\n+\n// UDPBidirectionalBindSocketPairCreator returns a Creator<SocketPair> that\n// obtains file descriptors by invoking the bind() and connect() syscalls on UDP\n// sockets.\n" } ]
Go
Apache License 2.0
google/gvisor
Add socket connection stress test. Tests 65k connection attempts on common types of sockets to check for port leaks. Also fixes a bug where dual-stack sockets wouldn't properly re-queue segments received while closing. PiperOrigin-RevId: 293241166
259,972
05.02.2020 11:17:14
28,800
37abbbc547d9d78e0bf42f192403c8eca30593d8
Add packetdrill tests to presubmit and CI testing
[ { "change_type": "ADD", "old_path": null, "new_path": "kokoro/packetdrill_tests.cfg", "diff": "+build_file: \"repo/scripts/packetdrill_tests.sh\"\n+\n+action {\n+ define_artifacts {\n+ regex: \"**/sponge_log.xml\"\n+ regex: \"**/sponge_log.log\"\n+ regex: \"**/outputs.zip\"\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/packetdrill_tests.sh", "diff": "+#!/bin/bash\n+\n+# Copyright 2019 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+source $(dirname $0)/common.sh\n+\n+install_runsc_for_test runsc-d\n+test_runsc $(bazel query \"attr(tags, manual, tests(//test/packetdrill/...))\")\n" }, { "change_type": "MODIFY", "old_path": "test/packetdrill/defs.bzl", "new_path": "test/packetdrill/defs.bzl", "diff": "@@ -15,7 +15,7 @@ def _packetdrill_test_impl(ctx):\n# Make sure that everything is readable here.\n\"find . -type f -exec chmod a+rx {} \\\\;\",\n\"find . -type d -exec chmod a+rx {} \\\\;\",\n- \"%s %s --init_script %s -- %s\\n\" % (\n+ \"%s %s --init_script %s $@ -- %s\\n\" % (\ntest_runner.short_path,\n\" \".join(ctx.attr.flags),\nctx.files._init_script[0].short_path,\n@@ -76,7 +76,9 @@ def packetdrill_netstack_test(name, **kwargs):\nkwargs[\"tags\"] = _PACKETDRILL_TAGS\n_packetdrill_test(\nname = name + \"_netstack_test\",\n- flags = [\"--dut_platform\", \"netstack\"],\n+ # This is the default runtime unless\n+ # \"--test_arg=--runtime=OTHER_RUNTIME\" is used to override the value.\n+ flags = [\"--dut_platform\", \"netstack\", \"--runtime\", \"runsc-d\"],\n**kwargs\n)\n" }, { "change_type": "MODIFY", "old_path": "test/packetdrill/packetdrill_test.sh", "new_path": "test/packetdrill/packetdrill_test.sh", "diff": "@@ -29,7 +29,7 @@ function failure() {\n}\ntrap 'failure ${LINENO} \"$BASH_COMMAND\"' ERR\n-declare -r LONGOPTS=\"dut_platform:,init_script:\"\n+declare -r LONGOPTS=\"dut_platform:,init_script:,runtime:\"\n# Don't use declare below so that the error from getopt will end the script.\nPARSED=$(getopt --options \"\" --longoptions=$LONGOPTS --name \"$0\" -- \"$@\")\n@@ -39,6 +39,7 @@ eval set -- \"$PARSED\"\nwhile true; do\ncase \"$1\" in\n--dut_platform)\n+ # Either \"linux\" or \"netstack\".\ndeclare -r DUT_PLATFORM=\"$2\"\nshift 2\n;;\n@@ -46,6 +47,13 @@ while true; do\ndeclare -r INIT_SCRIPT=\"$2\"\nshift 2\n;;\n+ --runtime)\n+ # Not readonly because there might be multiple --runtime arguments and we\n+ # want to use just the last one. Only used if --dut_platform is\n+ # \"netstack\".\n+ declare RUNTIME=\"$2\"\n+ shift 2\n+ ;;\n--)\nshift\nbreak\n@@ -61,9 +69,13 @@ declare -r scripts=\"$@\"\n# Check that the required flags are defined in a way that is safe for \"set -u\".\nif [[ \"${DUT_PLATFORM-}\" == \"netstack\" ]]; then\n- declare -r RUNTIME=\"--runtime runsc-d\"\n+ if [[ -z \"${RUNTIME-}\" ]]; then\n+ echo \"FAIL: Missing --runtime argument: ${RUNTIME-}\"\n+ exit 2\n+ fi\n+ declare -r RUNTIME_ARG=\"--runtime ${RUNTIME}\"\nelif [[ \"${DUT_PLATFORM-}\" == \"linux\" ]]; then\n- declare -r RUNTIME=\"\"\n+ declare -r RUNTIME_ARG=\"\"\nelse\necho \"FAIL: Bad or missing --dut_platform argument: ${DUT_PLATFORM-}\"\nexit 2\n@@ -143,7 +155,7 @@ done\ndocker pull \"${IMAGE_TAG}\"\n# Create the DUT container and connect to network.\n-DUT=$(docker create ${RUNTIME} --privileged --rm \\\n+DUT=$(docker create ${RUNTIME_ARG} --privileged --rm \\\n--stop-timeout ${TIMEOUT} -it ${IMAGE_TAG})\ndocker network connect \"${CTRL_NET}\" \\\n--ip \"${CTRL_NET_PREFIX}${DUT_NET_SUFFIX}\" \"${DUT}\" \\\n" } ]
Go
Apache License 2.0
google/gvisor
Add packetdrill tests to presubmit and CI testing PiperOrigin-RevId: 293409718
259,847
05.02.2020 11:33:48
28,800
f2d3efca1deded31a2929ea77c0eecf476764660
Fix undeclared variable error in common_build.sh.
[ { "change_type": "MODIFY", "old_path": "scripts/common_build.sh", "new_path": "scripts/common_build.sh", "diff": "@@ -32,21 +32,21 @@ declare -r BAZEL_FLAGS=(\n\"--keep_going\"\n\"--verbose_failures=true\"\n)\n+BAZEL_RBE_AUTH_FLAGS=\"\"\n+BAZEL_RBE_FLAGS=\"\"\nif [[ -v KOKORO_BAZEL_AUTH_CREDENTIAL ]]; then\n- declare -r BAZEL_RBE_AUTH_FLAGS=(\n- \"--auth_credentials=${KOKORO_BAZEL_AUTH_CREDENTIAL}\"\n- )\n- declare -r BAZEL_RBE_FLAGS=(\"--config=remote\")\n+ declare -r BAZEL_RBE_AUTH_FLAGS=\"--auth_credentials=${KOKORO_BAZEL_AUTH_CREDENTIAL}\"\n+ declare -r BAZEL_RBE_FLAGS=\"--config=remote\"\nfi\n# Wrap bazel.\nfunction build() {\n- bazel build \"${BAZEL_RBE_FLAGS[@]}\" \"${BAZEL_RBE_AUTH_FLAGS[@]}\" \"${BAZEL_FLAGS[@]}\" \"$@\" 2>&1 |\n+ bazel build \"${BAZEL_RBE_FLAGS}\" \"${BAZEL_RBE_AUTH_FLAGS}\" \"${BAZEL_FLAGS[@]}\" \"$@\" 2>&1 |\ntee /dev/fd/2 | grep -E '^ bazel-bin/' | awk '{ print $1; }'\n}\nfunction test() {\n- bazel test \"${BAZEL_RBE_FLAGS[@]}\" \"${BAZEL_RBE_AUTH_FLAGS[@]}\" \"${BAZEL_FLAGS[@]}\" \"$@\"\n+ bazel test \"${BAZEL_RBE_FLAGS}\" \"${BAZEL_RBE_AUTH_FLAGS}\" \"${BAZEL_FLAGS[@]}\" \"$@\"\n}\nfunction run() {\n" } ]
Go
Apache License 2.0
google/gvisor
Fix undeclared variable error in common_build.sh. PiperOrigin-RevId: 293413711
259,972
05.02.2020 17:56:00
28,800
f3d95607036b8a502c65aa7b3e8145227274dbbc
recv() on a closed TCP socket returns ENOTCONN From RFC 793 s3.9 p58 Event Processing: If RECEIVE Call arrives in CLOSED state and the user has access to such a connection, the return should be "error: connection does not exist" Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -2229,11 +2229,16 @@ func (s *SocketOperations) coalescingRead(ctx context.Context, dst usermem.IOSeq\nvar copied int\n// Copy as many views as possible into the user-provided buffer.\n- for dst.NumBytes() != 0 {\n+ for {\n+ // Always do at least one fetchReadView, even if the number of bytes to\n+ // read is 0.\nerr = s.fetchReadView()\nif err != nil {\nbreak\n}\n+ if dst.NumBytes() == 0 {\n+ break\n+ }\nvar n int\nvar e error\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1124,6 +1124,10 @@ type ReadErrors struct {\n// InvalidEndpointState is the number of times we found the endpoint state\n// to be unexpected.\nInvalidEndpointState StatCounter\n+\n+ // NotConnected is the number of times we tried to read but found that the\n+ // endpoint was not connected.\n+ NotConnected StatCounter\n}\n// WriteErrors collects packet write errors from an endpoint write call.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1003,8 +1003,8 @@ func (e *endpoint) Read(*tcpip.FullAddress) (buffer.View, tcpip.ControlMessages,\nif s == StateError {\nreturn buffer.View{}, tcpip.ControlMessages{}, he\n}\n- e.stats.ReadErrors.InvalidEndpointState.Increment()\n- return buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrInvalidEndpointState\n+ e.stats.ReadErrors.NotConnected.Increment()\n+ return buffer.View{}, tcpip.ControlMessages{}, tcpip.ErrNotConnected\n}\nv, err := e.readLocked()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -5405,12 +5405,11 @@ func TestEndpointBindListenAcceptState(t *testing.T) {\nt.Errorf(\"Unexpected endpoint state: want %v, got %v\", want, got)\n}\n- // Expect InvalidEndpointState errors on a read at this point.\n- if _, _, err := ep.Read(nil); err != tcpip.ErrInvalidEndpointState {\n- t.Fatalf(\"got c.EP.Read(nil) = %v, want = %v\", err, tcpip.ErrInvalidEndpointState)\n+ if _, _, err := ep.Read(nil); err != tcpip.ErrNotConnected {\n+ t.Errorf(\"got c.EP.Read(nil) = %v, want = %v\", err, tcpip.ErrNotConnected)\n}\n- if got := ep.Stats().(*tcp.Stats).ReadErrors.InvalidEndpointState.Value(); got != 1 {\n- t.Fatalf(\"got EP stats Stats.ReadErrors.InvalidEndpointState got %v want %v\", got, 1)\n+ if got := ep.Stats().(*tcp.Stats).ReadErrors.NotConnected.Value(); got != 1 {\n+ t.Errorf(\"got EP stats Stats.ReadErrors.NotConnected got %v want %v\", got, 1)\n}\nif err := ep.Listen(10); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/tcp_socket.cc", "new_path": "test/syscalls/linux/tcp_socket.cc", "diff": "@@ -1339,6 +1339,15 @@ TEST_P(SimpleTcpSocketTest, SetTCPDeferAcceptGreaterThanZero) {\nEXPECT_EQ(get, kTCPDeferAccept);\n}\n+TEST_P(SimpleTcpSocketTest, RecvOnClosedSocket) {\n+ auto s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+ char buf[1];\n+ EXPECT_THAT(recv(s.get(), buf, 0, 0), SyscallFailsWithErrno(ENOTCONN));\n+ EXPECT_THAT(recv(s.get(), buf, sizeof(buf), 0),\n+ SyscallFailsWithErrno(ENOTCONN));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, SimpleTcpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n" } ]
Go
Apache License 2.0
google/gvisor
recv() on a closed TCP socket returns ENOTCONN From RFC 793 s3.9 p58 Event Processing: If RECEIVE Call arrives in CLOSED state and the user has access to such a connection, the return should be "error: connection does not exist" Fixes #1598 PiperOrigin-RevId: 293494287
259,853
06.02.2020 10:06:56
28,800
5ff780891e229dbde00d9a37c2f8b6681e592fdb
Move p9.pool to a separate package
[ { "change_type": "MODIFY", "old_path": "pkg/p9/BUILD", "new_path": "pkg/p9/BUILD", "diff": "@@ -16,7 +16,6 @@ go_library(\n\"messages.go\",\n\"p9.go\",\n\"path_tree.go\",\n- \"pool.go\",\n\"server.go\",\n\"transport.go\",\n\"transport_flipcall.go\",\n@@ -27,6 +26,7 @@ go_library(\n\"//pkg/fdchannel\",\n\"//pkg/flipcall\",\n\"//pkg/log\",\n+ \"//pkg/pool\",\n\"//pkg/sync\",\n\"//pkg/unet\",\n\"@org_golang_x_sys//unix:go_default_library\",\n@@ -41,7 +41,6 @@ go_test(\n\"client_test.go\",\n\"messages_test.go\",\n\"p9_test.go\",\n- \"pool_test.go\",\n\"transport_test.go\",\n\"version_test.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/client.go", "new_path": "pkg/p9/client.go", "diff": "@@ -22,6 +22,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/flipcall\"\n\"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/pool\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/unet\"\n)\n@@ -74,10 +75,10 @@ type Client struct {\nsocket *unet.Socket\n// tagPool is the collection of available tags.\n- tagPool pool\n+ tagPool pool.Pool\n// fidPool is the collection of available fids.\n- fidPool pool\n+ fidPool pool.Pool\n// messageSize is the maximum total size of a message.\nmessageSize uint32\n@@ -155,8 +156,8 @@ func NewClient(socket *unet.Socket, messageSize uint32, version string) (*Client\n}\nc := &Client{\nsocket: socket,\n- tagPool: pool{start: 1, limit: uint64(NoTag)},\n- fidPool: pool{start: 1, limit: uint64(NoFID)},\n+ tagPool: pool.Pool{Start: 1, Limit: uint64(NoTag)},\n+ fidPool: pool.Pool{Start: 1, Limit: uint64(NoFID)},\npending: make(map[Tag]*response),\nrecvr: make(chan bool, 1),\nmessageSize: messageSize,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/pool/BUILD", "diff": "+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+\n+package(\n+ default_visibility = [\"//visibility:public\"],\n+ licenses = [\"notice\"],\n+)\n+\n+go_library(\n+ name = \"pool\",\n+ srcs = [\n+ \"pool.go\",\n+ ],\n+ deps = [\n+ \"//pkg/sync\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"pool_test\",\n+ size = \"small\",\n+ srcs = [\n+ \"pool_test.go\",\n+ ],\n+ library = \":pool\",\n+)\n" }, { "change_type": "RENAME", "old_path": "pkg/p9/pool.go", "new_path": "pkg/pool/pool.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package p9\n+package pool\nimport (\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n-// pool is a simple allocator.\n-//\n-// It is used for both tags and FIDs.\n-type pool struct {\n+// Pool is a simple allocator.\n+type Pool struct {\nmu sync.Mutex\n// cache is the set of returned values.\ncache []uint64\n- // start is the starting value (if needed).\n- start uint64\n+ // Start is the starting value (if needed).\n+ Start uint64\n// max is the current maximum issued.\nmax uint64\n- // limit is the upper limit.\n- limit uint64\n+ // Limit is the upper limit.\n+ Limit uint64\n}\n// Get gets a value from the pool.\n-func (p *pool) Get() (uint64, bool) {\n+func (p *Pool) Get() (uint64, bool) {\np.mu.Lock()\ndefer p.mu.Unlock()\n@@ -50,18 +48,18 @@ func (p *pool) Get() (uint64, bool) {\n}\n// Over the limit?\n- if p.start == p.limit {\n+ if p.Start == p.Limit {\nreturn 0, false\n}\n// Generate a new value.\n- v := p.start\n- p.start++\n+ v := p.Start\n+ p.Start++\nreturn v, true\n}\n// Put returns a value to the pool.\n-func (p *pool) Put(v uint64) {\n+func (p *Pool) Put(v uint64) {\np.mu.Lock()\np.cache = append(p.cache, v)\np.mu.Unlock()\n" }, { "change_type": "RENAME", "old_path": "pkg/p9/pool_test.go", "new_path": "pkg/pool/pool_test.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package p9\n+package pool\nimport (\n\"testing\"\n)\nfunc TestPoolUnique(t *testing.T) {\n- p := pool{start: 1, limit: 3}\n+ p := Pool{Start: 1, Limit: 3}\ngot := make(map[uint64]bool)\nfor {\n@@ -39,7 +39,7 @@ func TestPoolUnique(t *testing.T) {\n}\nfunc TestExausted(t *testing.T) {\n- p := pool{start: 1, limit: 500}\n+ p := Pool{Start: 1, Limit: 500}\nfor i := 0; i < 499; i++ {\n_, ok := p.Get()\nif !ok {\n@@ -54,7 +54,7 @@ func TestExausted(t *testing.T) {\n}\nfunc TestPoolRecycle(t *testing.T) {\n- p := pool{start: 1, limit: 500}\n+ p := Pool{Start: 1, Limit: 500}\nn1, _ := p.Get()\np.Put(n1)\nn2, _ := p.Get()\n" } ]
Go
Apache License 2.0
google/gvisor
Move p9.pool to a separate package PiperOrigin-RevId: 293617493
259,858
06.02.2020 10:11:15
28,800
0e96fcafd4404e1418c84b7830b9455867e174bb
Fix test case on AMD. When ignored, the trap should be executed which generates a SIGSEGV as in the above case.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/32bit.cc", "new_path": "test/syscalls/linux/32bit.cc", "diff": "@@ -155,7 +155,7 @@ TEST(Syscall32Bit, Syscall) {\ncase PlatformSupport::Ignored:\n// See above.\nEXPECT_EXIT(ExitGroup32(kSyscall, kExitCode),\n- ::testing::KilledBySignal(SIGILL), \"\");\n+ ::testing::KilledBySignal(SIGSEGV), \"\");\nbreak;\ncase PlatformSupport::Allowed:\n" } ]
Go
Apache License 2.0
google/gvisor
Fix test case on AMD. When ignored, the trap should be executed which generates a SIGSEGV as in the above case. PiperOrigin-RevId: 293618489
260,004
06.02.2020 11:12:41
28,800
6bd59b4e08893281468e8af5aebb5fab0f7a8c0d
Update link address for targets of Neighbor Adverts Get the link address for the target of an NDP Neighbor Advertisement from the NDP Target Link Layer Address option. Tests: ipv6.TestNeighorAdvertisementWithTargetLinkLayerOption ipv6.TestNeighorAdvertisementWithInvalidTargetLinkLayerOption
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp.go", "new_path": "pkg/tcpip/network/ipv6/icmp.go", "diff": "package ipv6\nimport (\n+ \"log\"\n+\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -194,7 +196,11 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\n// TODO(b/148429853): Properly process the NS message and do Neighbor\n// Unreachability Detection.\nfor {\n- opt, done, _ := it.Next()\n+ opt, done, err := it.Next()\n+ if err != nil {\n+ // This should never happen as Iter(true) above did not return an error.\n+ log.Fatalf(\"unexpected error when iterating over NDP options: %s\", err)\n+ }\nif done {\nbreak\n}\n@@ -253,21 +259,25 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\n}\nna := header.NDPNeighborAdvert(h.NDPPayload())\n+ it, err := na.Options().Iter(true)\n+ if err != nil {\n+ // If we have a malformed NDP NA option, drop the packet.\n+ received.Invalid.Increment()\n+ return\n+ }\n+\ntargetAddr := na.TargetAddress()\nstack := r.Stack()\nrxNICID := r.NICID()\n- isTentative, err := stack.IsAddrTentative(rxNICID, targetAddr)\n- if err != nil {\n+ if isTentative, err := stack.IsAddrTentative(rxNICID, targetAddr); err != nil {\n// We will only get an error if rxNICID is unrecognized,\n// which should not happen. For now short-circuit this\n// packet.\n//\n// TODO(b/141002840): Handle this better?\nreturn\n- }\n-\n- if isTentative {\n+ } else if isTentative {\n// We just got an NA from a node that owns an address we\n// are performing DAD on, implying the address is not\n// unique. In this case we let the stack know so it can\n@@ -283,13 +293,29 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, pkt tcpip.P\n// scenario is beyond the scope of RFC 4862. As such, we simply\n// ignore such a scenario for now and proceed as normal.\n//\n+ // If the NA message has the target link layer option, update the link\n+ // address cache with the link address for the target of the message.\n+ //\n// TODO(b/143147598): Handle the scenario described above. Also\n// inform the netstack integration that a duplicate address was\n// detected outside of DAD.\n+ //\n+ // TODO(b/148429853): Properly process the NA message and do Neighbor\n+ // Unreachability Detection.\n+ for {\n+ opt, done, err := it.Next()\n+ if err != nil {\n+ // This should never happen as Iter(true) above did not return an error.\n+ log.Fatalf(\"unexpected error when iterating over NDP options: %s\", err)\n+ }\n+ if done {\n+ break\n+ }\n- e.linkAddrCache.AddLinkAddress(e.nicID, targetAddr, r.RemoteLinkAddress)\n- if targetAddr != r.RemoteAddress {\n- e.linkAddrCache.AddLinkAddress(e.nicID, r.RemoteAddress, r.RemoteLinkAddress)\n+ switch opt := opt.(type) {\n+ case header.NDPTargetLinkLayerAddressOption:\n+ e.linkAddrCache.AddLinkAddress(e.nicID, targetAddr, opt.EthernetAddress())\n+ }\n}\ncase header.ICMPv6EchoRequest:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -121,21 +121,60 @@ func TestICMPCounts(t *testing.T) {\n}\ndefer r.Release()\n+ var tllData [header.NDPLinkLayerAddressSize]byte\n+ header.NDPOptions(tllData[:]).Serialize(header.NDPOptionsSerializer{\n+ header.NDPTargetLinkLayerAddressOption(linkAddr1),\n+ })\n+\ntypes := []struct {\ntyp header.ICMPv6Type\nsize int\n+ extraData []byte\n}{\n- {header.ICMPv6DstUnreachable, header.ICMPv6DstUnreachableMinimumSize},\n- {header.ICMPv6PacketTooBig, header.ICMPv6PacketTooBigMinimumSize},\n- {header.ICMPv6TimeExceeded, header.ICMPv6MinimumSize},\n- {header.ICMPv6ParamProblem, header.ICMPv6MinimumSize},\n- {header.ICMPv6EchoRequest, header.ICMPv6EchoMinimumSize},\n- {header.ICMPv6EchoReply, header.ICMPv6EchoMinimumSize},\n- {header.ICMPv6RouterSolicit, header.ICMPv6MinimumSize},\n- {header.ICMPv6RouterAdvert, header.ICMPv6HeaderSize + header.NDPRAMinimumSize},\n- {header.ICMPv6NeighborSolicit, header.ICMPv6NeighborSolicitMinimumSize},\n- {header.ICMPv6NeighborAdvert, header.ICMPv6NeighborAdvertSize},\n- {header.ICMPv6RedirectMsg, header.ICMPv6MinimumSize},\n+ {\n+ typ: header.ICMPv6DstUnreachable,\n+ size: header.ICMPv6DstUnreachableMinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6PacketTooBig,\n+ size: header.ICMPv6PacketTooBigMinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6TimeExceeded,\n+ size: header.ICMPv6MinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6ParamProblem,\n+ size: header.ICMPv6MinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6EchoRequest,\n+ size: header.ICMPv6EchoMinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6EchoReply,\n+ size: header.ICMPv6EchoMinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6RouterSolicit,\n+ size: header.ICMPv6MinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6RouterAdvert,\n+ size: header.ICMPv6HeaderSize + header.NDPRAMinimumSize,\n+ },\n+ {\n+ typ: header.ICMPv6NeighborSolicit,\n+ size: header.ICMPv6NeighborSolicitMinimumSize},\n+ {\n+ typ: header.ICMPv6NeighborAdvert,\n+ size: header.ICMPv6NeighborAdvertMinimumSize,\n+ extraData: tllData[:],\n+ },\n+ {\n+ typ: header.ICMPv6RedirectMsg,\n+ size: header.ICMPv6MinimumSize,\n+ },\n}\nhandleIPv6Payload := func(hdr buffer.Prependable) {\n@@ -154,10 +193,13 @@ func TestICMPCounts(t *testing.T) {\n}\nfor _, typ := range types {\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size)\n+ extraDataLen := len(typ.extraData)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size + extraDataLen)\n+ extraData := buffer.View(hdr.Prepend(extraDataLen))\n+ copy(extraData, typ.extraData)\npkt := header.ICMPv6(hdr.Prepend(typ.size))\npkt.SetType(typ.typ)\n- pkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, extraData.ToVectorisedView()))\nhandleIPv6Payload(hdr)\n}\n@@ -372,97 +414,104 @@ func TestLinkResolution(t *testing.T) {\n}\nfunc TestICMPChecksumValidationSimple(t *testing.T) {\n+ var tllData [header.NDPLinkLayerAddressSize]byte\n+ header.NDPOptions(tllData[:]).Serialize(header.NDPOptionsSerializer{\n+ header.NDPTargetLinkLayerAddressOption(linkAddr1),\n+ })\n+\ntypes := []struct {\nname string\ntyp header.ICMPv6Type\nsize int\n+ extraData []byte\nstatCounter func(tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter\n}{\n{\n- \"DstUnreachable\",\n- header.ICMPv6DstUnreachable,\n- header.ICMPv6DstUnreachableMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"DstUnreachable\",\n+ typ: header.ICMPv6DstUnreachable,\n+ size: header.ICMPv6DstUnreachableMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.DstUnreachable\n},\n},\n{\n- \"PacketTooBig\",\n- header.ICMPv6PacketTooBig,\n- header.ICMPv6PacketTooBigMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"PacketTooBig\",\n+ typ: header.ICMPv6PacketTooBig,\n+ size: header.ICMPv6PacketTooBigMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.PacketTooBig\n},\n},\n{\n- \"TimeExceeded\",\n- header.ICMPv6TimeExceeded,\n- header.ICMPv6MinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"TimeExceeded\",\n+ typ: header.ICMPv6TimeExceeded,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.TimeExceeded\n},\n},\n{\n- \"ParamProblem\",\n- header.ICMPv6ParamProblem,\n- header.ICMPv6MinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"ParamProblem\",\n+ typ: header.ICMPv6ParamProblem,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.ParamProblem\n},\n},\n{\n- \"EchoRequest\",\n- header.ICMPv6EchoRequest,\n- header.ICMPv6EchoMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"EchoRequest\",\n+ typ: header.ICMPv6EchoRequest,\n+ size: header.ICMPv6EchoMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.EchoRequest\n},\n},\n{\n- \"EchoReply\",\n- header.ICMPv6EchoReply,\n- header.ICMPv6EchoMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"EchoReply\",\n+ typ: header.ICMPv6EchoReply,\n+ size: header.ICMPv6EchoMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.EchoReply\n},\n},\n{\n- \"RouterSolicit\",\n- header.ICMPv6RouterSolicit,\n- header.ICMPv6MinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"RouterSolicit\",\n+ typ: header.ICMPv6RouterSolicit,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RouterSolicit\n},\n},\n{\n- \"RouterAdvert\",\n- header.ICMPv6RouterAdvert,\n- header.ICMPv6HeaderSize + header.NDPRAMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"RouterAdvert\",\n+ typ: header.ICMPv6RouterAdvert,\n+ size: header.ICMPv6HeaderSize + header.NDPRAMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RouterAdvert\n},\n},\n{\n- \"NeighborSolicit\",\n- header.ICMPv6NeighborSolicit,\n- header.ICMPv6NeighborSolicitMinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"NeighborSolicit\",\n+ typ: header.ICMPv6NeighborSolicit,\n+ size: header.ICMPv6NeighborSolicitMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.NeighborSolicit\n},\n},\n{\n- \"NeighborAdvert\",\n- header.ICMPv6NeighborAdvert,\n- header.ICMPv6NeighborAdvertSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"NeighborAdvert\",\n+ typ: header.ICMPv6NeighborAdvert,\n+ size: header.ICMPv6NeighborAdvertMinimumSize,\n+ extraData: tllData[:],\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.NeighborAdvert\n},\n},\n{\n- \"RedirectMsg\",\n- header.ICMPv6RedirectMsg,\n- header.ICMPv6MinimumSize,\n- func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ name: \"RedirectMsg\",\n+ typ: header.ICMPv6RedirectMsg,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RedirectMsg\n},\n},\n@@ -494,16 +543,19 @@ func TestICMPChecksumValidationSimple(t *testing.T) {\n)\n}\n- handleIPv6Payload := func(typ header.ICMPv6Type, size int, checksum bool) {\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + size)\n- pkt := header.ICMPv6(hdr.Prepend(size))\n- pkt.SetType(typ)\n+ handleIPv6Payload := func(checksum bool) {\n+ extraDataLen := len(typ.extraData)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size + extraDataLen)\n+ extraData := buffer.View(hdr.Prepend(extraDataLen))\n+ copy(extraData, typ.extraData)\n+ pkt := header.ICMPv6(hdr.Prepend(typ.size))\n+ pkt.SetType(typ.typ)\nif checksum {\n- pkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, buffer.VectorisedView{}))\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, extraData.ToVectorisedView()))\n}\nip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\nip.Encode(&header.IPv6Fields{\n- PayloadLength: uint16(size),\n+ PayloadLength: uint16(typ.size + extraDataLen),\nNextHeader: uint8(header.ICMPv6ProtocolNumber),\nHopLimit: header.NDPHopLimit,\nSrcAddr: lladdr1,\n@@ -528,7 +580,7 @@ func TestICMPChecksumValidationSimple(t *testing.T) {\n// Without setting checksum, the incoming packet should\n// be invalid.\n- handleIPv6Payload(typ.typ, typ.size, false)\n+ handleIPv6Payload(false)\nif got := invalid.Value(); got != 1 {\nt.Fatalf(\"got invalid = %d, want = 1\", got)\n}\n@@ -538,7 +590,7 @@ func TestICMPChecksumValidationSimple(t *testing.T) {\n}\n// When checksum is set, it should be received.\n- handleIPv6Payload(typ.typ, typ.size, true)\n+ handleIPv6Payload(true)\nif got := typStat.Value(); got != 1 {\nt.Fatalf(\"got %s = %d, want = 1\", typ.name, got)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -70,12 +70,34 @@ func setupStackAndEndpoint(t *testing.T, llladdr, rlladdr tcpip.Address) (*stack\nreturn s, ep\n}\n-// TestNeighorSolicitationWithSourceLinkLayerOption tests that receiving an\n-// NDP NS message with the Source Link Layer Address option results in a\n+// TestNeighorSolicitationWithSourceLinkLayerOption tests that receiving a\n+// valid NDP NS message with the Source Link Layer Address option results in a\n// new entry in the link address cache for the sender of the message.\nfunc TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\nconst nicID = 1\n+ tests := []struct {\n+ name string\n+ optsBuf []byte\n+ expectedLinkAddr tcpip.LinkAddress\n+ }{\n+ {\n+ name: \"Valid\",\n+ optsBuf: []byte{1, 1, 2, 3, 4, 5, 6, 7},\n+ expectedLinkAddr: \"\\x02\\x03\\x04\\x05\\x06\\x07\",\n+ },\n+ {\n+ name: \"Too Small\",\n+ optsBuf: []byte{1, 1, 2, 3, 4, 5, 6},\n+ },\n+ {\n+ name: \"Invalid Length\",\n+ optsBuf: []byte{1, 2, 2, 3, 4, 5, 6, 7},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{NewProtocol()},\n})\n@@ -87,15 +109,14 @@ func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\nt.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, ProtocolNumber, lladdr0, err)\n}\n- ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize + header.NDPLinkLayerAddressSize\n+ ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize + len(test.optsBuf)\nhdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNSSize)\npkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\npkt.SetType(header.ICMPv6NeighborSolicit)\nns := header.NDPNeighborSolicit(pkt.NDPPayload())\nns.SetTargetAddress(lladdr0)\n- ns.Options().Serialize(header.NDPOptionsSerializer{\n- header.NDPSourceLinkLayerAddressOption(linkAddr1),\n- })\n+ opts := ns.Options()\n+ copy(opts, test.optsBuf)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, buffer.VectorisedView{}))\npayloadLength := hdr.UsedLength()\nip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n@@ -106,40 +127,75 @@ func TestNeighorSolicitationWithSourceLinkLayerOption(t *testing.T) {\nSrcAddr: lladdr1,\nDstAddr: lladdr0,\n})\n+\n+ invalid := s.Stats().ICMP.V6PacketsReceived.Invalid\n+\n+ // Invalid count should initially be 0.\n+ if got := invalid.Value(); got != 0 {\n+ t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ }\n+\ne.InjectInbound(ProtocolNumber, tcpip.PacketBuffer{\nData: hdr.View().ToVectorisedView(),\n})\nlinkAddr, c, err := s.GetLinkAddress(nicID, lladdr1, lladdr0, ProtocolNumber, nil)\n+ if linkAddr != test.expectedLinkAddr {\n+ t.Errorf(\"got link address = %s, want = %s\", linkAddr, test.expectedLinkAddr)\n+ }\n+\n+ if test.expectedLinkAddr != \"\" {\nif err != nil {\nt.Errorf(\"s.GetLinkAddress(%d, %s, %s, %d, nil): %s\", nicID, lladdr1, lladdr0, ProtocolNumber, err)\n}\nif c != nil {\nt.Errorf(\"got unexpected channel\")\n}\n- if linkAddr != linkAddr1 {\n- t.Errorf(\"got link address = %s, want = %s\", linkAddr, linkAddr1)\n+\n+ // Invalid count should not have increased.\n+ if got := invalid.Value(); got != 0 {\n+ t.Errorf(\"got invalid = %d, want = 0\", got)\n+ }\n+ } else {\n+ if err != tcpip.ErrWouldBlock {\n+ t.Errorf(\"got s.GetLinkAddress(%d, %s, %s, %d, nil) = (_, _, %v), want = (_, _, %s)\", nicID, lladdr1, lladdr0, ProtocolNumber, err, tcpip.ErrWouldBlock)\n+ }\n+ if c == nil {\n+ t.Errorf(\"expected channel from call to s.GetLinkAddress(%d, %s, %s, %d, nil)\", nicID, lladdr1, lladdr0, ProtocolNumber)\n+ }\n+\n+ // Invalid count should have increased.\n+ if got := invalid.Value(); got != 1 {\n+ t.Errorf(\"got invalid = %d, want = 1\", got)\n+ }\n+ }\n+ })\n}\n}\n-// TestNeighorSolicitationWithInvalidSourceLinkLayerOption tests that receiving\n-// an NDP NS message with an invalid Source Link Layer Address option does not\n-// result in a new entry in the link address cache for the sender of the\n-// message.\n-func TestNeighorSolicitationWithInvalidSourceLinkLayerOption(t *testing.T) {\n+// TestNeighorAdvertisementWithTargetLinkLayerOption tests that receiving a\n+// valid NDP NA message with the Target Link Layer Address option results in a\n+// new entry in the link address cache for the target of the message.\n+func TestNeighorAdvertisementWithTargetLinkLayerOption(t *testing.T) {\nconst nicID = 1\ntests := []struct {\nname string\noptsBuf []byte\n+ expectedLinkAddr tcpip.LinkAddress\n}{\n+ {\n+ name: \"Valid\",\n+ optsBuf: []byte{2, 1, 2, 3, 4, 5, 6, 7},\n+ expectedLinkAddr: \"\\x02\\x03\\x04\\x05\\x06\\x07\",\n+ },\n{\nname: \"Too Small\",\n- optsBuf: []byte{1, 1, 1, 2, 3, 4, 5},\n+ optsBuf: []byte{2, 1, 2, 3, 4, 5, 6},\n},\n{\nname: \"Invalid Length\",\n- optsBuf: []byte{1, 2, 1, 2, 3, 4, 5, 6},\n+ optsBuf: []byte{2, 2, 2, 3, 4, 5, 6, 7},\n},\n}\n@@ -156,12 +212,12 @@ func TestNeighorSolicitationWithInvalidSourceLinkLayerOption(t *testing.T) {\nt.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, ProtocolNumber, lladdr0, err)\n}\n- ndpNSSize := header.ICMPv6NeighborSolicitMinimumSize + len(test.optsBuf)\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNSSize)\n- pkt := header.ICMPv6(hdr.Prepend(ndpNSSize))\n- pkt.SetType(header.ICMPv6NeighborSolicit)\n- ns := header.NDPNeighborSolicit(pkt.NDPPayload())\n- ns.SetTargetAddress(lladdr0)\n+ ndpNASize := header.ICMPv6NeighborAdvertMinimumSize + len(test.optsBuf)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + ndpNASize)\n+ pkt := header.ICMPv6(hdr.Prepend(ndpNASize))\n+ pkt.SetType(header.ICMPv6NeighborAdvert)\n+ ns := header.NDPNeighborAdvert(pkt.NDPPayload())\n+ ns.SetTargetAddress(lladdr1)\nopts := ns.Options()\ncopy(opts, test.optsBuf)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, lladdr1, lladdr0, buffer.VectorisedView{}))\n@@ -186,20 +242,35 @@ func TestNeighorSolicitationWithInvalidSourceLinkLayerOption(t *testing.T) {\nData: hdr.View().ToVectorisedView(),\n})\n- // Invalid count should have increased.\n- if got := invalid.Value(); got != 1 {\n- t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ linkAddr, c, err := s.GetLinkAddress(nicID, lladdr1, lladdr0, ProtocolNumber, nil)\n+ if linkAddr != test.expectedLinkAddr {\n+ t.Errorf(\"got link address = %s, want = %s\", linkAddr, test.expectedLinkAddr)\n}\n- linkAddr, c, err := s.GetLinkAddress(nicID, lladdr1, lladdr0, ProtocolNumber, nil)\n+ if test.expectedLinkAddr != \"\" {\n+ if err != nil {\n+ t.Errorf(\"s.GetLinkAddress(%d, %s, %s, %d, nil): %s\", nicID, lladdr1, lladdr0, ProtocolNumber, err)\n+ }\n+ if c != nil {\n+ t.Errorf(\"got unexpected channel\")\n+ }\n+\n+ // Invalid count should not have increased.\n+ if got := invalid.Value(); got != 0 {\n+ t.Errorf(\"got invalid = %d, want = 0\", got)\n+ }\n+ } else {\nif err != tcpip.ErrWouldBlock {\nt.Errorf(\"got s.GetLinkAddress(%d, %s, %s, %d, nil) = (_, _, %v), want = (_, _, %s)\", nicID, lladdr1, lladdr0, ProtocolNumber, err, tcpip.ErrWouldBlock)\n}\nif c == nil {\nt.Errorf(\"expected channel from call to s.GetLinkAddress(%d, %s, %s, %d, nil)\", nicID, lladdr1, lladdr0, ProtocolNumber)\n}\n- if linkAddr != \"\" {\n- t.Errorf(\"got s.GetLinkAddress(%d, %s, %s, %d, nil) = (%s, _, ), want = ('', _, _)\", nicID, lladdr1, lladdr0, ProtocolNumber, linkAddr)\n+\n+ // Invalid count should have increased.\n+ if got := invalid.Value(); got != 1 {\n+ t.Errorf(\"got invalid = %d, want = 1\", got)\n+ }\n}\n})\n}\n@@ -238,27 +309,59 @@ func TestHopLimitValidation(t *testing.T) {\n})\n}\n+ var tllData [header.NDPLinkLayerAddressSize]byte\n+ header.NDPOptions(tllData[:]).Serialize(header.NDPOptionsSerializer{\n+ header.NDPTargetLinkLayerAddressOption(linkAddr1),\n+ })\n+\ntypes := []struct {\nname string\ntyp header.ICMPv6Type\nsize int\n+ extraData []byte\nstatCounter func(tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter\n}{\n- {\"RouterSolicit\", header.ICMPv6RouterSolicit, header.ICMPv6MinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ {\n+ name: \"RouterSolicit\",\n+ typ: header.ICMPv6RouterSolicit,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RouterSolicit\n- }},\n- {\"RouterAdvert\", header.ICMPv6RouterAdvert, header.ICMPv6HeaderSize + header.NDPRAMinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ },\n+ },\n+ {\n+ name: \"RouterAdvert\",\n+ typ: header.ICMPv6RouterAdvert,\n+ size: header.ICMPv6HeaderSize + header.NDPRAMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RouterAdvert\n- }},\n- {\"NeighborSolicit\", header.ICMPv6NeighborSolicit, header.ICMPv6NeighborSolicitMinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ },\n+ },\n+ {\n+ name: \"NeighborSolicit\",\n+ typ: header.ICMPv6NeighborSolicit,\n+ size: header.ICMPv6NeighborSolicitMinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.NeighborSolicit\n- }},\n- {\"NeighborAdvert\", header.ICMPv6NeighborAdvert, header.ICMPv6NeighborAdvertSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ },\n+ },\n+ {\n+ name: \"NeighborAdvert\",\n+ typ: header.ICMPv6NeighborAdvert,\n+ size: header.ICMPv6NeighborAdvertMinimumSize,\n+ extraData: tllData[:],\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.NeighborAdvert\n- }},\n- {\"RedirectMsg\", header.ICMPv6RedirectMsg, header.ICMPv6MinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ },\n+ },\n+ {\n+ name: \"RedirectMsg\",\n+ typ: header.ICMPv6RedirectMsg,\n+ size: header.ICMPv6MinimumSize,\n+ statCounter: func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\nreturn stats.RedirectMsg\n- }},\n+ },\n+ },\n}\nfor _, typ := range types {\n@@ -270,10 +373,13 @@ func TestHopLimitValidation(t *testing.T) {\ninvalid := stats.Invalid\ntypStat := typ.statCounter(stats)\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size)\n+ extraDataLen := len(typ.extraData)\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size + extraDataLen)\n+ extraData := buffer.View(hdr.Prepend(extraDataLen))\n+ copy(extraData, typ.extraData)\npkt := header.ICMPv6(hdr.Prepend(typ.size))\npkt.SetType(typ.typ)\n- pkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, extraData.ToVectorisedView()))\n// Invalid count should initially be 0.\nif got := invalid.Value(); got != 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -478,13 +478,17 @@ func TestDADFail(t *testing.T) {\n{\n\"RxAdvert\",\nfunc(tgt tcpip.Address) buffer.Prependable {\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + header.ICMPv6NeighborAdvertSize)\n- pkt := header.ICMPv6(hdr.Prepend(header.ICMPv6NeighborAdvertSize))\n+ naSize := header.ICMPv6NeighborAdvertMinimumSize + header.NDPLinkLayerAddressSize\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + naSize)\n+ pkt := header.ICMPv6(hdr.Prepend(naSize))\npkt.SetType(header.ICMPv6NeighborAdvert)\nna := header.NDPNeighborAdvert(pkt.NDPPayload())\nna.SetSolicitedFlag(true)\nna.SetOverrideFlag(true)\nna.SetTargetAddress(tgt)\n+ na.Options().Serialize(header.NDPOptionsSerializer{\n+ header.NDPTargetLinkLayerAddressOption(linkAddr1),\n+ })\npkt.SetChecksum(header.ICMPv6Checksum(pkt, tgt, header.IPv6AllNodesMulticastAddress, buffer.VectorisedView{}))\npayloadLength := hdr.UsedLength()\nip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n" } ]
Go
Apache License 2.0
google/gvisor
Update link address for targets of Neighbor Adverts Get the link address for the target of an NDP Neighbor Advertisement from the NDP Target Link Layer Address option. Tests: - ipv6.TestNeighorAdvertisementWithTargetLinkLayerOption - ipv6.TestNeighorAdvertisementWithInvalidTargetLinkLayerOption PiperOrigin-RevId: 293632609
259,853
06.02.2020 14:01:45
28,800
615d66111214f5ae9b41fb2a89bb3549c03fc7af
runsc/container_test: hide host /etc in test containers The host /etc can contain config files which affect tests. For example, bash reads /etc/passwd and if it is too big a test can fail by timeout.
[ { "change_type": "MODIFY", "old_path": "runsc/testutil/testutil.go", "new_path": "runsc/testutil/testutil.go", "diff": "@@ -119,6 +119,13 @@ func NewSpecWithArgs(args ...string) *specs.Spec {\nCapabilities: specutils.AllCapabilities(),\n},\nMounts: []specs.Mount{\n+ // Hide the host /etc to avoid any side-effects.\n+ // For example, bash reads /etc/passwd and if it is\n+ // very big, tests can fail by timeout.\n+ {\n+ Type: \"tmpfs\",\n+ Destination: \"/etc\",\n+ },\n// Root is readonly, but many tests want to write to tmpdir.\n// This creates a writable mount inside the root. Also, when tmpdir points\n// to \"/tmp\", it makes the the actual /tmp to be mounted and not a tmpfs\n" } ]
Go
Apache License 2.0
google/gvisor
runsc/container_test: hide host /etc in test containers The host /etc can contain config files which affect tests. For example, bash reads /etc/passwd and if it is too big a test can fail by timeout. PiperOrigin-RevId: 293670637
259,891
06.02.2020 14:26:41
28,800
bfa4a235f401599492a2cf39471df62715f9f1cf
Fix `bazel run` target in docs.
[ { "change_type": "MODIFY", "old_path": "test/iptables/README.md", "new_path": "test/iptables/README.md", "diff": "@@ -28,7 +28,7 @@ Your test is now runnable with bazel!\nBuild the testing Docker container:\n```bash\n-$ bazel run //test/iptables/runner-image -- --norun\n+$ bazel run //test/iptables/runner:runner-image -- --norun\n```\nRun an individual test via:\n" } ]
Go
Apache License 2.0
google/gvisor
Fix `bazel run` target in docs. PiperOrigin-RevId: 293676954
260,004
06.02.2020 15:57:34
28,800
940d255971c38af9f91ceed1345fd973f8fdb41d
Perform DAD on IPv6 addresses when enabling a NIC Addresses may be added before a NIC is enabled. Make sure DAD is performed on the permanent IPv6 addresses when they get enabled. Test: stack_test.TestDoDADWhenNICEnabled stack.TestDisabledRxStatsWhenNICDisabled
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -78,11 +78,15 @@ go_test(\ngo_test(\nname = \"stack_test\",\nsize = \"small\",\n- srcs = [\"linkaddrcache_test.go\"],\n+ srcs = [\n+ \"linkaddrcache_test.go\",\n+ \"nic_test.go\",\n+ ],\nlibrary = \":stack\",\ndeps = [\n\"//pkg/sleep\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -1539,7 +1539,7 @@ func TestPrefixDiscoveryMaxOnLinkPrefixes(t *testing.T) {\n}\n// Checks to see if list contains an IPv6 address, item.\n-func contains(list []tcpip.ProtocolAddress, item tcpip.AddressWithPrefix) bool {\n+func containsV6Addr(list []tcpip.ProtocolAddress, item tcpip.AddressWithPrefix) bool {\nprotocolAddress := tcpip.ProtocolAddress{\nProtocol: header.IPv6ProtocolNumber,\nAddressWithPrefix: item,\n@@ -1665,7 +1665,7 @@ func TestAutoGenAddr(t *testing.T) {\n// with non-zero lifetime.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix1, true, true, 100, 0))\nexpectAutoGenAddrEvent(addr1, newAddr)\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr1) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr1)\n}\n@@ -1681,10 +1681,10 @@ func TestAutoGenAddr(t *testing.T) {\n// Receive an RA with prefix2 in a PI.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix2, true, true, 100, 0))\nexpectAutoGenAddrEvent(addr2, newAddr)\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr1) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr2) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr2)\n}\n@@ -1705,10 +1705,10 @@ func TestAutoGenAddr(t *testing.T) {\ncase <-time.After(newMinVLDuration + defaultAsyncEventTimeout):\nt.Fatal(\"timed out waiting for addr auto gen event\")\n}\n- if contains(s.NICInfo()[1].ProtocolAddresses, addr1) {\n+ if containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr1) {\nt.Fatalf(\"Should not have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr2) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr2)\n}\n}\n@@ -1853,7 +1853,7 @@ func TestAutoGenAddrDeprecateFromPI(t *testing.T) {\n// Receive PI for prefix1.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix1, true, true, 100, 100))\nexpectAutoGenAddrEvent(addr1, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should have %s in the list of addresses\", addr1)\n}\nexpectPrimaryAddr(addr1)\n@@ -1861,7 +1861,7 @@ func TestAutoGenAddrDeprecateFromPI(t *testing.T) {\n// Deprecate addr for prefix1 immedaitely.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix1, true, true, 100, 0))\nexpectAutoGenAddrEvent(addr1, deprecatedAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should have %s in the list of addresses\", addr1)\n}\n// addr should still be the primary endpoint as there are no other addresses.\n@@ -1879,7 +1879,7 @@ func TestAutoGenAddrDeprecateFromPI(t *testing.T) {\n// Receive PI for prefix2.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix2, true, true, 100, 100))\nexpectAutoGenAddrEvent(addr2, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\nexpectPrimaryAddr(addr2)\n@@ -1887,7 +1887,7 @@ func TestAutoGenAddrDeprecateFromPI(t *testing.T) {\n// Deprecate addr for prefix2 immedaitely.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix2, true, true, 100, 0))\nexpectAutoGenAddrEvent(addr2, deprecatedAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\n// addr1 should be the primary endpoint now since addr2 is deprecated but\n@@ -1982,7 +1982,7 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\n// Receive PI for prefix2.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix2, true, true, 100, 100))\nexpectAutoGenAddrEvent(addr2, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\nexpectPrimaryAddr(addr2)\n@@ -1990,10 +1990,10 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\n// Receive a PI for prefix1.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix1, true, true, 100, 90))\nexpectAutoGenAddrEvent(addr1, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\nexpectPrimaryAddr(addr1)\n@@ -2009,10 +2009,10 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\n// Wait for addr of prefix1 to be deprecated.\nexpectAutoGenAddrEventAfter(addr1, deprecatedAddr, newMinVLDuration-time.Second+defaultAsyncEventTimeout)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\n// addr2 should be the primary endpoint now since addr1 is deprecated but\n@@ -2049,10 +2049,10 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\n// Wait for addr of prefix1 to be deprecated.\nexpectAutoGenAddrEventAfter(addr1, deprecatedAddr, newMinVLDuration-time.Second+defaultAsyncEventTimeout)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\n// addr2 should be the primary endpoint now since it is not deprecated.\n@@ -2063,10 +2063,10 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\n// Wait for addr of prefix1 to be invalidated.\nexpectAutoGenAddrEventAfter(addr1, invalidatedAddr, time.Second+defaultAsyncEventTimeout)\n- if contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\nexpectPrimaryAddr(addr2)\n@@ -2112,10 +2112,10 @@ func TestAutoGenAddrTimerDeprecation(t *testing.T) {\ncase <-time.After(newMinVLDuration + defaultAsyncEventTimeout):\nt.Fatal(\"timed out waiting for addr auto gen event\")\n}\n- if contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr1)\n}\n- if contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr2)\n}\n// Should not have any primary endpoints.\n@@ -2600,7 +2600,7 @@ func TestAutoGenAddrStaticConflict(t *testing.T) {\nif err := s.AddProtocolAddress(1, tcpip.ProtocolAddress{Protocol: header.IPv6ProtocolNumber, AddressWithPrefix: addr}); err != nil {\nt.Fatalf(\"AddAddress(_, %d, %s) = %s\", header.IPv6ProtocolNumber, addr.Address, err)\n}\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr1)\n}\n@@ -2613,7 +2613,7 @@ func TestAutoGenAddrStaticConflict(t *testing.T) {\nt.Fatal(\"unexpectedly received an auto gen addr event for an address we already have statically\")\ndefault:\n}\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr1)\n}\n@@ -2624,7 +2624,7 @@ func TestAutoGenAddrStaticConflict(t *testing.T) {\nt.Fatal(\"unexpectedly received an auto gen addr event\")\ncase <-time.After(lifetimeSeconds*time.Second + defaultTimeout):\n}\n- if !contains(s.NICInfo()[1].ProtocolAddresses, addr) {\n+ if !containsV6Addr(s.NICInfo()[1].ProtocolAddresses, addr) {\nt.Fatalf(\"Should have %s in the list of addresses\", addr1)\n}\n}\n@@ -2702,17 +2702,17 @@ func TestAutoGenAddrWithOpaqueIID(t *testing.T) {\nconst validLifetimeSecondPrefix1 = 1\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix1, true, true, validLifetimeSecondPrefix1, 0))\nexpectAutoGenAddrEvent(addr1, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should have %s in the list of addresses\", addr1)\n}\n// Receive an RA with prefix2 in a PI with a large valid lifetime.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr2, 0, prefix2, true, true, 100, 0))\nexpectAutoGenAddrEvent(addr2, newAddr)\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\n@@ -2725,10 +2725,10 @@ func TestAutoGenAddrWithOpaqueIID(t *testing.T) {\ncase <-time.After(validLifetimeSecondPrefix1*time.Second + defaultAsyncEventTimeout):\nt.Fatal(\"timed out waiting for addr auto gen event\")\n}\n- if contains(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\n+ if containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr1) {\nt.Fatalf(\"should not have %s in the list of addresses\", addr1)\n}\n- if !contains(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\n+ if !containsV6Addr(s.NICInfo()[nicID].ProtocolAddresses, addr2) {\nt.Fatalf(\"should have %s in the list of addresses\", addr2)\n}\n}\n@@ -3014,16 +3014,16 @@ func TestCleanupHostOnlyStateOnBecomingRouter(t *testing.T) {\nnicinfo := s.NICInfo()\nnic1Addrs := nicinfo[nicID1].ProtocolAddresses\nnic2Addrs := nicinfo[nicID2].ProtocolAddresses\n- if !contains(nic1Addrs, e1Addr1) {\n+ if !containsV6Addr(nic1Addrs, e1Addr1) {\nt.Errorf(\"missing %s from the list of addresses for NIC(%d): %+v\", e1Addr1, nicID1, nic1Addrs)\n}\n- if !contains(nic1Addrs, e1Addr2) {\n+ if !containsV6Addr(nic1Addrs, e1Addr2) {\nt.Errorf(\"missing %s from the list of addresses for NIC(%d): %+v\", e1Addr2, nicID1, nic1Addrs)\n}\n- if !contains(nic2Addrs, e2Addr1) {\n+ if !containsV6Addr(nic2Addrs, e2Addr1) {\nt.Errorf(\"missing %s from the list of addresses for NIC(%d): %+v\", e2Addr1, nicID2, nic2Addrs)\n}\n- if !contains(nic2Addrs, e2Addr2) {\n+ if !containsV6Addr(nic2Addrs, e2Addr2) {\nt.Errorf(\"missing %s from the list of addresses for NIC(%d): %+v\", e2Addr2, nicID2, nic2Addrs)\n}\n@@ -3102,16 +3102,16 @@ func TestCleanupHostOnlyStateOnBecomingRouter(t *testing.T) {\nnicinfo = s.NICInfo()\nnic1Addrs = nicinfo[nicID1].ProtocolAddresses\nnic2Addrs = nicinfo[nicID2].ProtocolAddresses\n- if contains(nic1Addrs, e1Addr1) {\n+ if containsV6Addr(nic1Addrs, e1Addr1) {\nt.Errorf(\"still have %s in the list of addresses for NIC(%d): %+v\", e1Addr1, nicID1, nic1Addrs)\n}\n- if contains(nic1Addrs, e1Addr2) {\n+ if containsV6Addr(nic1Addrs, e1Addr2) {\nt.Errorf(\"still have %s in the list of addresses for NIC(%d): %+v\", e1Addr2, nicID1, nic1Addrs)\n}\n- if contains(nic2Addrs, e2Addr1) {\n+ if containsV6Addr(nic2Addrs, e2Addr1) {\nt.Errorf(\"still have %s in the list of addresses for NIC(%d): %+v\", e2Addr1, nicID2, nic2Addrs)\n}\n- if contains(nic2Addrs, e2Addr2) {\n+ if containsV6Addr(nic2Addrs, e2Addr2) {\nt.Errorf(\"still have %s in the list of addresses for NIC(%d): %+v\", e2Addr2, nicID2, nic2Addrs)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -16,6 +16,7 @@ package stack\nimport (\n\"log\"\n+ \"reflect\"\n\"sort\"\n\"strings\"\n\"sync/atomic\"\n@@ -39,6 +40,7 @@ type NIC struct {\nmu struct {\nsync.RWMutex\n+ enabled bool\nspoofing bool\npromiscuous bool\nprimary map[tcpip.NetworkProtocolNumber][]*referencedNetworkEndpoint\n@@ -56,6 +58,14 @@ type NIC struct {\ntype NICStats struct {\nTx DirectionStats\nRx DirectionStats\n+\n+ DisabledRx DirectionStats\n+}\n+\n+func makeNICStats() NICStats {\n+ var s NICStats\n+ tcpip.InitStatCounters(reflect.ValueOf(&s).Elem())\n+ return s\n}\n// DirectionStats includes packet and byte counts.\n@@ -99,16 +109,7 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\nname: name,\nlinkEP: ep,\ncontext: ctx,\n- stats: NICStats{\n- Tx: DirectionStats{\n- Packets: &tcpip.StatCounter{},\n- Bytes: &tcpip.StatCounter{},\n- },\n- Rx: DirectionStats{\n- Packets: &tcpip.StatCounter{},\n- Bytes: &tcpip.StatCounter{},\n- },\n- },\n+ stats: makeNICStats(),\n}\nnic.mu.primary = make(map[tcpip.NetworkProtocolNumber][]*referencedNetworkEndpoint)\nnic.mu.endpoints = make(map[NetworkEndpointID]*referencedNetworkEndpoint)\n@@ -137,14 +138,30 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\n// enable enables the NIC. enable will attach the link to its LinkEndpoint and\n// join the IPv6 All-Nodes Multicast address (ff02::1).\nfunc (n *NIC) enable() *tcpip.Error {\n+ n.mu.RLock()\n+ enabled := n.mu.enabled\n+ n.mu.RUnlock()\n+ if enabled {\n+ return nil\n+ }\n+\n+ n.mu.Lock()\n+ defer n.mu.Unlock()\n+\n+ if n.mu.enabled {\n+ return nil\n+ }\n+\n+ n.mu.enabled = true\n+\nn.attachLinkEndpoint()\n// Create an endpoint to receive broadcast packets on this interface.\nif _, ok := n.stack.networkProtocols[header.IPv4ProtocolNumber]; ok {\n- if err := n.AddAddress(tcpip.ProtocolAddress{\n+ if _, err := n.addAddressLocked(tcpip.ProtocolAddress{\nProtocol: header.IPv4ProtocolNumber,\nAddressWithPrefix: tcpip.AddressWithPrefix{header.IPv4Broadcast, 8 * header.IPv4AddressSize},\n- }, NeverPrimaryEndpoint); err != nil {\n+ }, NeverPrimaryEndpoint, permanent, static, false /* deprecated */); err != nil {\nreturn err\n}\n}\n@@ -166,8 +183,22 @@ func (n *NIC) enable() *tcpip.Error {\nreturn nil\n}\n- n.mu.Lock()\n- defer n.mu.Unlock()\n+ // Perform DAD on the all the unicast IPv6 endpoints that are in the permanent\n+ // state.\n+ //\n+ // Addresses may have aleady completed DAD but in the time since the NIC was\n+ // last enabled, other devices may have acquired the same addresses.\n+ for _, r := range n.mu.endpoints {\n+ addr := r.ep.ID().LocalAddress\n+ if k := r.getKind(); (k != permanent && k != permanentTentative) || !header.IsV6UnicastAddress(addr) {\n+ continue\n+ }\n+\n+ r.setKind(permanentTentative)\n+ if err := n.mu.ndp.startDuplicateAddressDetection(addr, r); err != nil {\n+ return err\n+ }\n+ }\nif err := n.joinGroupLocked(header.IPv6ProtocolNumber, header.IPv6AllNodesMulticastAddress); err != nil {\nreturn err\n@@ -633,7 +664,9 @@ func (n *NIC) addAddressLocked(protocolAddress tcpip.ProtocolAddress, peb Primar\nisIPv6Unicast := protocolAddress.Protocol == header.IPv6ProtocolNumber && header.IsV6UnicastAddress(protocolAddress.AddressWithPrefix.Address)\n// If the address is an IPv6 address and it is a permanent address,\n- // mark it as tentative so it goes through the DAD process.\n+ // mark it as tentative so it goes through the DAD process if the NIC is\n+ // enabled. If the NIC is not enabled, DAD will be started when the NIC is\n+ // enabled.\nif isIPv6Unicast && kind == permanent {\nkind = permanentTentative\n}\n@@ -668,8 +701,8 @@ func (n *NIC) addAddressLocked(protocolAddress tcpip.ProtocolAddress, peb Primar\nn.insertPrimaryEndpointLocked(ref, peb)\n- // If we are adding a tentative IPv6 address, start DAD.\n- if isIPv6Unicast && kind == permanentTentative {\n+ // If we are adding a tentative IPv6 address, start DAD if the NIC is enabled.\n+ if isIPv6Unicast && kind == permanentTentative && n.mu.enabled {\nif err := n.mu.ndp.startDuplicateAddressDetection(protocolAddress.AddressWithPrefix.Address, ref); err != nil {\nreturn nil, err\n}\n@@ -700,9 +733,7 @@ func (n *NIC) AllAddresses() []tcpip.ProtocolAddress {\n// Don't include tentative, expired or temporary endpoints to\n// avoid confusion and prevent the caller from using those.\nswitch ref.getKind() {\n- case permanentTentative, permanentExpired, temporary:\n- // TODO(b/140898488): Should tentative addresses be\n- // returned?\n+ case permanentExpired, temporary:\ncontinue\n}\naddrs = append(addrs, tcpip.ProtocolAddress{\n@@ -1016,11 +1047,23 @@ func handlePacket(protocol tcpip.NetworkProtocolNumber, dst, src tcpip.Address,\n// This rule applies only to the slice itself, not to the items of the slice;\n// the ownership of the items is not retained by the caller.\nfunc (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt tcpip.PacketBuffer) {\n+ n.mu.RLock()\n+ enabled := n.mu.enabled\n+ // If the NIC is not yet enabled, don't receive any packets.\n+ if !enabled {\n+ n.mu.RUnlock()\n+\n+ n.stats.DisabledRx.Packets.Increment()\n+ n.stats.DisabledRx.Bytes.IncrementBy(uint64(pkt.Data.Size()))\n+ return\n+ }\n+\nn.stats.Rx.Packets.Increment()\nn.stats.Rx.Bytes.IncrementBy(uint64(pkt.Data.Size()))\nnetProto, ok := n.stack.networkProtocols[protocol]\nif !ok {\n+ n.mu.RUnlock()\nn.stack.stats.UnknownProtocolRcvdPackets.Increment()\nreturn\n}\n@@ -1032,7 +1075,6 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\n}\n// Are any packet sockets listening for this network protocol?\n- n.mu.RLock()\npacketEPs := n.mu.packetEPs[protocol]\n// Check whether there are packet sockets listening for every protocol.\n// If we received a packet with protocol EthernetProtocolAll, then the\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/stack/nic_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package stack\n+\n+import (\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+)\n+\n+func TestDisabledRxStatsWhenNICDisabled(t *testing.T) {\n+ // When the NIC is disabled, the only field that matters is the stats field.\n+ // This test is limited to stats counter checks.\n+ nic := NIC{\n+ stats: makeNICStats(),\n+ }\n+\n+ if got := nic.stats.DisabledRx.Packets.Value(); got != 0 {\n+ t.Errorf(\"got DisabledRx.Packets = %d, want = 0\", got)\n+ }\n+ if got := nic.stats.DisabledRx.Bytes.Value(); got != 0 {\n+ t.Errorf(\"got DisabledRx.Bytes = %d, want = 0\", got)\n+ }\n+ if got := nic.stats.Rx.Packets.Value(); got != 0 {\n+ t.Errorf(\"got Rx.Packets = %d, want = 0\", got)\n+ }\n+ if got := nic.stats.Rx.Bytes.Value(); got != 0 {\n+ t.Errorf(\"got Rx.Bytes = %d, want = 0\", got)\n+ }\n+\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+\n+ nic.DeliverNetworkPacket(nil, \"\", \"\", 0, tcpip.PacketBuffer{Data: buffer.View([]byte{1, 2, 3, 4}).ToVectorisedView()})\n+\n+ if got := nic.stats.DisabledRx.Packets.Value(); got != 1 {\n+ t.Errorf(\"got DisabledRx.Packets = %d, want = 1\", got)\n+ }\n+ if got := nic.stats.DisabledRx.Bytes.Value(); got != 4 {\n+ t.Errorf(\"got DisabledRx.Bytes = %d, want = 4\", got)\n+ }\n+ if got := nic.stats.Rx.Packets.Value(); got != 0 {\n+ t.Errorf(\"got Rx.Packets = %d, want = 0\", got)\n+ }\n+ if got := nic.stats.Rx.Bytes.Value(); got != 0 {\n+ t.Errorf(\"got Rx.Bytes = %d, want = 0\", got)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2561,3 +2561,118 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\n})\n}\n}\n+\n+// TestDoDADWhenNICEnabled tests that IPv6 endpoints that were added while a NIC\n+// was disabled have DAD performed on them when the NIC is enabled.\n+func TestDoDADWhenNICEnabled(t *testing.T) {\n+ t.Parallel()\n+\n+ const dadTransmits = 1\n+ const retransmitTimer = time.Second\n+ const nicID = 1\n+\n+ ndpDisp := ndpDispatcher{\n+ dadC: make(chan ndpDADEvent),\n+ }\n+ opts := stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n+ NDPConfigs: stack.NDPConfigurations{\n+ DupAddrDetectTransmits: dadTransmits,\n+ RetransmitTimer: retransmitTimer,\n+ },\n+ NDPDisp: &ndpDisp,\n+ }\n+\n+ e := channel.New(dadTransmits, 1280, linkAddr1)\n+ s := stack.New(opts)\n+ nicOpts := stack.NICOptions{Disabled: true}\n+ if err := s.CreateNICWithOptions(nicID, e, nicOpts); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _, %+v) = %s\", nicID, nicOpts, err)\n+ }\n+\n+ addr := tcpip.ProtocolAddress{\n+ Protocol: header.IPv6ProtocolNumber,\n+ AddressWithPrefix: tcpip.AddressWithPrefix{\n+ Address: llAddr1,\n+ PrefixLen: 128,\n+ },\n+ }\n+ if err := s.AddProtocolAddress(nicID, addr); err != nil {\n+ t.Fatalf(\"AddProtocolAddress(%d, %+v): %s\", nicID, addr, err)\n+ }\n+\n+ // Address should be in the list of all addresses.\n+ if addrs := s.AllAddresses()[nicID]; !containsV6Addr(addrs, addr.AddressWithPrefix) {\n+ t.Fatalf(\"got s.AllAddresses()[%d] = %+v, want = %+v\", nicID, addrs, addr)\n+ }\n+\n+ // Address should be tentative so it should not be a main address.\n+ got, err := s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (_, %v), want = (_, nil)\", nicID, header.IPv6ProtocolNumber, err)\n+ }\n+ if want := (tcpip.AddressWithPrefix{}); got != want {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (%s, nil), want = (%s, nil)\", nicID, header.IPv6ProtocolNumber, got, want)\n+ }\n+\n+ // Enabling the NIC should start DAD for the address.\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n+ }\n+ if addrs := s.AllAddresses()[nicID]; !containsV6Addr(addrs, addr.AddressWithPrefix) {\n+ t.Fatalf(\"got s.AllAddresses()[%d] = %+v, want = %+v\", nicID, addrs, addr)\n+ }\n+\n+ // Address should not be considered bound to the NIC yet (DAD ongoing).\n+ got, err = s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (_, %v), want = (_, nil)\", nicID, header.IPv6ProtocolNumber, err)\n+ }\n+ if want := (tcpip.AddressWithPrefix{}); got != want {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (%s, nil), want = (%s, nil)\", nicID, header.IPv6ProtocolNumber, got, want)\n+ }\n+\n+ // Wait for DAD to resolve.\n+ select {\n+ case <-time.After(dadTransmits*retransmitTimer + defaultAsyncEventTimeout):\n+ t.Fatal(\"timed out waiting for DAD resolution\")\n+ case e := <-ndpDisp.dadC:\n+ if e.err != nil {\n+ t.Fatal(\"got DAD error: \", e.err)\n+ }\n+ if e.nicID != nicID {\n+ t.Fatalf(\"got DAD event w/ nicID = %d, want = %d\", e.nicID, nicID)\n+ }\n+ if e.addr != addr.AddressWithPrefix.Address {\n+ t.Fatalf(\"got DAD event w/ addr = %s, want = %s\", e.addr, addr.AddressWithPrefix.Address)\n+ }\n+ if !e.resolved {\n+ t.Fatal(\"got DAD event w/ resolved = false, want = true\")\n+ }\n+ }\n+ if addrs := s.AllAddresses()[nicID]; !containsV6Addr(addrs, addr.AddressWithPrefix) {\n+ t.Fatalf(\"got s.AllAddresses()[%d] = %+v, want = %+v\", nicID, addrs, addr)\n+ }\n+ got, err = s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (_, %v), want = (_, nil)\", nicID, header.IPv6ProtocolNumber, err)\n+ }\n+ if got != addr.AddressWithPrefix {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = %s, want = %s\", nicID, header.IPv6ProtocolNumber, got, addr.AddressWithPrefix)\n+ }\n+\n+ // Enabling the NIC again should be a no-op.\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n+ }\n+ if addrs := s.AllAddresses()[nicID]; !containsV6Addr(addrs, addr.AddressWithPrefix) {\n+ t.Fatalf(\"got s.AllAddresses()[%d] = %+v, want = %+v\", nicID, addrs, addr)\n+ }\n+ got, err = s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (_, %v), want = (_, nil)\", nicID, header.IPv6ProtocolNumber, err)\n+ }\n+ if got != addr.AddressWithPrefix {\n+ t.Fatalf(\"got stack.GetMainNICAddress(%d, %d) = (%s, nil), want = (%s, nil)\", nicID, header.IPv6ProtocolNumber, got, addr.AddressWithPrefix)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -1170,7 +1170,9 @@ type TransportEndpointStats struct {\n// marker interface.\nfunc (*TransportEndpointStats) IsEndpointStats() {}\n-func fillIn(v reflect.Value) {\n+// InitStatCounters initializes v's fields with nil StatCounter fields to new\n+// StatCounters.\n+func InitStatCounters(v reflect.Value) {\nfor i := 0; i < v.NumField(); i++ {\nv := v.Field(i)\nif s, ok := v.Addr().Interface().(**StatCounter); ok {\n@@ -1178,14 +1180,14 @@ func fillIn(v reflect.Value) {\n*s = new(StatCounter)\n}\n} else {\n- fillIn(v)\n+ InitStatCounters(v)\n}\n}\n}\n// FillIn returns a copy of s with nil fields initialized to new StatCounters.\nfunc (s Stats) FillIn() Stats {\n- fillIn(reflect.ValueOf(&s).Elem())\n+ InitStatCounters(reflect.ValueOf(&s).Elem())\nreturn s\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Perform DAD on IPv6 addresses when enabling a NIC Addresses may be added before a NIC is enabled. Make sure DAD is performed on the permanent IPv6 addresses when they get enabled. Test: - stack_test.TestDoDADWhenNICEnabled - stack.TestDisabledRxStatsWhenNICDisabled PiperOrigin-RevId: 293697429
259,854
07.02.2020 14:00:50
28,800
e1587a28876f8aac689a2cd1b7630f1637655b58
Log level, optname, optval and optlen in getsockopt/setsockopt in strace. Log 8, 16, and 32 int optvals and dump the memory of other sizes. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/linux64_amd64.go", "new_path": "pkg/sentry/strace/linux64_amd64.go", "diff": "@@ -78,8 +78,8 @@ var linuxAMD64 = SyscallMap{\n51: makeSyscallInfo(\"getsockname\", FD, PostSockAddr, SockLen),\n52: makeSyscallInfo(\"getpeername\", FD, PostSockAddr, SockLen),\n53: makeSyscallInfo(\"socketpair\", SockFamily, SockType, SockProtocol, Hex),\n- 54: makeSyscallInfo(\"setsockopt\", FD, Hex, Hex, Hex, Hex),\n- 55: makeSyscallInfo(\"getsockopt\", FD, Hex, Hex, Hex, Hex),\n+ 54: makeSyscallInfo(\"setsockopt\", FD, SockOptLevel, SockOptName, SetSockOptVal, Hex /* length by value, not a pointer */),\n+ 55: makeSyscallInfo(\"getsockopt\", FD, SockOptLevel, SockOptName, GetSockOptVal, SockLen),\n56: makeSyscallInfo(\"clone\", CloneFlags, Hex, Hex, Hex, Hex),\n57: makeSyscallInfo(\"fork\"),\n58: makeSyscallInfo(\"vfork\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/socket.go", "new_path": "pkg/sentry/strace/socket.go", "diff": "@@ -419,3 +419,218 @@ func sockFlags(flags int32) string {\n}\nreturn SocketFlagSet.Parse(uint64(flags))\n}\n+\n+func getSockOptVal(t *kernel.Task, level, optname uint64, optVal usermem.Addr, optLen usermem.Addr, maximumBlobSize uint, rval uintptr) string {\n+ if int(rval) < 0 {\n+ return hexNum(uint64(optVal))\n+ }\n+ if optVal == 0 {\n+ return \"null\"\n+ }\n+ l, err := copySockLen(t, optLen)\n+ if err != nil {\n+ return fmt.Sprintf(\"%#x {error reading length: %v}\", optLen, err)\n+ }\n+ return sockOptVal(t, level, optname, optVal, uint64(l), maximumBlobSize)\n+}\n+\n+func sockOptVal(t *kernel.Task, level, optname uint64, optVal usermem.Addr, optLen uint64, maximumBlobSize uint) string {\n+ switch optLen {\n+ case 1:\n+ var v uint8\n+ _, err := t.CopyIn(optVal, &v)\n+ if err != nil {\n+ return fmt.Sprintf(\"%#x {error reading optval: %v}\", optVal, err)\n+ }\n+ return fmt.Sprintf(\"%#x {value=%v}\", optVal, v)\n+ case 2:\n+ var v uint16\n+ _, err := t.CopyIn(optVal, &v)\n+ if err != nil {\n+ return fmt.Sprintf(\"%#x {error reading optval: %v}\", optVal, err)\n+ }\n+ return fmt.Sprintf(\"%#x {value=%v}\", optVal, v)\n+ case 4:\n+ var v uint32\n+ _, err := t.CopyIn(optVal, &v)\n+ if err != nil {\n+ return fmt.Sprintf(\"%#x {error reading optval: %v}\", optVal, err)\n+ }\n+ return fmt.Sprintf(\"%#x {value=%v}\", optVal, v)\n+ default:\n+ return dump(t, optVal, uint(optLen), maximumBlobSize)\n+ }\n+}\n+\n+var sockOptLevels = abi.ValueSet{\n+ linux.SOL_IP: \"SOL_IP\",\n+ linux.SOL_SOCKET: \"SOL_SOCKET\",\n+ linux.SOL_TCP: \"SOL_TCP\",\n+ linux.SOL_UDP: \"SOL_UDP\",\n+ linux.SOL_IPV6: \"SOL_IPV6\",\n+ linux.SOL_ICMPV6: \"SOL_ICMPV6\",\n+ linux.SOL_RAW: \"SOL_RAW\",\n+ linux.SOL_PACKET: \"SOL_PACKET\",\n+ linux.SOL_NETLINK: \"SOL_NETLINK\",\n+}\n+\n+var sockOptNames = map[uint64]abi.ValueSet{\n+ linux.SOL_IP: {\n+ linux.IP_TTL: \"IP_TTL\",\n+ linux.IP_MULTICAST_TTL: \"IP_MULTICAST_TTL\",\n+ linux.IP_MULTICAST_IF: \"IP_MULTICAST_IF\",\n+ linux.IP_MULTICAST_LOOP: \"IP_MULTICAST_LOOP\",\n+ linux.IP_TOS: \"IP_TOS\",\n+ linux.IP_RECVTOS: \"IP_RECVTOS\",\n+ linux.IPT_SO_GET_INFO: \"IPT_SO_GET_INFO\",\n+ linux.IPT_SO_GET_ENTRIES: \"IPT_SO_GET_ENTRIES\",\n+ linux.IP_ADD_MEMBERSHIP: \"IP_ADD_MEMBERSHIP\",\n+ linux.IP_DROP_MEMBERSHIP: \"IP_DROP_MEMBERSHIP\",\n+ linux.MCAST_JOIN_GROUP: \"MCAST_JOIN_GROUP\",\n+ linux.IP_ADD_SOURCE_MEMBERSHIP: \"IP_ADD_SOURCE_MEMBERSHIP\",\n+ linux.IP_BIND_ADDRESS_NO_PORT: \"IP_BIND_ADDRESS_NO_PORT\",\n+ linux.IP_BLOCK_SOURCE: \"IP_BLOCK_SOURCE\",\n+ linux.IP_CHECKSUM: \"IP_CHECKSUM\",\n+ linux.IP_DROP_SOURCE_MEMBERSHIP: \"IP_DROP_SOURCE_MEMBERSHIP\",\n+ linux.IP_FREEBIND: \"IP_FREEBIND\",\n+ linux.IP_HDRINCL: \"IP_HDRINCL\",\n+ linux.IP_IPSEC_POLICY: \"IP_IPSEC_POLICY\",\n+ linux.IP_MINTTL: \"IP_MINTTL\",\n+ linux.IP_MSFILTER: \"IP_MSFILTER\",\n+ linux.IP_MTU_DISCOVER: \"IP_MTU_DISCOVER\",\n+ linux.IP_MULTICAST_ALL: \"IP_MULTICAST_ALL\",\n+ linux.IP_NODEFRAG: \"IP_NODEFRAG\",\n+ linux.IP_OPTIONS: \"IP_OPTIONS\",\n+ linux.IP_PASSSEC: \"IP_PASSSEC\",\n+ linux.IP_PKTINFO: \"IP_PKTINFO\",\n+ linux.IP_RECVERR: \"IP_RECVERR\",\n+ linux.IP_RECVFRAGSIZE: \"IP_RECVFRAGSIZE\",\n+ linux.IP_RECVOPTS: \"IP_RECVOPTS\",\n+ linux.IP_RECVORIGDSTADDR: \"IP_RECVORIGDSTADDR\",\n+ linux.IP_RECVTTL: \"IP_RECVTTL\",\n+ linux.IP_RETOPTS: \"IP_RETOPTS\",\n+ linux.IP_TRANSPARENT: \"IP_TRANSPARENT\",\n+ linux.IP_UNBLOCK_SOURCE: \"IP_UNBLOCK_SOURCE\",\n+ linux.IP_UNICAST_IF: \"IP_UNICAST_IF\",\n+ linux.IP_XFRM_POLICY: \"IP_XFRM_POLICY\",\n+ linux.MCAST_BLOCK_SOURCE: \"MCAST_BLOCK_SOURCE\",\n+ linux.MCAST_JOIN_SOURCE_GROUP: \"MCAST_JOIN_SOURCE_GROUP\",\n+ linux.MCAST_LEAVE_GROUP: \"MCAST_LEAVE_GROUP\",\n+ linux.MCAST_LEAVE_SOURCE_GROUP: \"MCAST_LEAVE_SOURCE_GROUP\",\n+ linux.MCAST_MSFILTER: \"MCAST_MSFILTER\",\n+ linux.MCAST_UNBLOCK_SOURCE: \"MCAST_UNBLOCK_SOURCE\",\n+ linux.IP_ROUTER_ALERT: \"IP_ROUTER_ALERT\",\n+ linux.IP_PKTOPTIONS: \"IP_PKTOPTIONS\",\n+ linux.IP_MTU: \"IP_MTU\",\n+ },\n+ linux.SOL_SOCKET: {\n+ linux.SO_ERROR: \"SO_ERROR\",\n+ linux.SO_PEERCRED: \"SO_PEERCRED\",\n+ linux.SO_PASSCRED: \"SO_PASSCRED\",\n+ linux.SO_SNDBUF: \"SO_SNDBUF\",\n+ linux.SO_RCVBUF: \"SO_RCVBUF\",\n+ linux.SO_REUSEADDR: \"SO_REUSEADDR\",\n+ linux.SO_REUSEPORT: \"SO_REUSEPORT\",\n+ linux.SO_BINDTODEVICE: \"SO_BINDTODEVICE\",\n+ linux.SO_BROADCAST: \"SO_BROADCAST\",\n+ linux.SO_KEEPALIVE: \"SO_KEEPALIVE\",\n+ linux.SO_LINGER: \"SO_LINGER\",\n+ linux.SO_SNDTIMEO: \"SO_SNDTIMEO\",\n+ linux.SO_RCVTIMEO: \"SO_RCVTIMEO\",\n+ linux.SO_OOBINLINE: \"SO_OOBINLINE\",\n+ linux.SO_TIMESTAMP: \"SO_TIMESTAMP\",\n+ },\n+ linux.SOL_TCP: {\n+ linux.TCP_NODELAY: \"TCP_NODELAY\",\n+ linux.TCP_CORK: \"TCP_CORK\",\n+ linux.TCP_QUICKACK: \"TCP_QUICKACK\",\n+ linux.TCP_MAXSEG: \"TCP_MAXSEG\",\n+ linux.TCP_KEEPIDLE: \"TCP_KEEPIDLE\",\n+ linux.TCP_KEEPINTVL: \"TCP_KEEPINTVL\",\n+ linux.TCP_USER_TIMEOUT: \"TCP_USER_TIMEOUT\",\n+ linux.TCP_INFO: \"TCP_INFO\",\n+ linux.TCP_CC_INFO: \"TCP_CC_INFO\",\n+ linux.TCP_NOTSENT_LOWAT: \"TCP_NOTSENT_LOWAT\",\n+ linux.TCP_ZEROCOPY_RECEIVE: \"TCP_ZEROCOPY_RECEIVE\",\n+ linux.TCP_CONGESTION: \"TCP_CONGESTION\",\n+ linux.TCP_LINGER2: \"TCP_LINGER2\",\n+ linux.TCP_DEFER_ACCEPT: \"TCP_DEFER_ACCEPT\",\n+ linux.TCP_REPAIR_OPTIONS: \"TCP_REPAIR_OPTIONS\",\n+ linux.TCP_INQ: \"TCP_INQ\",\n+ linux.TCP_FASTOPEN: \"TCP_FASTOPEN\",\n+ linux.TCP_FASTOPEN_CONNECT: \"TCP_FASTOPEN_CONNECT\",\n+ linux.TCP_FASTOPEN_KEY: \"TCP_FASTOPEN_KEY\",\n+ linux.TCP_FASTOPEN_NO_COOKIE: \"TCP_FASTOPEN_NO_COOKIE\",\n+ linux.TCP_KEEPCNT: \"TCP_KEEPCNT\",\n+ linux.TCP_QUEUE_SEQ: \"TCP_QUEUE_SEQ\",\n+ linux.TCP_REPAIR: \"TCP_REPAIR\",\n+ linux.TCP_REPAIR_QUEUE: \"TCP_REPAIR_QUEUE\",\n+ linux.TCP_REPAIR_WINDOW: \"TCP_REPAIR_WINDOW\",\n+ linux.TCP_SAVED_SYN: \"TCP_SAVED_SYN\",\n+ linux.TCP_SAVE_SYN: \"TCP_SAVE_SYN\",\n+ linux.TCP_SYNCNT: \"TCP_SYNCNT\",\n+ linux.TCP_THIN_DUPACK: \"TCP_THIN_DUPACK\",\n+ linux.TCP_THIN_LINEAR_TIMEOUTS: \"TCP_THIN_LINEAR_TIMEOUTS\",\n+ linux.TCP_TIMESTAMP: \"TCP_TIMESTAMP\",\n+ linux.TCP_ULP: \"TCP_ULP\",\n+ linux.TCP_WINDOW_CLAMP: \"TCP_WINDOW_CLAMP\",\n+ },\n+ linux.SOL_IPV6: {\n+ linux.IPV6_V6ONLY: \"IPV6_V6ONLY\",\n+ linux.IPV6_PATHMTU: \"IPV6_PATHMTU\",\n+ linux.IPV6_TCLASS: \"IPV6_TCLASS\",\n+ linux.IPV6_ADD_MEMBERSHIP: \"IPV6_ADD_MEMBERSHIP\",\n+ linux.IPV6_DROP_MEMBERSHIP: \"IPV6_DROP_MEMBERSHIP\",\n+ linux.IPV6_IPSEC_POLICY: \"IPV6_IPSEC_POLICY\",\n+ linux.IPV6_JOIN_ANYCAST: \"IPV6_JOIN_ANYCAST\",\n+ linux.IPV6_LEAVE_ANYCAST: \"IPV6_LEAVE_ANYCAST\",\n+ linux.IPV6_PKTINFO: \"IPV6_PKTINFO\",\n+ linux.IPV6_ROUTER_ALERT: \"IPV6_ROUTER_ALERT\",\n+ linux.IPV6_XFRM_POLICY: \"IPV6_XFRM_POLICY\",\n+ linux.MCAST_BLOCK_SOURCE: \"MCAST_BLOCK_SOURCE\",\n+ linux.MCAST_JOIN_GROUP: \"MCAST_JOIN_GROUP\",\n+ linux.MCAST_JOIN_SOURCE_GROUP: \"MCAST_JOIN_SOURCE_GROUP\",\n+ linux.MCAST_LEAVE_GROUP: \"MCAST_LEAVE_GROUP\",\n+ linux.MCAST_LEAVE_SOURCE_GROUP: \"MCAST_LEAVE_SOURCE_GROUP\",\n+ linux.MCAST_UNBLOCK_SOURCE: \"MCAST_UNBLOCK_SOURCE\",\n+ linux.IPV6_2292DSTOPTS: \"IPV6_2292DSTOPTS\",\n+ linux.IPV6_2292HOPLIMIT: \"IPV6_2292HOPLIMIT\",\n+ linux.IPV6_2292HOPOPTS: \"IPV6_2292HOPOPTS\",\n+ linux.IPV6_2292PKTINFO: \"IPV6_2292PKTINFO\",\n+ linux.IPV6_2292PKTOPTIONS: \"IPV6_2292PKTOPTIONS\",\n+ linux.IPV6_2292RTHDR: \"IPV6_2292RTHDR\",\n+ linux.IPV6_ADDR_PREFERENCES: \"IPV6_ADDR_PREFERENCES\",\n+ linux.IPV6_AUTOFLOWLABEL: \"IPV6_AUTOFLOWLABEL\",\n+ linux.IPV6_DONTFRAG: \"IPV6_DONTFRAG\",\n+ linux.IPV6_DSTOPTS: \"IPV6_DSTOPTS\",\n+ linux.IPV6_FLOWINFO: \"IPV6_FLOWINFO\",\n+ linux.IPV6_FLOWINFO_SEND: \"IPV6_FLOWINFO_SEND\",\n+ linux.IPV6_FLOWLABEL_MGR: \"IPV6_FLOWLABEL_MGR\",\n+ linux.IPV6_FREEBIND: \"IPV6_FREEBIND\",\n+ linux.IPV6_HOPOPTS: \"IPV6_HOPOPTS\",\n+ linux.IPV6_MINHOPCOUNT: \"IPV6_MINHOPCOUNT\",\n+ linux.IPV6_MTU: \"IPV6_MTU\",\n+ linux.IPV6_MTU_DISCOVER: \"IPV6_MTU_DISCOVER\",\n+ linux.IPV6_MULTICAST_ALL: \"IPV6_MULTICAST_ALL\",\n+ linux.IPV6_MULTICAST_HOPS: \"IPV6_MULTICAST_HOPS\",\n+ linux.IPV6_MULTICAST_IF: \"IPV6_MULTICAST_IF\",\n+ linux.IPV6_MULTICAST_LOOP: \"IPV6_MULTICAST_LOOP\",\n+ linux.IPV6_RECVDSTOPTS: \"IPV6_RECVDSTOPTS\",\n+ linux.IPV6_RECVERR: \"IPV6_RECVERR\",\n+ linux.IPV6_RECVFRAGSIZE: \"IPV6_RECVFRAGSIZE\",\n+ linux.IPV6_RECVHOPLIMIT: \"IPV6_RECVHOPLIMIT\",\n+ linux.IPV6_RECVHOPOPTS: \"IPV6_RECVHOPOPTS\",\n+ linux.IPV6_RECVORIGDSTADDR: \"IPV6_RECVORIGDSTADDR\",\n+ linux.IPV6_RECVPATHMTU: \"IPV6_RECVPATHMTU\",\n+ linux.IPV6_RECVPKTINFO: \"IPV6_RECVPKTINFO\",\n+ linux.IPV6_RECVRTHDR: \"IPV6_RECVRTHDR\",\n+ linux.IPV6_RECVTCLASS: \"IPV6_RECVTCLASS\",\n+ linux.IPV6_RTHDR: \"IPV6_RTHDR\",\n+ linux.IPV6_RTHDRDSTOPTS: \"IPV6_RTHDRDSTOPTS\",\n+ linux.IPV6_TRANSPARENT: \"IPV6_TRANSPARENT\",\n+ linux.IPV6_UNICAST_HOPS: \"IPV6_UNICAST_HOPS\",\n+ linux.IPV6_UNICAST_IF: \"IPV6_UNICAST_IF\",\n+ linux.MCAST_MSFILTER: \"MCAST_MSFILTER\",\n+ linux.IPV6_ADDRFORM: \"IPV6_ADDRFORM\",\n+ },\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/strace.go", "new_path": "pkg/sentry/strace/strace.go", "diff": "@@ -55,6 +55,14 @@ var ItimerTypes = abi.ValueSet{\nlinux.ITIMER_PROF: \"ITIMER_PROF\",\n}\n+func hexNum(num uint64) string {\n+ return \"0x\" + strconv.FormatUint(num, 16)\n+}\n+\n+func hexArg(arg arch.SyscallArgument) string {\n+ return hexNum(arg.Uint64())\n+}\n+\nfunc iovecs(t *kernel.Task, addr usermem.Addr, iovcnt int, printContent bool, maxBytes uint64) string {\nif iovcnt < 0 || iovcnt > linux.UIO_MAXIOV {\nreturn fmt.Sprintf(\"%#x (error decoding iovecs: invalid iovcnt)\", addr)\n@@ -389,6 +397,12 @@ func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlo\noutput = append(output, path(t, args[arg].Pointer()))\ncase ExecveStringVector:\noutput = append(output, stringVector(t, args[arg].Pointer()))\n+ case SetSockOptVal:\n+ output = append(output, sockOptVal(t, args[arg-2].Uint64() /* level */, args[arg-1].Uint64() /* optName */, args[arg].Pointer() /* optVal */, args[arg+1].Uint64() /* optLen */, maximumBlobSize))\n+ case SockOptLevel:\n+ output = append(output, sockOptLevels.Parse(args[arg].Uint64()))\n+ case SockOptName:\n+ output = append(output, sockOptNames[args[arg-1].Uint64() /* level */].Parse(args[arg].Uint64()))\ncase SockAddr:\noutput = append(output, sockAddr(t, args[arg].Pointer(), uint32(args[arg+1].Uint64())))\ncase SockLen:\n@@ -446,7 +460,7 @@ func (i *SyscallInfo) pre(t *kernel.Task, args arch.SyscallArguments, maximumBlo\ncase Hex:\nfallthrough\ndefault:\n- output = append(output, \"0x\"+strconv.FormatUint(args[arg].Uint64(), 16))\n+ output = append(output, hexArg(args[arg]))\n}\n}\n@@ -507,6 +521,12 @@ func (i *SyscallInfo) post(t *kernel.Task, args arch.SyscallArguments, rval uint\noutput[arg] = capData(t, args[arg-1].Pointer(), args[arg].Pointer())\ncase PollFDs:\noutput[arg] = pollFDs(t, args[arg].Pointer(), uint(args[arg+1].Uint()), true)\n+ case GetSockOptVal:\n+ output[arg] = getSockOptVal(t, args[arg-2].Uint64() /* level */, args[arg-1].Uint64() /* optName */, args[arg].Pointer() /* optVal */, args[arg+1].Pointer() /* optLen */, maximumBlobSize, rval)\n+ case SetSockOptVal:\n+ // No need to print the value again. While it usually\n+ // isn't, the string version of this arg can be long.\n+ output[arg] = hexArg(args[arg])\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/syscalls.go", "new_path": "pkg/sentry/strace/syscalls.go", "diff": "@@ -207,9 +207,27 @@ const (\n// array is in the next argument.\nPollFDs\n- // SelectFDSet is an fd_set argument in select(2)/pselect(2). The number of\n- // fds represented must be the first argument.\n+ // SelectFDSet is an fd_set argument in select(2)/pselect(2). The\n+ // number of FDs represented must be the first argument.\nSelectFDSet\n+\n+ // GetSockOptVal is the optval argument in getsockopt(2).\n+ //\n+ // Formatted after syscall execution.\n+ GetSockOptVal\n+\n+ // SetSockOptVal is the optval argument in setsockopt(2).\n+ //\n+ // Contents omitted after syscall execution.\n+ SetSockOptVal\n+\n+ // SockOptLevel is the level argument in getsockopt(2) and\n+ // setsockopt(2).\n+ SockOptLevel\n+\n+ // SockOptLevel is the optname argument in getsockopt(2) and\n+ // setsockopt(2).\n+ SockOptName\n)\n// defaultFormat is the syscall argument format to use if the actual format is\n" } ]
Go
Apache License 2.0
google/gvisor
Log level, optname, optval and optlen in getsockopt/setsockopt in strace. Log 8, 16, and 32 int optvals and dump the memory of other sizes. Updates #1782 PiperOrigin-RevId: 293889388
259,891
10.02.2020 11:08:24
28,800
31f2182cd3fc2a6fdb1aecf1c56f1302f16f6453
iptables: add instructions for runsc building. The readme didn't mention that users need to: `bazel build` when working on iptables tests enable raw sockets in /etc/docker/daemon.json.
[ { "change_type": "MODIFY", "old_path": "test/iptables/README.md", "new_path": "test/iptables/README.md", "diff": "iptables tests are run via `scripts/iptables_test.sh`.\n+iptables requires raw socket support, so you must add the `--net-raw=true` flag\n+to `/etc/docker/daemon.json` in order to use it.\n+\n## Test Structure\nEach test implements `TestCase`, providing (1) a function to run inside the\n@@ -25,7 +28,14 @@ Your test is now runnable with bazel!\n## Run individual tests\n-Build the testing Docker container:\n+Build and install `runsc`. Re-run this when you modify gVisor:\n+\n+```bash\n+$ bazel build //runsc && sudo cp bazel-bin/runsc/linux_amd64_pure_stripped/runsc $(which runsc)\n+```\n+\n+Build the testing Docker container. Re-run this when you modify the test code in\n+this directory:\n```bash\n$ bazel run //test/iptables/runner:runner-image -- --norun\n" } ]
Go
Apache License 2.0
google/gvisor
iptables: add instructions for runsc building. The readme didn't mention that users need to: - `bazel build` when working on iptables tests - enable raw sockets in /etc/docker/daemon.json. PiperOrigin-RevId: 294260169
259,847
10.02.2020 11:57:31
28,800
20840bfec087d45853e81d1ac34940f3b2fb920a
Move x86 state definition to its own file.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/BUILD", "new_path": "pkg/sentry/arch/BUILD", "diff": "@@ -14,6 +14,7 @@ go_library(\n\"arch_state_aarch64.go\",\n\"arch_state_x86.go\",\n\"arch_x86.go\",\n+ \"arch_x86_impl.go\",\n\"auxv.go\",\n\"signal.go\",\n\"signal_act.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_state_x86.go", "new_path": "pkg/sentry/arch/arch_state_x86.go", "diff": "@@ -43,8 +43,8 @@ func (e ErrFloatingPoint) Error() string {\n// and SSE state, so this is the equivalent XSTATE_BV value.\nconst fxsaveBV uint64 = cpuid.XSAVEFeatureX87 | cpuid.XSAVEFeatureSSE\n-// afterLoad is invoked by stateify.\n-func (s *State) afterLoad() {\n+// afterLoadFPState is invoked by afterLoad.\n+func (s *State) afterLoadFPState() {\nold := s.x86FPState\n// Recreate the slice. This is done to ensure that it is aligned\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_x86.go", "new_path": "pkg/sentry/arch/arch_x86.go", "diff": "@@ -155,21 +155,6 @@ func NewFloatingPointData() *FloatingPointData {\nreturn (*FloatingPointData)(&(newX86FPState()[0]))\n}\n-// State contains the common architecture bits for X86 (the build tag of this\n-// file ensures it's only built on x86).\n-//\n-// +stateify savable\n-type State struct {\n- // The system registers.\n- Regs syscall.PtraceRegs `state:\".(syscallPtraceRegs)\"`\n-\n- // Our floating point state.\n- x86FPState `state:\"wait\"`\n-\n- // FeatureSet is a pointer to the currently active feature set.\n- FeatureSet *cpuid.FeatureSet\n-}\n-\n// Proto returns a protobuf representation of the system registers in State.\nfunc (s State) Proto() *rpb.Registers {\nregs := &rpb.AMD64Registers{\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/arch/arch_x86_impl.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build amd64 i386\n+\n+package arch\n+\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/cpuid\"\n+)\n+\n+// State contains the common architecture bits for X86 (the build tag of this\n+// file ensures it's only built on x86).\n+//\n+// +stateify savable\n+type State struct {\n+ // The system registers.\n+ Regs syscall.PtraceRegs `state:\".(syscallPtraceRegs)\"`\n+\n+ // Our floating point state.\n+ x86FPState `state:\"wait\"`\n+\n+ // FeatureSet is a pointer to the currently active feature set.\n+ FeatureSet *cpuid.FeatureSet\n+}\n+\n+// afterLoad is invoked by stateify.\n+func (s *State) afterLoad() {\n+ s.afterLoadFPState()\n+}\n" }, { "change_type": "MODIFY", "old_path": "tools/build/tags.bzl", "new_path": "tools/build/tags.bzl", "diff": "go_suffixes = [\n\"_386\",\n\"_386_unsafe\",\n- \"_amd64\",\n- \"_amd64_unsafe\",\n\"_aarch64\",\n\"_aarch64_unsafe\",\n+ \"_amd64\",\n+ \"_amd64_unsafe\",\n\"_arm\",\n- \"_arm_unsafe\",\n\"_arm64\",\n\"_arm64_unsafe\",\n+ \"_arm_unsafe\",\n+ \"_impl\",\n+ \"_impl_unsafe\",\n+ \"_linux\",\n+ \"_linux_unsafe\",\n\"_mips\",\n- \"_mips_unsafe\",\n- \"_mipsle\",\n- \"_mipsle_unsafe\",\n\"_mips64\",\n\"_mips64_unsafe\",\n\"_mips64le\",\n\"_mips64le_unsafe\",\n+ \"_mips_unsafe\",\n+ \"_mipsle\",\n+ \"_mipsle_unsafe\",\n+ \"_opts\",\n+ \"_opts_unsafe\",\n\"_ppc64\",\n\"_ppc64_unsafe\",\n\"_ppc64le\",\n@@ -31,10 +37,4 @@ go_suffixes = [\n\"_sparc64_unsafe\",\n\"_wasm\",\n\"_wasm_unsafe\",\n- \"_linux\",\n- \"_linux_unsafe\",\n- \"_opts\",\n- \"_opts_unsafe\",\n- \"_impl\",\n- \"_impl_unsafe\",\n]\n" } ]
Go
Apache License 2.0
google/gvisor
Move x86 state definition to its own file. PiperOrigin-RevId: 294271541
259,992
10.02.2020 12:02:47
28,800
bfa0bba72abb69cbc7f4da27d3b4b116c3784495
Redirect FIXME to gvisor.dev
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -111,10 +111,10 @@ func (fs *Filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\n// Dentry isn't cached; it either doesn't exist or failed\n// revalidation. Attempt to resolve it via Lookup.\n//\n- // FIXME(b/144498111): Inode.Lookup() should return *(kernfs.)Dentry,\n- // not *vfs.Dentry, since (kernfs.)Filesystem assumes that all dentries\n- // in the filesystem are (kernfs.)Dentry and performs vfs.DentryImpl\n- // casts accordingly.\n+ // FIXME(gvisor.dev/issue/1193): Inode.Lookup() should return\n+ // *(kernfs.)Dentry, not *vfs.Dentry, since (kernfs.)Filesystem assumes\n+ // that all dentries in the filesystem are (kernfs.)Dentry and performs\n+ // vfs.DentryImpl casts accordingly.\nvar err error\nchildVFSD, err = parent.inode.Lookup(ctx, name)\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Redirect FIXME to gvisor.dev PiperOrigin-RevId: 294272755
259,858
10.02.2020 12:06:06
28,800
c9a18b16ade6ec0bc90fc75d0a4ab0621f9d01d6
Document MinimumTotalMemoryBytes.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/usage/memory.go", "new_path": "pkg/sentry/usage/memory.go", "diff": "@@ -253,6 +253,10 @@ func (m *MemoryLocked) Copy() (MemoryStats, uint64) {\n}\n// MinimumTotalMemoryBytes is the minimum reported total system memory.\n+//\n+// This can be configured through options provided to the Sentry at start.\n+// This number is purely synthetic. This is only set before the application\n+// starts executing, and must not be modified.\nvar MinimumTotalMemoryBytes uint64 = 2 << 30 // 2 GB\n// TotalMemory returns the \"total usable memory\" available.\n" } ]
Go
Apache License 2.0
google/gvisor
Document MinimumTotalMemoryBytes. PiperOrigin-RevId: 294273559
259,858
10.02.2020 13:04:29
28,800
4d4d47f0c0a21d3404d2edae527b187d62daa3c8
Add contextual note.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/directory.go", "new_path": "pkg/sentry/fsimpl/gofer/directory.go", "diff": "@@ -87,6 +87,10 @@ func (d *dentry) getDirents(ctx context.Context) ([]vfs.Dirent, error) {\n// to assume that directory fids have the correct semantics, and translates\n// struct file_operations::readdir calls directly to readdir RPCs), but is\n// consistent with VFS1.\n+ //\n+ // NOTE(b/135560623): In particular, some gofer implementations may not\n+ // retain state between calls to Readdir, so may not provide a coherent\n+ // directory stream across in the presence of mutation.\nd.fs.renameMu.RLock()\ndefer d.fs.renameMu.RUnlock()\n" } ]
Go
Apache License 2.0
google/gvisor
Add contextual note. PiperOrigin-RevId: 294285723
259,847
10.02.2020 13:06:57
28,800
bc504d52026790b7deed6506371ebc6d5d17c948
Fix build_file in runtimes_tests.
[ { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/go1.12.cfg", "new_path": "kokoro/runtime_tests/go1.12.cfg", "diff": "-build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/java11.cfg", "new_path": "kokoro/runtime_tests/java11.cfg", "diff": "-build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/nodejs12.4.0.cfg", "new_path": "kokoro/runtime_tests/nodejs12.4.0.cfg", "diff": "-build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/php7.3.6.cfg", "new_path": "kokoro/runtime_tests/php7.3.6.cfg", "diff": "-build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/runtime_tests/python3.7.3.cfg", "new_path": "kokoro/runtime_tests/python3.7.3.cfg", "diff": "-build_file: \"github/kokoro/runtime_tests/runtime_tests.sh\"\n+build_file: \"github/github/kokoro/runtime_tests/runtime_tests.sh\"\nenv_vars {\nkey: \"RUNTIME_TEST_NAME\"\n" } ]
Go
Apache License 2.0
google/gvisor
Fix build_file in runtimes_tests. PiperOrigin-RevId: 294286242
259,858
10.02.2020 13:20:44
28,800
bb22ebd7fbfc66556b38df669be5c6372daba018
Add contextual comment.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/benchmark/benchmark_test.go", "new_path": "pkg/sentry/fsimpl/ext/benchmark/benchmark_test.go", "diff": "// These benchmarks emulate memfs benchmarks. Ext4 images must be created\n// before this benchmark is run using the `make_deep_ext4.sh` script at\n// /tmp/image-{depth}.ext4 for all the depths tested below.\n+//\n+// The benchmark itself cannot run the script because the script requires\n+// sudo privileges to create the file system images.\npackage benchmark_test\nimport (\n" } ]
Go
Apache License 2.0
google/gvisor
Add contextual comment. PiperOrigin-RevId: 294289066
259,858
10.02.2020 13:51:26
28,800
a6f9361c2f7c5b46a200de1dc891a0ce059ad90e
Add context to comments.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/gofer/attr.go", "new_path": "pkg/sentry/fs/gofer/attr.go", "diff": "@@ -88,8 +88,9 @@ func bsize(pattr p9.Attr) int64 {\nif pattr.BlockSize > 0 {\nreturn int64(pattr.BlockSize)\n}\n- // Some files may have no clue of their block size. Better not to report\n- // something misleading or buggy and have a safe default.\n+ // Some files, particularly those that are not on a local file system,\n+ // may have no clue of their block size. Better not to report something\n+ // misleading or buggy and have a safe default.\nreturn usermem.PageSize\n}\n@@ -149,6 +150,7 @@ func links(valid p9.AttrMask, pattr p9.Attr) uint64 {\n}\n// This node is likely backed by a file system that doesn't support links.\n+ //\n// We could readdir() and count children directories to provide an accurate\n// link count. However this may be expensive since the gofer may be backed by remote\n// storage. Instead, simply return 2 links for directories and 1 for everything else\n" } ]
Go
Apache License 2.0
google/gvisor
Add context to comments. PiperOrigin-RevId: 294295852
259,858
10.02.2020 14:11:04
28,800
afcab8fe9f6fb3504ebdbb95d35299277c2d67ca
Clean-up comments in runsc/BUILD and CONTRIBUTING.md.
[ { "change_type": "MODIFY", "old_path": "CONTRIBUTING.md", "new_path": "CONTRIBUTING.md", "diff": "@@ -47,7 +47,7 @@ Definitions for the rules below:\n`core`:\n* `//pkg/sentry/...`\n-* Transitive dependencies in `//pkg/...`, `//third_party/...`.\n+* Transitive dependencies in `//pkg/...`, etc.\n`runsc`:\n" }, { "change_type": "MODIFY", "old_path": "runsc/BUILD", "new_path": "runsc/BUILD", "diff": "@@ -26,7 +26,7 @@ go_binary(\n)\n# The runsc-race target is a race-compatible BUILD target. This must be built\n-# via: bazel build --features=race //runsc:runsc-race\n+# via: bazel build --features=race :runsc-race\n#\n# This is neccessary because the race feature must apply to all dependencies\n# due a bug in gazelle file selection. The pure attribute must be off because\n" } ]
Go
Apache License 2.0
google/gvisor
Clean-up comments in runsc/BUILD and CONTRIBUTING.md. PiperOrigin-RevId: 294300437
259,860
10.02.2020 14:47:00
28,800
475316e87dac806d69bcb06ea4065f3c138bb47e
Refactor getxattr. Put most of the logic for getxattr in one place for clarity. This simplifies FGetXattr and getXattrFromPath, which are just wrappers for getXattr.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "new_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "diff": "@@ -49,14 +49,11 @@ func FGetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n}\ndefer f.DecRef()\n- n, value, err := getXattr(t, f.Dirent, nameAddr, size)\n+ n, err := getXattr(t, f.Dirent, nameAddr, valueAddr, size)\nif err != nil {\nreturn 0, nil, err\n}\n- if _, err := t.CopyOutBytes(valueAddr, []byte(value)); err != nil {\n- return 0, nil, err\n- }\nreturn uintptr(n), nil, nil\n}\n@@ -71,41 +68,36 @@ func getXattrFromPath(t *kernel.Task, args arch.SyscallArguments, resolveSymlink\nreturn 0, nil, err\n}\n- valueLen := 0\n+ n := 0\nerr = fileOpOn(t, linux.AT_FDCWD, path, resolveSymlink, func(_ *fs.Dirent, d *fs.Dirent, _ uint) error {\nif dirPath && !fs.IsDir(d.Inode.StableAttr) {\nreturn syserror.ENOTDIR\n}\n- n, value, err := getXattr(t, d, nameAddr, size)\n- valueLen = n\n- if err != nil {\n- return err\n- }\n-\n- _, err = t.CopyOutBytes(valueAddr, []byte(value))\n+ n, err = getXattr(t, d, nameAddr, valueAddr, size)\nreturn err\n})\nif err != nil {\nreturn 0, nil, err\n}\n- return uintptr(valueLen), nil, nil\n-}\n-// getXattr implements getxattr(2) from the given *fs.Dirent.\n-func getXattr(t *kernel.Task, d *fs.Dirent, nameAddr usermem.Addr, size uint64) (int, string, error) {\n- if err := checkXattrPermissions(t, d.Inode, fs.PermMask{Read: true}); err != nil {\n- return 0, \"\", err\n+ return uintptr(n), nil, nil\n}\n+// getXattr implements getxattr(2) from the given *fs.Dirent.\n+func getXattr(t *kernel.Task, d *fs.Dirent, nameAddr, valueAddr usermem.Addr, size uint64) (int, error) {\nname, err := copyInXattrName(t, nameAddr)\nif err != nil {\n- return 0, \"\", err\n+ return 0, err\n+ }\n+\n+ if err := checkXattrPermissions(t, d.Inode, fs.PermMask{Read: true}); err != nil {\n+ return 0, err\n}\n// TODO(b/148380782): Support xattrs in namespaces other than \"user\".\nif !strings.HasPrefix(name, linux.XATTR_USER_PREFIX) {\n- return 0, \"\", syserror.EOPNOTSUPP\n+ return 0, syserror.EOPNOTSUPP\n}\n// If getxattr(2) is called with size 0, the size of the value will be\n@@ -118,18 +110,22 @@ func getXattr(t *kernel.Task, d *fs.Dirent, nameAddr usermem.Addr, size uint64)\nvalue, err := d.Inode.GetXattr(t, name, requestedSize)\nif err != nil {\n- return 0, \"\", err\n+ return 0, err\n}\nn := len(value)\nif uint64(n) > requestedSize {\n- return 0, \"\", syserror.ERANGE\n+ return 0, syserror.ERANGE\n}\n// Don't copy out the attribute value if size is 0.\nif size == 0 {\n- return n, \"\", nil\n+ return n, nil\n+ }\n+\n+ if _, err = t.CopyOutBytes(valueAddr, []byte(value)); err != nil {\n+ return 0, err\n}\n- return n, value, nil\n+ return n, nil\n}\n// SetXattr implements linux syscall setxattr(2).\n" } ]
Go
Apache License 2.0
google/gvisor
Refactor getxattr. Put most of the logic for getxattr in one place for clarity. This simplifies FGetXattr and getXattrFromPath, which are just wrappers for getXattr. PiperOrigin-RevId: 294308332
259,858
10.02.2020 15:43:36
28,800
dc5a8e52d7004e3796feaadb0a0b0960f7289884
Rename build to builddefs and minor build clean-up. The name 'bazel' also doesn't work because bazel will treat it specially. Fixes
[ { "change_type": "RENAME", "old_path": "tools/build/BUILD", "new_path": "tools/bazeldefs/BUILD", "diff": "" }, { "change_type": "RENAME", "old_path": "tools/build/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -8,7 +8,7 @@ load(\"@rules_pkg//:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\nload(\"@io_bazel_rules_docker//go:image.bzl\", _go_image = \"go_image\")\nload(\"@io_bazel_rules_docker//container:container.bzl\", _container_image = \"container_image\")\nload(\"@pydeps//:requirements.bzl\", _py_requirement = \"requirement\")\n-load(\"//tools/build:tags.bzl\", _go_suffixes = \"go_suffixes\")\n+load(\"//tools/bazeldefs:tags.bzl\", _go_suffixes = \"go_suffixes\")\ncontainer_image = _container_image\ncc_binary = _cc_binary\n@@ -21,7 +21,7 @@ go_image = _go_image\ngo_embed_data = _go_embed_data\ngo_suffixes = _go_suffixes\ngtest = \"@com_google_googletest//:gtest\"\n-loopback = \"//tools/build:loopback\"\n+loopback = \"//tools/bazeldefs:loopback\"\nproto_library = native.proto_library\npkg_deb = _pkg_deb\npkg_tar = _pkg_tar\n" }, { "change_type": "RENAME", "old_path": "tools/build/tags.bzl", "new_path": "tools/bazeldefs/tags.bzl", "diff": "" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -7,7 +7,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\n-load(\"//tools/build:defs.bzl\", \"go_suffixes\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n+load(\"//tools/bazeldefs:defs.bzl\", \"go_suffixes\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n# Delegate directly.\ncc_binary = _cc_binary\n" } ]
Go
Apache License 2.0
google/gvisor
Rename build to builddefs and minor build clean-up. The name 'bazel' also doesn't work because bazel will treat it specially. Fixes #1807 PiperOrigin-RevId: 294321221
259,858
10.02.2020 17:12:03
28,800
71af006b6fe4504fccb86f0222a8a1864d33fb7d
Cleanup internal package group.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/BUILD", "new_path": "pkg/sentry/BUILD", "diff": "-# This BUILD file defines a package_group that allows for interdependencies for\n-# sentry-internal packages.\n-\npackage(licenses = [\"notice\"])\n+# The \"internal\" package_group should be used as much as possible by packages\n+# that should remain Sentry-internal (i.e. not be exposed directly to command\n+# line tooling or APIs).\npackage_group(\nname = \"internal\",\npackages = [\n- \"//cloud/gvisor/gopkg/sentry/...\",\n- \"//cloud/gvisor/sentry/...\",\n\"//pkg/sentry/...\",\n\"//runsc/...\",\n# Code generated by go_marshal relies on go_marshal libraries.\n" } ]
Go
Apache License 2.0
google/gvisor
Cleanup internal package group. PiperOrigin-RevId: 294339229
259,858
11.02.2020 11:37:12
28,800
115898e368e4afe5418a7290d9545fafc7f6f25e
Prevent DATA RACE in UnstableAttr. The slaveInodeOperations is currently copying the object when truncate is called (which is a no-op). This may result in a (unconsequential) data race when being modified concurrently.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/tty/slave.go", "new_path": "pkg/sentry/fs/tty/slave.go", "diff": "@@ -73,7 +73,7 @@ func (si *slaveInodeOperations) Release(ctx context.Context) {\n}\n// Truncate implements fs.InodeOperations.Truncate.\n-func (slaveInodeOperations) Truncate(context.Context, *fs.Inode, int64) error {\n+func (*slaveInodeOperations) Truncate(context.Context, *fs.Inode, int64) error {\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Prevent DATA RACE in UnstableAttr. The slaveInodeOperations is currently copying the object when truncate is called (which is a no-op). This may result in a (unconsequential) data race when being modified concurrently. PiperOrigin-RevId: 294484276
259,891
07.02.2020 11:21:07
28,800
6fdf2c53a1d084b70602170b660242036fd8fe4f
iptables: User chains Adds creation of user chains via `-N <chainname>` Adds `-j RETURN` support for built-in chains, which triggers the chain's underflow rule (usually the default policy). Adds tests for chain creation, default policies, and `-j RETURN' from built-in chains.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -50,7 +50,9 @@ type metadata struct {\n// nflog logs messages related to the writing and reading of iptables.\nfunc nflog(format string, args ...interface{}) {\n- log.Infof(\"netfilter: \"+format, args...)\n+ if log.IsLogging(log.Debug) {\n+ log.Debugf(\"netfilter: \"+format, args...)\n+ }\n}\n// GetInfo returns information about iptables.\n@@ -227,19 +229,23 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\n}\nfunc marshalTarget(target iptables.Target) []byte {\n- switch target.(type) {\n- case iptables.UnconditionalAcceptTarget:\n- return marshalStandardTarget(iptables.Accept)\n- case iptables.UnconditionalDropTarget:\n- return marshalStandardTarget(iptables.Drop)\n+ switch tg := target.(type) {\n+ case iptables.AcceptTarget:\n+ return marshalStandardTarget(iptables.RuleAccept)\n+ case iptables.DropTarget:\n+ return marshalStandardTarget(iptables.RuleDrop)\ncase iptables.ErrorTarget:\n- return marshalErrorTarget()\n+ return marshalErrorTarget(errorTargetName)\n+ case iptables.UserChainTarget:\n+ return marshalErrorTarget(tg.Name)\n+ case iptables.ReturnTarget:\n+ return marshalStandardTarget(iptables.RuleReturn)\ndefault:\npanic(fmt.Errorf(\"unknown target of type %T\", target))\n}\n}\n-func marshalStandardTarget(verdict iptables.Verdict) []byte {\n+func marshalStandardTarget(verdict iptables.RuleVerdict) []byte {\nnflog(\"convert to binary: marshalling standard target with size %d\", linux.SizeOfXTStandardTarget)\n// The target's name will be the empty string.\n@@ -254,14 +260,14 @@ func marshalStandardTarget(verdict iptables.Verdict) []byte {\nreturn binary.Marshal(ret, usermem.ByteOrder, target)\n}\n-func marshalErrorTarget() []byte {\n+func marshalErrorTarget(errorName string) []byte {\n// This is an error target named error\ntarget := linux.XTErrorTarget{\nTarget: linux.XTEntryTarget{\nTargetSize: linux.SizeOfXTErrorTarget,\n},\n}\n- copy(target.Name[:], errorTargetName)\n+ copy(target.Name[:], errorName)\ncopy(target.Target.Name[:], errorTargetName)\nret := make([]byte, 0, linux.SizeOfXTErrorTarget)\n@@ -270,38 +276,35 @@ func marshalErrorTarget() []byte {\n// translateFromStandardVerdict translates verdicts the same way as the iptables\n// tool.\n-func translateFromStandardVerdict(verdict iptables.Verdict) int32 {\n+func translateFromStandardVerdict(verdict iptables.RuleVerdict) int32 {\nswitch verdict {\n- case iptables.Accept:\n+ case iptables.RuleAccept:\nreturn -linux.NF_ACCEPT - 1\n- case iptables.Drop:\n+ case iptables.RuleDrop:\nreturn -linux.NF_DROP - 1\n- case iptables.Queue:\n- return -linux.NF_QUEUE - 1\n- case iptables.Return:\n+ case iptables.RuleReturn:\nreturn linux.NF_RETURN\n- case iptables.Jump:\n+ default:\n// TODO(gvisor.dev/issue/170): Support Jump.\n- panic(\"Jump isn't supported yet\")\n- }\npanic(fmt.Sprintf(\"unknown standard verdict: %d\", verdict))\n}\n+}\n-// translateToStandardVerdict translates from the value in a\n+// translateToStandardTarget translates from the value in a\n// linux.XTStandardTarget to an iptables.Verdict.\n-func translateToStandardVerdict(val int32) (iptables.Verdict, error) {\n+func translateToStandardTarget(val int32) (iptables.Target, error) {\n// TODO(gvisor.dev/issue/170): Support other verdicts.\nswitch val {\ncase -linux.NF_ACCEPT - 1:\n- return iptables.Accept, nil\n+ return iptables.AcceptTarget{}, nil\ncase -linux.NF_DROP - 1:\n- return iptables.Drop, nil\n+ return iptables.DropTarget{}, nil\ncase -linux.NF_QUEUE - 1:\n- return iptables.Invalid, errors.New(\"unsupported iptables verdict QUEUE\")\n+ return nil, errors.New(\"unsupported iptables verdict QUEUE\")\ncase linux.NF_RETURN:\n- return iptables.Invalid, errors.New(\"unsupported iptables verdict RETURN\")\n+ return iptables.ReturnTarget{}, nil\ndefault:\n- return iptables.Invalid, fmt.Errorf(\"unknown iptables verdict %d\", val)\n+ return nil, fmt.Errorf(\"unknown iptables verdict %d\", val)\n}\n}\n@@ -411,6 +414,10 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\ntable.BuiltinChains[hk] = ruleIdx\n}\nif offset == replace.Underflow[hook] {\n+ if !validUnderflow(table.Rules[ruleIdx]) {\n+ nflog(\"underflow for hook %d isn't an unconditional ACCEPT or DROP.\")\n+ return syserr.ErrInvalidArgument\n+ }\ntable.Underflows[hk] = ruleIdx\n}\n}\n@@ -425,12 +432,34 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\n}\n+ // Add the user chains.\n+ for ruleIdx, rule := range table.Rules {\n+ target, ok := rule.Target.(iptables.UserChainTarget)\n+ if !ok {\n+ continue\n+ }\n+\n+ // We found a user chain. Before inserting it into the table,\n+ // check that:\n+ // - There's some other rule after it.\n+ // - There are no matchers.\n+ if ruleIdx == len(table.Rules)-1 {\n+ nflog(\"user chain must have a rule or default policy.\")\n+ return syserr.ErrInvalidArgument\n+ }\n+ if len(table.Rules[ruleIdx].Matchers) != 0 {\n+ nflog(\"user chain's first node must have no matcheres.\")\n+ return syserr.ErrInvalidArgument\n+ }\n+ table.UserChains[target.Name] = ruleIdx + 1\n+ }\n+\n// TODO(gvisor.dev/issue/170): Support other chains.\n// Since we only support modifying the INPUT chain right now, make sure\n// all other chains point to ACCEPT rules.\nfor hook, ruleIdx := range table.BuiltinChains {\nif hook != iptables.Input {\n- if _, ok := table.Rules[ruleIdx].Target.(iptables.UnconditionalAcceptTarget); !ok {\n+ if _, ok := table.Rules[ruleIdx].Target.(iptables.AcceptTarget); !ok {\nnflog(\"hook %d is unsupported.\", hook)\nreturn syserr.ErrInvalidArgument\n}\n@@ -519,18 +548,7 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\nbuf = optVal[:linux.SizeOfXTStandardTarget]\nbinary.Unmarshal(buf, usermem.ByteOrder, &standardTarget)\n- verdict, err := translateToStandardVerdict(standardTarget.Verdict)\n- if err != nil {\n- return nil, err\n- }\n- switch verdict {\n- case iptables.Accept:\n- return iptables.UnconditionalAcceptTarget{}, nil\n- case iptables.Drop:\n- return iptables.UnconditionalDropTarget{}, nil\n- default:\n- return nil, fmt.Errorf(\"Unknown verdict: %v\", verdict)\n- }\n+ return translateToStandardTarget(standardTarget.Verdict)\ncase errorTargetName:\n// Error target.\n@@ -548,11 +566,14 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\n// somehow fall through every rule.\n// * To mark the start of a user defined chain. These\n// rules have an error with the name of the chain.\n- switch errorTarget.Name.String() {\n+ switch name := errorTarget.Name.String(); name {\ncase errorTargetName:\n+ nflog(\"set entries: error target\")\nreturn iptables.ErrorTarget{}, nil\ndefault:\n- return nil, fmt.Errorf(\"unknown error target %q doesn't exist or isn't supported yet.\", errorTarget.Name.String())\n+ // User defined chain.\n+ nflog(\"set entries: user-defined target %q\", name)\n+ return iptables.UserChainTarget{Name: name}, nil\n}\n}\n@@ -585,6 +606,18 @@ func containsUnsupportedFields(iptip linux.IPTIP) bool {\niptip.InverseFlags != 0\n}\n+func validUnderflow(rule iptables.Rule) bool {\n+ if len(rule.Matchers) != 0 {\n+ return false\n+ }\n+ switch rule.Target.(type) {\n+ case iptables.AcceptTarget, iptables.DropTarget:\n+ return true\n+ default:\n+ return false\n+ }\n+}\n+\nfunc hookFromLinux(hook int) iptables.Hook {\nswitch hook {\ncase linux.NF_INET_PRE_ROUTING:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -52,10 +52,10 @@ func DefaultTables() IPTables {\nTables: map[string]Table{\nTablenameNat: Table{\nRules: []Rule{\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\nRule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\n@@ -74,8 +74,8 @@ func DefaultTables() IPTables {\n},\nTablenameMangle: Table{\nRules: []Rule{\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\nRule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\n@@ -90,9 +90,9 @@ func DefaultTables() IPTables {\n},\nTablenameFilter: Table{\nRules: []Rule{\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: UnconditionalAcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\n+ Rule{Target: AcceptTarget{}},\nRule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\n@@ -149,13 +149,11 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\nfor _, tablename := range it.Priorities[hook] {\nswitch verdict := it.checkTable(hook, pkt, tablename); verdict {\n// If the table returns Accept, move on to the next table.\n- case Accept:\n+ case TableAccept:\ncontinue\n// The Drop verdict is final.\n- case Drop:\n+ case TableDrop:\nreturn false\n- case Stolen, Queue, Repeat, None, Jump, Return, Continue:\n- panic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\ndefault:\npanic(fmt.Sprintf(\"Unknown verdict %v.\", verdict))\n}\n@@ -166,36 +164,58 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n}\n// Precondition: pkt.NetworkHeader is set.\n-func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) Verdict {\n+func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) TableVerdict {\n// Start from ruleIdx and walk the list of rules until a rule gives us\n// a verdict.\ntable := it.Tables[tablename]\nfor ruleIdx := table.BuiltinChains[hook]; ruleIdx < len(table.Rules); ruleIdx++ {\nswitch verdict := it.checkRule(hook, pkt, table, ruleIdx); verdict {\n- // In either of these cases, this table is done with the packet.\n- case Accept, Drop:\n- return verdict\n- // Continue traversing the rules of the table.\n- case Continue:\n+ case RuleAccept:\n+ return TableAccept\n+\n+ case RuleDrop:\n+ return TableDrop\n+\n+ case RuleContinue:\ncontinue\n- case Stolen, Queue, Repeat, None, Jump, Return:\n- panic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\n+\n+ case RuleReturn:\n+ // TODO(gvisor.dev/issue/170): We don't implement jump\n+ // yet, so any Return is from a built-in chain. That\n+ // means we have to to call the underflow.\n+ underflow := table.Rules[table.Underflows[hook]]\n+ // Underflow is guaranteed to be an unconditional\n+ // ACCEPT or DROP.\n+ switch v, _ := underflow.Target.Action(pkt); v {\n+ case RuleAccept:\n+ return TableAccept\n+ case RuleDrop:\n+ return TableDrop\n+ case RuleContinue, RuleReturn:\n+ panic(\"Underflows should only return RuleAccept or RuleDrop.\")\ndefault:\n- panic(fmt.Sprintf(\"Unknown verdict %v.\", verdict))\n+ panic(fmt.Sprintf(\"Unknown verdict: %d\", v))\n}\n+\n+ default:\n+ panic(fmt.Sprintf(\"Unknown verdict: %d\", verdict))\n+ }\n+\n}\n- panic(fmt.Sprintf(\"Traversed past the entire list of iptables rules in table %q.\", tablename))\n+ // We got through the entire table without a decision. Default to DROP\n+ // for safety.\n+ return TableDrop\n}\n// Precondition: pk.NetworkHeader is set.\n-func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) Verdict {\n+func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) RuleVerdict {\nrule := table.Rules[ruleIdx]\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\nif rule.Filter.Protocol != 0 && rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\n- return Continue\n+ return RuleContinue\n}\n// Go through each rule matcher. If they all match, run\n@@ -203,10 +223,10 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\nfor _, matcher := range rule.Matchers {\nmatches, hotdrop := matcher.Match(hook, pkt, \"\")\nif hotdrop {\n- return Drop\n+ return RuleDrop\n}\nif !matches {\n- return Continue\n+ return RuleContinue\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "@@ -21,20 +21,20 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n-// UnconditionalAcceptTarget accepts all packets.\n-type UnconditionalAcceptTarget struct{}\n+// AcceptTarget accepts packets.\n+type AcceptTarget struct{}\n// Action implements Target.Action.\n-func (UnconditionalAcceptTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\n- return Accept, \"\"\n+func (AcceptTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+ return RuleAccept, \"\"\n}\n-// UnconditionalDropTarget denies all packets.\n-type UnconditionalDropTarget struct{}\n+// DropTarget drops packets.\n+type DropTarget struct{}\n// Action implements Target.Action.\n-func (UnconditionalDropTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\n- return Drop, \"\"\n+func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+ return RuleDrop, \"\"\n}\n// ErrorTarget logs an error and drops the packet. It represents a target that\n@@ -42,7 +42,26 @@ func (UnconditionalDropTarget) Action(packet tcpip.PacketBuffer) (Verdict, strin\ntype ErrorTarget struct{}\n// Action implements Target.Action.\n-func (ErrorTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\n- log.Warningf(\"ErrorTarget triggered.\")\n- return Drop, \"\"\n+func (ErrorTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+ log.Debugf(\"ErrorTarget triggered.\")\n+ return RuleDrop, \"\"\n+}\n+\n+// UserChainTarget marks a rule as the beginning of a user chain.\n+type UserChainTarget struct {\n+ Name string\n+}\n+\n+// Action implements Target.Action.\n+func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n+ panic(\"UserChainTarget should never be called.\")\n+}\n+\n+// ReturnTarget returns from the current chain. If the chain is a built-in, the\n+// hook's underflow should be called.\n+type ReturnTarget struct{}\n+\n+// Action implements Target.Action.\n+func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n+ return RuleReturn, \"\"\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -56,44 +56,32 @@ const (\nNumHooks\n)\n-// A Verdict is returned by a rule's target to indicate how traversal of rules\n-// should (or should not) continue.\n-type Verdict int\n+// A TableVerdict is what a table decides should be done with a packet.\n+type TableVerdict int\nconst (\n- // Invalid indicates an unkonwn or erroneous verdict.\n- Invalid Verdict = iota\n+ // TableAccept indicates the packet should continue through netstack.\n+ TableAccept TableVerdict = iota\n- // Accept indicates the packet should continue traversing netstack as\n- // normal.\n- Accept\n-\n- // Drop inicates the packet should be dropped, stopping traversing\n- // netstack.\n- Drop\n-\n- // Stolen indicates the packet was co-opted by the target and should\n- // stop traversing netstack.\n- Stolen\n-\n- // Queue indicates the packet should be queued for userspace processing.\n- Queue\n+ // TableAccept indicates the packet should be dropped.\n+ TableDrop\n+)\n- // Repeat indicates the packet should re-traverse the chains for the\n- // current hook.\n- Repeat\n+// A RuleVerdict is what a rule decides should be done with a packet.\n+type RuleVerdict int\n- // None indicates no verdict was reached.\n- None\n+const (\n+ // RuleAccept indicates the packet should continue through netstack.\n+ RuleAccept RuleVerdict = iota\n- // Jump indicates a jump to another chain.\n- Jump\n+ // RuleContinue indicates the packet should continue to the next rule.\n+ RuleContinue\n- // Continue indicates that traversal should continue at the next rule.\n- Continue\n+ // RuleDrop indicates the packet should be dropped.\n+ RuleDrop\n- // Return indicates that traversal should return to the calling chain.\n- Return\n+ // RuleReturn indicates the packet should return to the previous chain.\n+ RuleReturn\n)\n// IPTables holds all the tables for a netstack.\n@@ -187,5 +175,5 @@ type Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n// Jump, it also returns the name of the chain to jump to.\n- Action(packet tcpip.PacketBuffer) (Verdict, string)\n+ Action(packet tcpip.PacketBuffer) (RuleVerdict, string)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -36,6 +36,10 @@ func init() {\nRegisterTestCase(FilterInputDropTCPSrcPort{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropUDP{})\n+ RegisterTestCase(FilterInputCreateUserChain{})\n+ RegisterTestCase(FilterInputDefaultPolicyAccept{})\n+ RegisterTestCase(FilterInputDefaultPolicyDrop{})\n+ RegisterTestCase(FilterInputReturnUnderflow{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -295,8 +299,119 @@ func (FilterInputRequireProtocolUDP) ContainerAction(ip net.IP) error {\nreturn nil\n}\n-// LocalAction implements TestCase.LocalAction.\nfunc (FilterInputRequireProtocolUDP) LocalAction(ip net.IP) error {\n// No-op.\nreturn nil\n}\n+\n+// FilterInputCreateUserChain tests chain creation.\n+type FilterInputCreateUserChain struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputCreateUserChain) Name() string {\n+ return \"FilterInputCreateUserChain\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputCreateUserChain) ContainerAction(ip net.IP) error {\n+ // Create a chain.\n+ const chainName = \"foochain\"\n+ if err := filterTable(\"-N\", chainName); err != nil {\n+ return err\n+ }\n+\n+ // Add a simple rule to the chain.\n+ return filterTable(\"-A\", chainName, \"-j\", \"DROP\")\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputCreateUserChain) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// FilterInputDefaultPolicyAccept tests the default ACCEPT policy.\n+type FilterInputDefaultPolicyAccept struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDefaultPolicyAccept) Name() string {\n+ return \"FilterInputDefaultPolicyAccept\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDefaultPolicyAccept) ContainerAction(ip net.IP) error {\n+ // Set the default policy to accept, then receive a packet.\n+ if err := filterTable(\"-P\", \"INPUT\", \"ACCEPT\"); err != nil {\n+ return err\n+ }\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDefaultPolicyAccept) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// FilterInputDefaultPolicyDrop tests the default DROP policy.\n+type FilterInputDefaultPolicyDrop struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDefaultPolicyDrop) Name() string {\n+ return \"FilterInputDefaultPolicyDrop\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDefaultPolicyDrop) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-P\", \"INPUT\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for UDP packets on dropPort.\n+ if err := listenUDP(dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"packets on port %d should have been dropped, but got a packet\", dropPort)\n+ } else if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {\n+ return fmt.Errorf(\"error reading: %v\", err)\n+ }\n+\n+ // At this point we know that reading timed out and never received a\n+ // packet.\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDefaultPolicyDrop) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// FilterInputReturnUnderflow tests that -j RETURN in a built-in chain causes\n+// the underflow rule (i.e. default policy) to be executed.\n+type FilterInputReturnUnderflow struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputReturnUnderflow) Name() string {\n+ return \"FilterInputReturnUnderflow\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputReturnUnderflow) ContainerAction(ip net.IP) error {\n+ // Add a RETURN rule followed by an unconditional accept, and set the\n+ // default policy to DROP.\n+ if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"RETURN\"); err != nil {\n+ return err\n+ }\n+ if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+ if err := filterTable(\"-P\", \"INPUT\", \"ACCEPT\"); err != nil {\n+ return err\n+ }\n+\n+ // We should receive packets, as the RETURN rule will trigger the default\n+ // ACCEPT policy.\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputReturnUnderflow) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -214,6 +214,30 @@ func TestFilterInputDropTCPSrcPort(t *testing.T) {\n}\n}\n+func TestFilterInputCreateUserChain(t *testing.T) {\n+ if err := singleTest(FilterInputCreateUserChain{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterInputDefaultPolicyAccept(t *testing.T) {\n+ if err := singleTest(FilterInputDefaultPolicyAccept{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterInputDefaultPolicyDrop(t *testing.T) {\n+ if err := singleTest(FilterInputDefaultPolicyDrop{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterInputReturnUnderflow(t *testing.T) {\n+ if err := singleTest(FilterInputReturnUnderflow{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\nfunc TestFilterOutputDropTCPDestPort(t *testing.T) {\nif err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {\nt.Fatal(err)\n" } ]
Go
Apache License 2.0
google/gvisor
iptables: User chains - Adds creation of user chains via `-N <chainname>` - Adds `-j RETURN` support for built-in chains, which triggers the chain's underflow rule (usually the default policy). - Adds tests for chain creation, default policies, and `-j RETURN' from built-in chains.
259,974
11.02.2020 00:52:23
0
d30a884775556474f1a893fd30460a6edf0a3039
Add definition of arch.ARMTrapFlag. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/arch/arch_aarch64.go", "new_path": "pkg/sentry/arch/arch_aarch64.go", "diff": "@@ -34,6 +34,9 @@ const (\nSyscallWidth = 4\n)\n+// ARMTrapFlag is the mask for the trap flag.\n+const ARMTrapFlag = uint64(1) << 21\n+\n// aarch64FPState is aarch64 floating point state.\ntype aarch64FPState []byte\n" } ]
Go
Apache License 2.0
google/gvisor
Add definition of arch.ARMTrapFlag. Fixes #1708 Signed-off-by: Haibo Xu [email protected] Change-Id: Ib15768692ead17c81c06f7666ca3f0a14064c3a0
259,891
12.02.2020 16:19:06
28,800
6ef63cd7da107d487fda7c48af50fa9802913cd9
We can now create and jump in iptables. For example: $ iptables -N foochain $ iptables -A INPUT -j foochain
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -225,11 +225,14 @@ type XTEntryTarget struct {\n// SizeOfXTEntryTarget is the size of an XTEntryTarget.\nconst SizeOfXTEntryTarget = 32\n-// XTStandardTarget is a builtin target, one of ACCEPT, DROP, JUMP, QUEUE, or\n-// RETURN. It corresponds to struct xt_standard_target in\n+// XTStandardTarget is a built-in target, one of ACCEPT, DROP, JUMP, QUEUE,\n+// RETURN, or jump. It corresponds to struct xt_standard_target in\n// include/uapi/linux/netfilter/x_tables.h.\ntype XTStandardTarget struct {\nTarget XTEntryTarget\n+ // A positive verdict indicates a jump, and is the offset from the\n+ // start of the table to jump to. A negative value means one of the\n+ // other built-in targets.\nVerdict int32\n_ [4]byte\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/BUILD", "new_path": "pkg/sentry/socket/netfilter/BUILD", "diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\n\"extensions.go\",\n\"netfilter.go\",\n+ \"targets.go\",\n\"tcp_matcher.go\",\n\"udp_matcher.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -240,13 +240,15 @@ func marshalTarget(target iptables.Target) []byte {\nreturn marshalErrorTarget(tg.Name)\ncase iptables.ReturnTarget:\nreturn marshalStandardTarget(iptables.RuleReturn)\n+ case JumpTarget:\n+ return marshalJumpTarget(tg)\ndefault:\npanic(fmt.Errorf(\"unknown target of type %T\", target))\n}\n}\nfunc marshalStandardTarget(verdict iptables.RuleVerdict) []byte {\n- nflog(\"convert to binary: marshalling standard target with size %d\", linux.SizeOfXTStandardTarget)\n+ nflog(\"convert to binary: marshalling standard target\")\n// The target's name will be the empty string.\ntarget := linux.XTStandardTarget{\n@@ -274,6 +276,23 @@ func marshalErrorTarget(errorName string) []byte {\nreturn binary.Marshal(ret, usermem.ByteOrder, target)\n}\n+func marshalJumpTarget(jt JumpTarget) []byte {\n+ nflog(\"convert to binary: marshalling jump target\")\n+\n+ // The target's name will be the empty string.\n+ target := linux.XTStandardTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTStandardTarget,\n+ },\n+ // Verdict is overloaded by the ABI. When positive, it holds\n+ // the jump offset from the start of the table.\n+ Verdict: int32(jt.Offset),\n+ }\n+\n+ ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n// translateFromStandardVerdict translates verdicts the same way as the iptables\n// tool.\nfunc translateFromStandardVerdict(verdict iptables.RuleVerdict) int32 {\n@@ -335,7 +354,8 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// Convert input into a list of rules and their offsets.\nvar offset uint32\n- var offsets []uint32\n+ // offsets maps rule byte offsets to their position in table.Rules.\n+ offsets := map[uint32]int{}\nfor entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\nnflog(\"set entries: processing entry at offset %d\", offset)\n@@ -396,11 +416,12 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nTarget: target,\nMatchers: matchers,\n})\n- offsets = append(offsets, offset)\n+ offsets[offset] = int(entryIdx)\noffset += uint32(entry.NextOffset)\nif initialOptValLen-len(optVal) != int(entry.NextOffset) {\nnflog(\"entry NextOffset is %d, but entry took up %d bytes\", entry.NextOffset, initialOptValLen-len(optVal))\n+ return syserr.ErrInvalidArgument\n}\n}\n@@ -409,13 +430,13 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nfor hook, _ := range replace.HookEntry {\nif table.ValidHooks()&(1<<hook) != 0 {\nhk := hookFromLinux(hook)\n- for ruleIdx, offset := range offsets {\n+ for offset, ruleIdx := range offsets {\nif offset == replace.HookEntry[hook] {\ntable.BuiltinChains[hk] = ruleIdx\n}\nif offset == replace.Underflow[hook] {\nif !validUnderflow(table.Rules[ruleIdx]) {\n- nflog(\"underflow for hook %d isn't an unconditional ACCEPT or DROP.\")\n+ nflog(\"underflow for hook %d isn't an unconditional ACCEPT or DROP\")\nreturn syserr.ErrInvalidArgument\n}\ntable.Underflows[hk] = ruleIdx\n@@ -444,16 +465,35 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// - There's some other rule after it.\n// - There are no matchers.\nif ruleIdx == len(table.Rules)-1 {\n- nflog(\"user chain must have a rule or default policy.\")\n+ nflog(\"user chain must have a rule or default policy\")\nreturn syserr.ErrInvalidArgument\n}\nif len(table.Rules[ruleIdx].Matchers) != 0 {\n- nflog(\"user chain's first node must have no matcheres.\")\n+ nflog(\"user chain's first node must have no matchers\")\nreturn syserr.ErrInvalidArgument\n}\ntable.UserChains[target.Name] = ruleIdx + 1\n}\n+ // Set each jump to point to the appropriate rule. Right now they hold byte\n+ // offsets.\n+ for ruleIdx, rule := range table.Rules {\n+ jump, ok := rule.Target.(JumpTarget)\n+ if !ok {\n+ continue\n+ }\n+\n+ // Find the rule corresponding to the jump rule offset.\n+ jumpTo, ok := offsets[jump.Offset]\n+ if !ok {\n+ nflog(\"failed to find a rule to jump to\")\n+ return syserr.ErrInvalidArgument\n+ }\n+ jump.RuleNum = jumpTo\n+ rule.Target = jump\n+ table.Rules[ruleIdx] = rule\n+ }\n+\n// TODO(gvisor.dev/issue/170): Support other chains.\n// Since we only support modifying the INPUT chain right now, make sure\n// all other chains point to ACCEPT rules.\n@@ -548,7 +588,13 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\nbuf = optVal[:linux.SizeOfXTStandardTarget]\nbinary.Unmarshal(buf, usermem.ByteOrder, &standardTarget)\n+ if standardTarget.Verdict < 0 {\n+ // A Verdict < 0 indicates a non-jump verdict.\nreturn translateToStandardTarget(standardTarget.Verdict)\n+ } else {\n+ // A verdict >= 0 indicates a jump.\n+ return JumpTarget{Offset: uint32(standardTarget.Verdict)}, nil\n+ }\ncase errorTargetName:\n// Error target.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/socket/netfilter/targets.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package netfilter\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n+)\n+\n+// JumpTarget implements iptables.Target.\n+type JumpTarget struct {\n+ // Offset is the byte offset of the rule to jump to. It is used for\n+ // marshaling and unmarshaling.\n+ Offset uint32\n+\n+ // RuleNum is the rule to jump to.\n+ RuleNum int\n+}\n+\n+// Action implements iptables.Target.Action.\n+func (jt JumpTarget) Action(tcpip.PacketBuffer) (iptables.RuleVerdict, int) {\n+ return iptables.RuleJump, jt.RuleNum\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -135,25 +135,53 @@ func EmptyFilterTable() Table {\n}\n}\n+// A chainVerdict is what a table decides should be done with a packet.\n+type chainVerdict int\n+\n+const (\n+ // chainAccept indicates the packet should continue through netstack.\n+ chainAccept chainVerdict = iota\n+\n+ // chainAccept indicates the packet should be dropped.\n+ chainDrop\n+\n+ // chainReturn indicates the packet should return to the calling chain\n+ // or the underflow rule of a builtin chain.\n+ chainReturn\n+)\n+\n// Check runs pkt through the rules for hook. It returns true when the packet\n// should continue traversing the network stack and false when it should be\n// dropped.\n//\n// Precondition: pkt.NetworkHeader is set.\nfunc (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n- // TODO(gvisor.dev/issue/170): A lot of this is uncomplicated because\n- // we're missing features. Jumps, the call stack, etc. aren't checked\n- // for yet because we're yet to support them.\n-\n// Go through each table containing the hook.\nfor _, tablename := range it.Priorities[hook] {\n- switch verdict := it.checkTable(hook, pkt, tablename); verdict {\n+ table := it.Tables[tablename]\n+ ruleIdx := table.BuiltinChains[hook]\n+ switch verdict := it.checkChain(hook, pkt, table, ruleIdx); verdict {\n// If the table returns Accept, move on to the next table.\n- case TableAccept:\n+ case chainAccept:\ncontinue\n// The Drop verdict is final.\n- case TableDrop:\n+ case chainDrop:\nreturn false\n+ case chainReturn:\n+ // Any Return from a built-in chain means we have to\n+ // call the underflow.\n+ underflow := table.Rules[table.Underflows[hook]]\n+ switch v, _ := underflow.Target.Action(pkt); v {\n+ case RuleAccept:\n+ continue\n+ case RuleDrop:\n+ return false\n+ case RuleJump, RuleReturn:\n+ panic(\"Underflows should only return RuleAccept or RuleDrop.\")\n+ default:\n+ panic(fmt.Sprintf(\"Unknown verdict: %d\", v))\n+ }\n+\ndefault:\npanic(fmt.Sprintf(\"Unknown verdict %v.\", verdict))\n}\n@@ -164,37 +192,37 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n}\n// Precondition: pkt.NetworkHeader is set.\n-func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) TableVerdict {\n+func (it *IPTables) checkChain(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) chainVerdict {\n// Start from ruleIdx and walk the list of rules until a rule gives us\n// a verdict.\n- table := it.Tables[tablename]\n- for ruleIdx := table.BuiltinChains[hook]; ruleIdx < len(table.Rules); ruleIdx++ {\n- switch verdict := it.checkRule(hook, pkt, table, ruleIdx); verdict {\n+ for ruleIdx < len(table.Rules) {\n+ switch verdict, jumpTo := it.checkRule(hook, pkt, table, ruleIdx); verdict {\ncase RuleAccept:\n- return TableAccept\n+ return chainAccept\ncase RuleDrop:\n- return TableDrop\n-\n- case RuleContinue:\n- continue\n+ return chainDrop\ncase RuleReturn:\n- // TODO(gvisor.dev/issue/170): We don't implement jump\n- // yet, so any Return is from a built-in chain. That\n- // means we have to to call the underflow.\n- underflow := table.Rules[table.Underflows[hook]]\n- // Underflow is guaranteed to be an unconditional\n- // ACCEPT or DROP.\n- switch v, _ := underflow.Target.Action(pkt); v {\n- case RuleAccept:\n- return TableAccept\n- case RuleDrop:\n- return TableDrop\n- case RuleContinue, RuleReturn:\n- panic(\"Underflows should only return RuleAccept or RuleDrop.\")\n+ return chainReturn\n+\n+ case RuleJump:\n+ // \"Jumping\" to the next rule just means we're\n+ // continuing on down the list.\n+ if jumpTo == ruleIdx+1 {\n+ ruleIdx++\n+ continue\n+ }\n+ switch verdict := it.checkChain(hook, pkt, table, jumpTo); verdict {\n+ case chainAccept:\n+ return chainAccept\n+ case chainDrop:\n+ return chainDrop\n+ case chainReturn:\n+ ruleIdx++\n+ continue\ndefault:\n- panic(fmt.Sprintf(\"Unknown verdict: %d\", v))\n+ panic(fmt.Sprintf(\"Unknown verdict: %d\", verdict))\n}\ndefault:\n@@ -205,17 +233,18 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\n// We got through the entire table without a decision. Default to DROP\n// for safety.\n- return TableDrop\n+ return chainDrop\n}\n// Precondition: pk.NetworkHeader is set.\n-func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) RuleVerdict {\n+func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) (RuleVerdict, int) {\nrule := table.Rules[ruleIdx]\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\nif rule.Filter.Protocol != 0 && rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\n- return RuleContinue\n+ // Continue on to the next rule.\n+ return RuleJump, ruleIdx + 1\n}\n// Go through each rule matcher. If they all match, run\n@@ -223,14 +252,14 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\nfor _, matcher := range rule.Matchers {\nmatches, hotdrop := matcher.Match(hook, pkt, \"\")\nif hotdrop {\n- return RuleDrop\n+ return RuleDrop, 0\n}\nif !matches {\n- return RuleContinue\n+ // Continue on to the next rule.\n+ return RuleJump, ruleIdx + 1\n}\n}\n// All the matchers matched, so run the target.\n- verdict, _ := rule.Target.Action(pkt)\n- return verdict\n+ return rule.Target.Action(pkt)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// This file contains various Targets.\n-\npackage iptables\nimport (\n@@ -25,16 +23,16 @@ import (\ntype AcceptTarget struct{}\n// Action implements Target.Action.\n-func (AcceptTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n- return RuleAccept, \"\"\n+func (AcceptTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, int) {\n+ return RuleAccept, 0\n}\n// DropTarget drops packets.\ntype DropTarget struct{}\n// Action implements Target.Action.\n-func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n- return RuleDrop, \"\"\n+func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, int) {\n+ return RuleDrop, 0\n}\n// ErrorTarget logs an error and drops the packet. It represents a target that\n@@ -42,9 +40,9 @@ func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\ntype ErrorTarget struct{}\n// Action implements Target.Action.\n-func (ErrorTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (ErrorTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, int) {\nlog.Debugf(\"ErrorTarget triggered.\")\n- return RuleDrop, \"\"\n+ return RuleDrop, 0\n}\n// UserChainTarget marks a rule as the beginning of a user chain.\n@@ -53,7 +51,7 @@ type UserChainTarget struct {\n}\n// Action implements Target.Action.\n-func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, int) {\npanic(\"UserChainTarget should never be called.\")\n}\n@@ -62,6 +60,6 @@ func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\ntype ReturnTarget struct{}\n// Action implements Target.Action.\n-func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n- return RuleReturn, \"\"\n+func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, int) {\n+ return RuleReturn, 0\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -56,17 +56,6 @@ const (\nNumHooks\n)\n-// A TableVerdict is what a table decides should be done with a packet.\n-type TableVerdict int\n-\n-const (\n- // TableAccept indicates the packet should continue through netstack.\n- TableAccept TableVerdict = iota\n-\n- // TableAccept indicates the packet should be dropped.\n- TableDrop\n-)\n-\n// A RuleVerdict is what a rule decides should be done with a packet.\ntype RuleVerdict int\n@@ -74,12 +63,12 @@ const (\n// RuleAccept indicates the packet should continue through netstack.\nRuleAccept RuleVerdict = iota\n- // RuleContinue indicates the packet should continue to the next rule.\n- RuleContinue\n-\n// RuleDrop indicates the packet should be dropped.\nRuleDrop\n+ // RuleJump indicates the packet should jump to another chain.\n+ RuleJump\n+\n// RuleReturn indicates the packet should return to the previous chain.\nRuleReturn\n)\n@@ -174,6 +163,6 @@ type Matcher interface {\ntype Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n- // Jump, it also returns the name of the chain to jump to.\n- Action(packet tcpip.PacketBuffer) (RuleVerdict, string)\n+ // Jump, it also returns the index of the rule to jump to.\n+ Action(packet tcpip.PacketBuffer) (RuleVerdict, int)\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -26,6 +26,7 @@ const (\nacceptPort = 2402\nsendloopDuration = 2 * time.Second\nnetwork = \"udp4\"\n+ chainName = \"foochain\"\n)\nfunc init() {\n@@ -40,6 +41,12 @@ func init() {\nRegisterTestCase(FilterInputDefaultPolicyAccept{})\nRegisterTestCase(FilterInputDefaultPolicyDrop{})\nRegisterTestCase(FilterInputReturnUnderflow{})\n+ RegisterTestCase(FilterInputSerializeJump{})\n+ RegisterTestCase(FilterInputJumpBasic{})\n+ RegisterTestCase(FilterInputJumpReturn{})\n+ RegisterTestCase(FilterInputJumpReturnDrop{})\n+ RegisterTestCase(FilterInputJumpBuiltin{})\n+ RegisterTestCase(FilterInputJumpTwice{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -267,13 +274,12 @@ func (FilterInputMultiUDPRules) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (FilterInputMultiUDPRules) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n- return err\n- }\n- if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", acceptPort), \"-j\", \"ACCEPT\"); err != nil {\n- return err\n+ rules := [][]string{\n+ {\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"},\n+ {\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", acceptPort), \"-j\", \"ACCEPT\"},\n+ {\"-L\"},\n}\n- return filterTable(\"-L\")\n+ return filterTableRules(rules)\n}\n// LocalAction implements TestCase.LocalAction.\n@@ -314,14 +320,13 @@ func (FilterInputCreateUserChain) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (FilterInputCreateUserChain) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n// Create a chain.\n- const chainName = \"foochain\"\n- if err := filterTable(\"-N\", chainName); err != nil {\n- return err\n- }\n-\n+ {\"-N\", chainName},\n// Add a simple rule to the chain.\n- return filterTable(\"-A\", chainName, \"-j\", \"DROP\")\n+ {\"-A\", chainName, \"-j\", \"DROP\"},\n+ }\n+ return filterTableRules(rules)\n}\n// LocalAction implements TestCase.LocalAction.\n@@ -396,13 +401,12 @@ func (FilterInputReturnUnderflow) Name() string {\nfunc (FilterInputReturnUnderflow) ContainerAction(ip net.IP) error {\n// Add a RETURN rule followed by an unconditional accept, and set the\n// default policy to DROP.\n- if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"RETURN\"); err != nil {\n- return err\n+ rules := [][]string{\n+ {\"-A\", \"INPUT\", \"-j\", \"RETURN\"},\n+ {\"-A\", \"INPUT\", \"-j\", \"DROP\"},\n+ {\"-P\", \"INPUT\", \"ACCEPT\"},\n}\n- if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"DROP\"); err != nil {\n- return err\n- }\n- if err := filterTable(\"-P\", \"INPUT\", \"ACCEPT\"); err != nil {\n+ if err := filterTableRules(rules); err != nil {\nreturn err\n}\n@@ -415,3 +419,178 @@ func (FilterInputReturnUnderflow) ContainerAction(ip net.IP) error {\nfunc (FilterInputReturnUnderflow) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// Verify that we can serialize jumps.\n+type FilterInputSerializeJump struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputSerializeJump) Name() string {\n+ return \"FilterInputSerializeJump\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputSerializeJump) ContainerAction(ip net.IP) error {\n+ // Write a JUMP rule, the serialize it with `-L`.\n+ rules := [][]string{\n+ {\"-N\", chainName},\n+ {\"-A\", \"INPUT\", \"-j\", chainName},\n+ {\"-L\"},\n+ }\n+ return filterTableRules(rules)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputSerializeJump) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// Jump to a chain and execute a rule there.\n+type FilterInputJumpBasic struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputJumpBasic) Name() string {\n+ return \"FilterInputJumpBasic\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputJumpBasic) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n+ {\"-P\", \"INPUT\", \"DROP\"},\n+ {\"-N\", chainName},\n+ {\"-A\", \"INPUT\", \"-j\", chainName},\n+ {\"-A\", chainName, \"-j\", \"ACCEPT\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ // Listen for UDP packets on acceptPort.\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputJumpBasic) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// Jump, return, and execute a rule.\n+type FilterInputJumpReturn struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputJumpReturn) Name() string {\n+ return \"FilterInputJumpReturn\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputJumpReturn) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n+ {\"-N\", chainName},\n+ {\"-P\", \"INPUT\", \"ACCEPT\"},\n+ {\"-A\", \"INPUT\", \"-j\", chainName},\n+ {\"-A\", chainName, \"-j\", \"RETURN\"},\n+ {\"-A\", chainName, \"-j\", \"DROP\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ // Listen for UDP packets on acceptPort.\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputJumpReturn) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+type FilterInputJumpReturnDrop struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputJumpReturnDrop) Name() string {\n+ return \"FilterInputJumpReturnDrop\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputJumpReturnDrop) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n+ {\"-N\", chainName},\n+ {\"-A\", \"INPUT\", \"-j\", chainName},\n+ {\"-A\", \"INPUT\", \"-j\", \"DROP\"},\n+ {\"-A\", chainName, \"-j\", \"RETURN\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ // Listen for UDP packets on dropPort.\n+ if err := listenUDP(dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"packets on port %d should have been dropped, but got a packet\", dropPort)\n+ } else if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {\n+ return fmt.Errorf(\"error reading: %v\", err)\n+ }\n+\n+ // At this point we know that reading timed out and never received a\n+ // packet.\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputJumpReturnDrop) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, dropPort, sendloopDuration)\n+}\n+\n+// Jumping to a top-levl chain is illegal.\n+type FilterInputJumpBuiltin struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputJumpBuiltin) Name() string {\n+ return \"FilterInputJumpBuiltin\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputJumpBuiltin) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"OUTPUT\"); err == nil {\n+ return fmt.Errorf(\"iptables should be unable to jump to a built-in chain\")\n+ }\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputJumpBuiltin) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// Jump twice, then return twice and execute a rule.\n+type FilterInputJumpTwice struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputJumpTwice) Name() string {\n+ return \"FilterInputJumpTwice\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputJumpTwice) ContainerAction(ip net.IP) error {\n+ const chainName2 = chainName + \"2\"\n+ rules := [][]string{\n+ {\"-P\", \"INPUT\", \"DROP\"},\n+ {\"-N\", chainName},\n+ {\"-N\", chainName2},\n+ {\"-A\", \"INPUT\", \"-j\", chainName},\n+ {\"-A\", chainName, \"-j\", chainName2},\n+ {\"-A\", \"INPUT\", \"-j\", \"ACCEPT\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ // UDP packets should jump and return twice, eventually hitting the\n+ // ACCEPT rule.\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputJumpTwice) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -249,3 +249,39 @@ func TestFilterOutputDropTCPSrcPort(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\n+func TestJumpSerialize(t *testing.T) {\n+ if err := singleTest(FilterInputSerializeJump{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestJumpBasic(t *testing.T) {\n+ if err := singleTest(FilterInputJumpBasic{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestJumpReturn(t *testing.T) {\n+ if err := singleTest(FilterInputJumpReturn{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestJumpReturnDrop(t *testing.T) {\n+ if err := singleTest(FilterInputJumpReturnDrop{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestJumpBuiltin(t *testing.T) {\n+ if err := singleTest(FilterInputJumpBuiltin{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestJumpTwice(t *testing.T) {\n+ if err := singleTest(FilterInputJumpTwice{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_util.go", "new_path": "test/iptables/iptables_util.go", "diff": "@@ -35,6 +35,16 @@ func filterTable(args ...string) error {\nreturn nil\n}\n+// filterTableRules is like filterTable, but runs multiple iptables commands.\n+func filterTableRules(argsList [][]string) error {\n+ for _, args := range argsList {\n+ if err := filterTable(args...); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n+\n// listenUDP listens on a UDP port and returns the value of net.Conn.Read() for\n// the first read on that port.\nfunc listenUDP(port int, timeout time.Duration) error {\n" } ]
Go
Apache License 2.0
google/gvisor
We can now create and jump in iptables. For example: $ iptables -N foochain $ iptables -A INPUT -j foochain
259,955
18.02.2020 16:03:32
-28,800
03cee0656c9fd8cf9509c3a91baf72db4a8f6d28
scope.add should only record the first position
[ { "change_type": "MODIFY", "old_path": "tools/go_generics/globals/scope.go", "new_path": "tools/go_generics/globals/scope.go", "diff": "@@ -72,6 +72,10 @@ func (s *scope) deepLookup(n string) *symbol {\n}\nfunc (s *scope) add(name string, kind SymKind, pos token.Pos) {\n+ if s.syms[name] != nil {\n+ return\n+ }\n+\ns.syms[name] = &symbol{\nkind: kind,\npos: pos,\n" } ]
Go
Apache License 2.0
google/gvisor
scope.add should only record the first position
259,896
18.02.2020 11:30:42
28,800
b30b7f3422202232ad1c385a7ac0d775151fee2f
Add nat table support for iptables. Add nat table support for Prerouting hook with Redirect option. Add tests to check redirect of ports.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -250,6 +250,33 @@ type XTErrorTarget struct {\n// SizeOfXTErrorTarget is the size of an XTErrorTarget.\nconst SizeOfXTErrorTarget = 64\n+// NfNATIPV4Range. It corresponds to struct nf_nat_ipv4_range\n+// in include/uapi/linux/netfilter/nf_nat.h.\n+type NfNATIPV4Range struct {\n+ Flags uint32\n+ MinIP [4]byte\n+ MaxIP [4]byte\n+ MinPort uint16\n+ MaxPort uint16\n+}\n+\n+// NfNATIPV4MultiRangeCompat. It corresponds to struct\n+// nf_nat_ipv4_multi_range_compat in include/uapi/linux/netfilter/nf_nat.h.\n+type NfNATIPV4MultiRangeCompat struct {\n+ Rangesize uint32\n+ RangeIPV4 [1]NfNATIPV4Range\n+}\n+\n+// XTRedirectTarget triggers a redirect when reached.\n+type XTRedirectTarget struct {\n+ Target XTEntryTarget\n+ NfRange NfNATIPV4MultiRangeCompat\n+ _ [4]byte\n+}\n+\n+// SizeOfXTRedirectTarget is the size of an XTRedirectTarget.\n+const SizeOfXTRedirectTarget = 56\n+\n// IPTGetinfo is the argument for the IPT_SO_GET_INFO sockopt. It corresponds\n// to struct ipt_getinfo in include/uapi/linux/netfilter_ipv4/ip_tables.h.\ntype IPTGetinfo struct {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -35,6 +35,11 @@ import (\n// shouldn't be reached - an error has occurred if we fall through to one.\nconst errorTargetName = \"ERROR\"\n+// redirectTargetName is used to mark targets as redirect targets. Redirect\n+// targets should be reached for only NAT and Mangle tables. These targets will\n+// change the destination port/destination IP for packets.\n+const redirectTargetName = \"REDIRECT\"\n+\n// Metadata is used to verify that we are correctly serializing and\n// deserializing iptables into structs consumable by the iptables tool. We save\n// a metadata struct when the tables are written, and when they are read out we\n@@ -240,6 +245,8 @@ func marshalTarget(target iptables.Target) []byte {\nreturn marshalErrorTarget(tg.Name)\ncase iptables.ReturnTarget:\nreturn marshalStandardTarget(iptables.RuleReturn)\n+ case iptables.RedirectTarget:\n+ return marshalRedirectTarget()\ndefault:\npanic(fmt.Errorf(\"unknown target of type %T\", target))\n}\n@@ -274,6 +281,18 @@ func marshalErrorTarget(errorName string) []byte {\nreturn binary.Marshal(ret, usermem.ByteOrder, target)\n}\n+func marshalRedirectTarget() []byte {\n+ // This is a redirect target named redirect\n+ target := linux.XTRedirectTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTRedirectTarget,\n+ },\n+ }\n+\n+ ret := make([]byte, 0, linux.SizeOfXTRedirectTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n// translateFromStandardVerdict translates verdicts the same way as the iptables\n// tool.\nfunc translateFromStandardVerdict(verdict iptables.RuleVerdict) int32 {\n@@ -326,6 +345,8 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nswitch replace.Name.String() {\ncase iptables.TablenameFilter:\ntable = iptables.EmptyFilterTable()\n+ case iptables.TablenameNat:\n+ table = iptables.EmptyNatTable()\ndefault:\nnflog(\"we don't yet support writing to the %q table (gvisor.dev/issue/170)\", replace.Name.String())\nreturn syserr.ErrInvalidArgument\n@@ -455,10 +476,11 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\n// TODO(gvisor.dev/issue/170): Support other chains.\n- // Since we only support modifying the INPUT chain right now, make sure\n- // all other chains point to ACCEPT rules.\n+ // Since we only support modifying the INPUT chain and redirect for\n+ // PREROUTING chain right now, make sure all other chains point to\n+ // ACCEPT rules.\nfor hook, ruleIdx := range table.BuiltinChains {\n- if hook != iptables.Input {\n+ if hook != iptables.Input && hook != iptables.Prerouting {\nif _, ok := table.Rules[ruleIdx].Target.(iptables.AcceptTarget); !ok {\nnflog(\"hook %d is unsupported.\", hook)\nreturn syserr.ErrInvalidArgument\n@@ -575,6 +597,36 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\nnflog(\"set entries: user-defined target %q\", name)\nreturn iptables.UserChainTarget{Name: name}, nil\n}\n+\n+ case redirectTargetName:\n+ // Redirect target.\n+ if len(optVal) < linux.SizeOfXTRedirectTarget {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: optVal has insufficient size for redirect target %d\", len(optVal))\n+ }\n+\n+ var redirectTarget linux.XTRedirectTarget\n+ buf = optVal[:linux.SizeOfXTRedirectTarget]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &redirectTarget)\n+\n+ // Copy linux.XTRedirectTarget to iptables.RedirectTarget.\n+ var target iptables.RedirectTarget\n+ nfRange := redirectTarget.NfRange\n+\n+ target.RangeSize = nfRange.Rangesize\n+ target.Flags = nfRange.RangeIPV4[0].Flags\n+\n+ target.MinIP = tcpip.Address(nfRange.RangeIPV4[0].MinIP[:])\n+ target.MaxIP = tcpip.Address(nfRange.RangeIPV4[0].MaxIP[:])\n+\n+ // Convert port from big endian to little endian.\n+ port := make([]byte, 2)\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4[0].MinPort)\n+ target.MinPort = binary.LittleEndian.Uint16(port)\n+\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4[0].MaxPort)\n+ target.MaxPort = binary.LittleEndian.Uint16(port)\n+ return target, nil\n+\n}\n// Unknown target.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -135,6 +135,27 @@ func EmptyFilterTable() Table {\n}\n}\n+// EmptyNatTable returns a Table with no rules and the filter table chains\n+// mapped to HookUnset.\n+func EmptyNatTable() Table {\n+ return Table{\n+ Rules: []Rule{},\n+ BuiltinChains: map[Hook]int{\n+ Prerouting: HookUnset,\n+ Input: HookUnset,\n+ Output: HookUnset,\n+ Postrouting: HookUnset,\n+ },\n+ Underflows: map[Hook]int{\n+ Prerouting: HookUnset,\n+ Input: HookUnset,\n+ Output: HookUnset,\n+ Postrouting: HookUnset,\n+ },\n+ UserChains: map[string]int{},\n+ }\n+}\n+\n// Check runs pkt through the rules for hook. It returns true when the packet\n// should continue traversing the network stack and false when it should be\n// dropped.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "@@ -19,6 +19,7 @@ package iptables\nimport (\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n// AcceptTarget accepts packets.\n@@ -65,3 +66,26 @@ type ReturnTarget struct{}\nfunc (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\nreturn RuleReturn, \"\"\n}\n+\n+// RedirectTarget redirects the packet by modifying the destination port/IP.\n+type RedirectTarget struct {\n+ RangeSize uint32\n+ Flags uint32\n+ MinIP tcpip.Address\n+ MaxIP tcpip.Address\n+ MinPort uint16\n+ MaxPort uint16\n+}\n+\n+// Action implements Target.Action.\n+func (rt RedirectTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+ log.Infof(\"RedirectTarget triggered.\")\n+\n+ // TODO(gvisor.dev/issue/170): Checking only for UDP protocol.\n+ // We're yet to support for TCP protocol.\n+ headerView := packet.Data.First()\n+ h := header.UDP(headerView)\n+ h.SetDestinationPort(rt.MinPort)\n+\n+ return RuleAccept, \"\"\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n)\n// NIC represents a \"network interface card\" to which the networking stack is\n@@ -1012,6 +1013,7 @@ func (n *NIC) leaveGroupLocked(addr tcpip.Address) *tcpip.Error {\nfunc handlePacket(protocol tcpip.NetworkProtocolNumber, dst, src tcpip.Address, localLinkAddr, remotelinkAddr tcpip.LinkAddress, ref *referencedNetworkEndpoint, pkt tcpip.PacketBuffer) {\nr := makeRoute(protocol, dst, src, localLinkAddr, ref, false /* handleLocal */, false /* multicastLoop */)\nr.RemoteLinkAddress = remotelinkAddr\n+\nref.ep.HandlePacket(&r, pkt)\nref.decRef()\n}\n@@ -1082,6 +1084,27 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\nn.stack.stats.IP.InvalidSourceAddressesReceived.Increment()\nreturn\n}\n+\n+ // TODO(gvisor.dev/issue/170): Not supporting iptables for IPv6 yet.\n+ if protocol == header.IPv4ProtocolNumber {\n+ newPkt := pkt.Clone()\n+\n+ headerView := newPkt.Data.First()\n+ h := header.IPv4(headerView)\n+ newPkt.NetworkHeader = headerView[:h.HeaderLength()]\n+\n+ hlen := int(h.HeaderLength())\n+ tlen := int(h.TotalLength())\n+ newPkt.Data.TrimFront(hlen)\n+ newPkt.Data.CapLength(tlen - hlen)\n+\n+ ipt := n.stack.IPTables()\n+ if ok := ipt.Check(iptables.Prerouting, newPkt); !ok {\n+ // iptables is telling us to drop the packet.\n+ return\n+ }\n+ }\n+\nif ref := n.getRef(protocol, dst); ref != nil {\nhandlePacket(protocol, dst, src, linkEP.LinkAddress(), remote, ref, pkt)\nreturn\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -196,12 +196,24 @@ func TestNATRedirectUDPPort(t *testing.T) {\n}\n}\n+func TestNATRedirectTCPPort(t *testing.T) {\n+ if err := singleTest(NATRedirectTCPPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\nfunc TestNATDropUDP(t *testing.T) {\nif err := singleTest(NATDropUDP{}); err != nil {\nt.Fatal(err)\n}\n}\n+func TestNATAcceptAll(t *testing.T) {\n+ if err := singleTest(NATAcceptAll{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\nfunc TestFilterInputDropTCPDestPort(t *testing.T) {\nif err := singleTest(FilterInputDropTCPDestPort{}); err != nil {\nt.Fatal(err)\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_util.go", "new_path": "test/iptables/iptables_util.go", "diff": "@@ -35,6 +35,16 @@ func filterTable(args ...string) error {\nreturn nil\n}\n+// natTable calls `iptables -t nat` with the given args.\n+func natTable(args ...string) error {\n+ args = append([]string{\"-t\", \"nat\"}, args...)\n+ cmd := exec.Command(iptablesBinary, args...)\n+ if out, err := cmd.CombinedOutput(); err != nil {\n+ return fmt.Errorf(\"error running iptables with args %v\\nerror: %v\\noutput: %s\", args, err, string(out))\n+ }\n+ return nil\n+}\n+\n// listenUDP listens on a UDP port and returns the value of net.Conn.Read() for\n// the first read on that port.\nfunc listenUDP(port int, timeout time.Duration) error {\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/nat.go", "new_path": "test/iptables/nat.go", "diff": "@@ -25,7 +25,9 @@ const (\nfunc init() {\nRegisterTestCase(NATRedirectUDPPort{})\n+ RegisterTestCase(NATRedirectTCPPort{})\nRegisterTestCase(NATDropUDP{})\n+ RegisterTestCase(NATAcceptAll{})\n}\n// NATRedirectUDPPort tests that packets are redirected to different port.\n@@ -38,13 +40,14 @@ func (NATRedirectUDPPort) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (NATRedirectUDPPort) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\nreturn err\n}\nif err := listenUDP(redirectPort, sendloopDuration); err != nil {\nreturn fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", redirectPort, err)\n}\n+\nreturn nil\n}\n@@ -53,6 +56,37 @@ func (NATRedirectUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+// NATRedirectTCPPort tests that connections are redirected on specified ports.\n+type NATRedirectTCPPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATRedirectTCPPort) Name() string {\n+ return \"NATRedirectTCPPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATRedirectTCPPort) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--dport\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ return err\n+ }\n+\n+ // Listen for TCP packets on redirect port.\n+ if err := listenTCP(redirectPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"connection on port %d should be accepted, but got error %v\", redirectPort, err)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATRedirectTCPPort) LocalAction(ip net.IP) error {\n+ if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"connection destined to port %d should be accepted, but got error %v\", dropPort, err)\n+ }\n+\n+ return nil\n+}\n+\n// NATDropUDP tests that packets are not received in ports other than redirect port.\ntype NATDropUDP struct{}\n@@ -63,7 +97,7 @@ func (NATDropUDP) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (NATDropUDP) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\nreturn err\n}\n@@ -78,3 +112,29 @@ func (NATDropUDP) ContainerAction(ip net.IP) error {\nfunc (NATDropUDP) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// NATAcceptAll tests that all UDP packets are accepted.\n+type NATAcceptAll struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATAcceptAll) Name() string {\n+ return \"NATAcceptAll\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATAcceptAll) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"ACCEPT\"); err != nil {\n+ return err\n+ }\n+\n+ if err := listenUDP(acceptPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", acceptPort, err)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATAcceptAll) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add nat table support for iptables. Add nat table support for Prerouting hook with Redirect option. Add tests to check redirect of ports.
259,891
18.02.2020 21:20:41
28,800
92d2d78876a938871327685e1104d7b4ff46986e
Fix mis-named comment.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/registration.go", "new_path": "pkg/tcpip/stack/registration.go", "diff": "@@ -277,7 +277,7 @@ type NetworkProtocol interface {\n// DefaultPrefixLen returns the protocol's default prefix length.\nDefaultPrefixLen() int\n- // ParsePorts returns the source and destination addresses stored in a\n+ // ParseAddresses returns the source and destination addresses stored in a\n// packet of this protocol.\nParseAddresses(v buffer.View) (src, dst tcpip.Address)\n" } ]
Go
Apache License 2.0
google/gvisor
Fix mis-named comment.
259,858
19.02.2020 18:27:48
28,800
ec5630527bc4473081048d2d13d1dcfadc6c7cdd
Add statefile command to runsc.
[ { "change_type": "MODIFY", "old_path": "runsc/cmd/BUILD", "new_path": "runsc/cmd/BUILD", "diff": "@@ -31,6 +31,7 @@ go_library(\n\"spec.go\",\n\"start.go\",\n\"state.go\",\n+ \"statefile.go\",\n\"syscalls.go\",\n\"wait.go\",\n],\n@@ -43,6 +44,8 @@ go_library(\n\"//pkg/sentry/control\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n+ \"//pkg/state\",\n+ \"//pkg/state/statefile\",\n\"//pkg/sync\",\n\"//pkg/unet\",\n\"//pkg/urpc\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "runsc/cmd/statefile.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package cmd\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"os\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/pkg/state\"\n+ \"gvisor.dev/gvisor/pkg/state/statefile\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+// Statefile implements subcommands.Command for the \"statefile\" command.\n+type Statefile struct {\n+ list bool\n+ get string\n+ key string\n+ output string\n+ html bool\n+}\n+\n+// Name implements subcommands.Command.\n+func (*Statefile) Name() string {\n+ return \"state\"\n+}\n+\n+// Synopsis implements subcommands.Command.\n+func (*Statefile) Synopsis() string {\n+ return \"shows information about a statefile\"\n+}\n+\n+// Usage implements subcommands.Command.\n+func (*Statefile) Usage() string {\n+ return `statefile [flags] <statefile>`\n+}\n+\n+// SetFlags implements subcommands.Command.\n+func (s *Statefile) SetFlags(f *flag.FlagSet) {\n+ f.BoolVar(&s.list, \"list\", false, \"lists the metdata in the statefile.\")\n+ f.StringVar(&s.get, \"get\", \"\", \"extracts the given metadata key.\")\n+ f.StringVar(&s.key, \"key\", \"\", \"the integrity key for the file.\")\n+ f.StringVar(&s.output, \"output\", \"\", \"target to write the result.\")\n+ f.BoolVar(&s.html, \"html\", false, \"outputs in HTML format.\")\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (s *Statefile) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+ // Check arguments.\n+ if s.list && s.get != \"\" {\n+ Fatalf(\"error: can't specify -list and -get simultaneously.\")\n+ }\n+\n+ // Setup output.\n+ var output = os.Stdout // Default.\n+ if s.output != \"\" {\n+ f, err := os.OpenFile(s.output, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)\n+ if err != nil {\n+ Fatalf(\"error opening output: %v\", err)\n+ }\n+ defer func() {\n+ if err := f.Close(); err != nil {\n+ Fatalf(\"error flushing output: %v\", err)\n+ }\n+ }()\n+ output = f\n+ }\n+\n+ // Open the file.\n+ if f.NArg() != 1 {\n+ f.Usage()\n+ return subcommands.ExitUsageError\n+ }\n+ input, err := os.Open(f.Arg(0))\n+ if err != nil {\n+ Fatalf(\"error opening input: %v\\n\", err)\n+ }\n+\n+ if s.html {\n+ fmt.Fprintf(output, \"<html><body>\\n\")\n+ defer fmt.Fprintf(output, \"</body></html>\\n\")\n+ }\n+\n+ // Dump the full file?\n+ if !s.list && s.get == \"\" {\n+ var key []byte\n+ if s.key != \"\" {\n+ key = []byte(s.key)\n+ }\n+ rc, _, err := statefile.NewReader(input, key)\n+ if err != nil {\n+ Fatalf(\"error parsing statefile: %v\", err)\n+ }\n+ if err := state.PrettyPrint(output, rc, s.html); err != nil {\n+ Fatalf(\"error printing state: %v\", err)\n+ }\n+ return subcommands.ExitSuccess\n+ }\n+\n+ // Load just the metadata.\n+ metadata, err := statefile.MetadataUnsafe(input)\n+ if err != nil {\n+ Fatalf(\"error reading metadata: %v\", err)\n+ }\n+\n+ // Is it a single key?\n+ if s.get != \"\" {\n+ val, ok := metadata[s.get]\n+ if !ok {\n+ Fatalf(\"metadata key %s: not found\", s.get)\n+ }\n+ fmt.Fprintf(output, \"%s\\n\", val)\n+ return subcommands.ExitSuccess\n+ }\n+\n+ // List all keys.\n+ if s.html {\n+ fmt.Fprintf(output, \" <ul>\\n\")\n+ defer fmt.Fprintf(output, \" </ul>\\n\")\n+ }\n+ for key := range metadata {\n+ if s.html {\n+ fmt.Fprintf(output, \" <li>%s</li>\\n\", key)\n+ } else {\n+ fmt.Fprintf(output, \"%s\\n\", key)\n+ }\n+ }\n+ return subcommands.ExitSuccess\n+}\n" }, { "change_type": "MODIFY", "old_path": "runsc/main.go", "new_path": "runsc/main.go", "diff": "@@ -116,8 +116,8 @@ func main() {\nsubcommands.Register(new(cmd.Resume), \"\")\nsubcommands.Register(new(cmd.Run), \"\")\nsubcommands.Register(new(cmd.Spec), \"\")\n- subcommands.Register(new(cmd.Start), \"\")\nsubcommands.Register(new(cmd.State), \"\")\n+ subcommands.Register(new(cmd.Start), \"\")\nsubcommands.Register(new(cmd.Wait), \"\")\n// Register internal commands with the internal group name. This causes\n@@ -127,6 +127,7 @@ func main() {\nsubcommands.Register(new(cmd.Boot), internalGroup)\nsubcommands.Register(new(cmd.Debug), internalGroup)\nsubcommands.Register(new(cmd.Gofer), internalGroup)\n+ subcommands.Register(new(cmd.Statefile), internalGroup)\n// All subcommands must be registered before flag parsing.\nflag.Parse()\n" } ]
Go
Apache License 2.0
google/gvisor
Add statefile command to runsc. PiperOrigin-RevId: 296105337
259,858
20.02.2020 12:32:31
28,800
72187fa7a9e1f3ee9d021681f4465777f91c13fe
Import tags.bzl directly from tools/defs.bzl. This simplifies the script slightly.
[ { "change_type": "MODIFY", "old_path": "tools/bazeldefs/defs.bzl", "new_path": "tools/bazeldefs/defs.bzl", "diff": "@@ -8,7 +8,6 @@ load(\"@rules_pkg//:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\nload(\"@io_bazel_rules_docker//go:image.bzl\", _go_image = \"go_image\")\nload(\"@io_bazel_rules_docker//container:container.bzl\", _container_image = \"container_image\")\nload(\"@pydeps//:requirements.bzl\", _py_requirement = \"requirement\")\n-load(\"//tools/bazeldefs:tags.bzl\", _go_suffixes = \"go_suffixes\")\ncontainer_image = _container_image\ncc_binary = _cc_binary\n@@ -19,7 +18,6 @@ cc_test = _cc_test\ncc_toolchain = \"@bazel_tools//tools/cpp:current_cc_toolchain\"\ngo_image = _go_image\ngo_embed_data = _go_embed_data\n-go_suffixes = _go_suffixes\ngtest = \"@com_google_googletest//:gtest\"\ngbenchmark = \"@com_google_benchmark//:benchmark\"\nloopback = \"//tools/bazeldefs:loopback\"\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -7,7 +7,8 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\n-load(\"//tools/bazeldefs:defs.bzl\", \"go_suffixes\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _gbenchmark = \"gbenchmark\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n+load(\"//tools/bazeldefs:defs.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _gbenchmark = \"gbenchmark\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n+load(\"//tools/bazeldefs:tags.bzl\", \"go_suffixes\")\n# Delegate directly.\ncc_binary = _cc_binary\n" } ]
Go
Apache License 2.0
google/gvisor
Import tags.bzl directly from tools/defs.bzl. This simplifies the script slightly. PiperOrigin-RevId: 296272077
259,974
19.02.2020 08:09:16
0
5d711c329a7973dae37b654528949d62a131319a
Force downloading new version of org_golang_x_sys. ARM64 PTRACE_SYSEMU support was added to Linux kernal from v5.3 and the corresponding support in golang is also enabled in the latest org.golang/x/sys repository. Updates
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -33,6 +33,20 @@ load(\"@bazel_gazelle//:deps.bzl\", \"gazelle_dependencies\", \"go_repository\")\ngazelle_dependencies()\n+# TODO(gvisor.dev/issue/1876): Move the statement to \"External repositories\"\n+# block below once 1876 is fixed.\n+#\n+# The com_google_protobuf repository below would trigger downloading a older\n+# version of org_golang_x_sys. If putting this repository statment in a place\n+# after that of the com_google_protobuf, this statement will not work as\n+# expectd to download a new version of org_golang_x_sys.\n+go_repository(\n+ name = \"org_golang_x_sys\",\n+ importpath = \"golang.org/x/sys\",\n+ sum = \"h1:72l8qCJ1nGxMGH26QVBVIxKd/D34cfGt0OvrPtpemyY=\",\n+ version = \"v0.0.0-20191220220014-0732a990476f\",\n+)\n+\n# Load C++ rules.\nhttp_archive(\nname = \"rules_cc\",\n@@ -256,13 +270,6 @@ go_repository(\nversion = \"v0.0.0-20190423024810-112230192c58\",\n)\n-go_repository(\n- name = \"org_golang_x_sys\",\n- importpath = \"golang.org/x/sys\",\n- sum = \"h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=\",\n- version = \"v0.0.0-20190215142949-d0b11bdaac8a\",\n-)\n-\ngo_repository(\nname = \"org_golang_x_time\",\ncommit = \"c4c64cad1fd0a1a8dab2523e04e61d35308e131e\",\n" } ]
Go
Apache License 2.0
google/gvisor
Force downloading new version of org_golang_x_sys. ARM64 PTRACE_SYSEMU support was added to Linux kernal from v5.3 and the corresponding support in golang is also enabled in the latest org.golang/x/sys repository. Updates #1876 Signed-off-by: Haibo Xu <[email protected]> Change-Id: I10750c4c8b68f6f68d0a4d828e266966434c92fe
260,004
21.02.2020 09:53:56
28,800
97c07242c37e56f6cfdc52036d554052ba95f2ae
Use Route.MaxHeaderLength when constructing NDP RS Test: stack_test.TestRouterSolicitation
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp.go", "new_path": "pkg/tcpip/stack/ndp.go", "diff": "@@ -1235,7 +1235,7 @@ func (ndp *ndpState) startSolicitingRouters() {\n}\npayloadSize := header.ICMPv6HeaderSize + header.NDPRSMinimumSize\n- hdr := buffer.NewPrependable(header.IPv6MinimumSize + payloadSize)\n+ hdr := buffer.NewPrependable(int(r.MaxHeaderLength()) + payloadSize)\npkt := header.ICMPv6(hdr.Prepend(payloadSize))\npkt.SetType(header.ICMPv6RouterSolicit)\npkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -267,6 +267,17 @@ func (n *ndpDispatcher) OnDHCPv6Configuration(nicID tcpip.NICID, configuration s\n}\n}\n+// channelLinkWithHeaderLength is a channel.Endpoint with a configurable\n+// header length.\n+type channelLinkWithHeaderLength struct {\n+ *channel.Endpoint\n+ headerLength uint16\n+}\n+\n+func (l *channelLinkWithHeaderLength) MaxHeaderLength() uint16 {\n+ return l.headerLength\n+}\n+\n// Check e to make sure that the event is for addr on nic with ID 1, and the\n// resolved flag set to resolved with the specified err.\nfunc checkDADEvent(e ndpDADEvent, nicID tcpip.NICID, addr tcpip.Address, resolved bool, err *tcpip.Error) string {\n@@ -323,21 +334,46 @@ func TestDADDisabled(t *testing.T) {\n// DAD for various values of DupAddrDetectTransmits and RetransmitTimer.\n// Included in the subtests is a test to make sure that an invalid\n// RetransmitTimer (<1ms) values get fixed to the default RetransmitTimer of 1s.\n+// This tests also validates the NDP NS packet that is transmitted.\nfunc TestDADResolve(t *testing.T) {\nconst nicID = 1\ntests := []struct {\nname string\n+ linkHeaderLen uint16\ndupAddrDetectTransmits uint8\nretransTimer time.Duration\nexpectedRetransmitTimer time.Duration\n}{\n- {\"1:1s:1s\", 1, time.Second, time.Second},\n- {\"2:1s:1s\", 2, time.Second, time.Second},\n- {\"1:2s:2s\", 1, 2 * time.Second, 2 * time.Second},\n+ {\n+ name: \"1:1s:1s\",\n+ dupAddrDetectTransmits: 1,\n+ retransTimer: time.Second,\n+ expectedRetransmitTimer: time.Second,\n+ },\n+ {\n+ name: \"2:1s:1s\",\n+ linkHeaderLen: 1,\n+ dupAddrDetectTransmits: 2,\n+ retransTimer: time.Second,\n+ expectedRetransmitTimer: time.Second,\n+ },\n+ {\n+ name: \"1:2s:2s\",\n+ linkHeaderLen: 2,\n+ dupAddrDetectTransmits: 1,\n+ retransTimer: 2 * time.Second,\n+ expectedRetransmitTimer: 2 * time.Second,\n+ },\n// 0s is an invalid RetransmitTimer timer and will be fixed to\n// the default RetransmitTimer value of 1s.\n- {\"1:0s:1s\", 1, 0, time.Second},\n+ {\n+ name: \"1:0s:1s\",\n+ linkHeaderLen: 3,\n+ dupAddrDetectTransmits: 1,\n+ retransTimer: 0,\n+ expectedRetransmitTimer: time.Second,\n+ },\n}\nfor _, test := range tests {\n@@ -356,10 +392,13 @@ func TestDADResolve(t *testing.T) {\nopts.NDPConfigs.RetransmitTimer = test.retransTimer\nopts.NDPConfigs.DupAddrDetectTransmits = test.dupAddrDetectTransmits\n- e := channel.New(int(test.dupAddrDetectTransmits), 1280, linkAddr1)\n- e.LinkEPCapabilities |= stack.CapabilityResolutionRequired\n+ e := channelLinkWithHeaderLength{\n+ Endpoint: channel.New(int(test.dupAddrDetectTransmits), 1280, linkAddr1),\n+ headerLength: test.linkHeaderLen,\n+ }\n+ e.Endpoint.LinkEPCapabilities |= stack.CapabilityResolutionRequired\ns := stack.New(opts)\n- if err := s.CreateNIC(nicID, e); err != nil {\n+ if err := s.CreateNIC(nicID, &e); err != nil {\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n}\n@@ -445,6 +484,10 @@ func TestDADResolve(t *testing.T) {\nchecker.NDPNSTargetAddress(addr1),\nchecker.NDPNSOptions(nil),\n))\n+\n+ if l, want := p.Pkt.Header.AvailableLength(), int(test.linkHeaderLen); l != want {\n+ t.Errorf(\"got p.Pkt.Header.AvailableLength() = %d; want = %d\", l, want)\n+ }\n}\n})\n}\n@@ -3336,8 +3379,11 @@ func TestDHCPv6ConfigurationFromNDPDA(t *testing.T) {\nfunc TestRouterSolicitation(t *testing.T) {\nt.Parallel()\n+ const nicID = 1\n+\ntests := []struct {\nname string\n+ linkHeaderLen uint16\nmaxRtrSolicit uint8\nrtrSolicitInt time.Duration\neffectiveRtrSolicitInt time.Duration\n@@ -3354,6 +3400,7 @@ func TestRouterSolicitation(t *testing.T) {\n},\n{\nname: \"Two RS with delay\",\n+ linkHeaderLen: 1,\nmaxRtrSolicit: 2,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3362,6 +3409,7 @@ func TestRouterSolicitation(t *testing.T) {\n},\n{\nname: \"Single RS without delay\",\n+ linkHeaderLen: 2,\nmaxRtrSolicit: 1,\nrtrSolicitInt: time.Second,\neffectiveRtrSolicitInt: time.Second,\n@@ -3370,6 +3418,7 @@ func TestRouterSolicitation(t *testing.T) {\n},\n{\nname: \"Two RS without delay and invalid zero interval\",\n+ linkHeaderLen: 3,\nmaxRtrSolicit: 2,\nrtrSolicitInt: 0,\neffectiveRtrSolicitInt: 4 * time.Second,\n@@ -3407,8 +3456,11 @@ func TestRouterSolicitation(t *testing.T) {\nt.Run(test.name, func(t *testing.T) {\nt.Parallel()\n- e := channel.New(int(test.maxRtrSolicit), 1280, linkAddr1)\n- e.LinkEPCapabilities |= stack.CapabilityResolutionRequired\n+ e := channelLinkWithHeaderLength{\n+ Endpoint: channel.New(int(test.maxRtrSolicit), 1280, linkAddr1),\n+ headerLength: test.linkHeaderLen,\n+ }\n+ e.Endpoint.LinkEPCapabilities |= stack.CapabilityResolutionRequired\nwaitForPkt := func(timeout time.Duration) {\nt.Helper()\nctx, _ := context.WithTimeout(context.Background(), timeout)\n@@ -3434,6 +3486,10 @@ func TestRouterSolicitation(t *testing.T) {\nchecker.TTL(header.NDPHopLimit),\nchecker.NDPRS(),\n)\n+\n+ if l, want := p.Pkt.Header.AvailableLength(), int(test.linkHeaderLen); l != want {\n+ t.Errorf(\"got p.Pkt.Header.AvailableLength() = %d; want = %d\", l, want)\n+ }\n}\nwaitForNothing := func(timeout time.Duration) {\nt.Helper()\n@@ -3450,8 +3506,8 @@ func TestRouterSolicitation(t *testing.T) {\nMaxRtrSolicitationDelay: test.maxRtrSolicitDelay,\n},\n})\n- if err := s.CreateNIC(1, e); err != nil {\n- t.Fatalf(\"CreateNIC(1) = %s\", err)\n+ if err := s.CreateNIC(nicID, &e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n}\n// Make sure each RS got sent at the right\n" } ]
Go
Apache License 2.0
google/gvisor
Use Route.MaxHeaderLength when constructing NDP RS Test: stack_test.TestRouterSolicitation PiperOrigin-RevId: 296454766
260,004
21.02.2020 11:20:15
28,800
a155a23480abfafe096ff50f2c4aaf2c215b6c44
Attach LinkEndpoint to NetworkDispatcher immediately Tests: stack_test.TestAttachToLinkEndpointImmediately
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -45,7 +45,6 @@ type NIC struct {\ncontext NICContext\nstats NICStats\n- attach sync.Once\nmu struct {\nsync.RWMutex\n@@ -141,6 +140,8 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\nnic.mu.packetEPs[netProto.Number()] = []PacketEndpoint{}\n}\n+ nic.linkEP.Attach(nic)\n+\nreturn nic\n}\n@@ -200,14 +201,16 @@ func (n *NIC) disable() *tcpip.Error {\n}\n}\n- // TODO(b/147015577): Should n detach from its LinkEndpoint?\n-\nn.mu.enabled = false\nreturn nil\n}\n-// enable enables n. enable will attach the nic to its LinkEndpoint and\n-// join the IPv6 All-Nodes Multicast address (ff02::1).\n+// enable enables n.\n+//\n+// If the stack has IPv6 enabled, enable will join the IPv6 All-Nodes Multicast\n+// address (ff02::1), start DAD for permanent addresses, and start soliciting\n+// routers if the stack is not operating as a router. If the stack is also\n+// configured to auto-generate a link-local address, one will be generated.\nfunc (n *NIC) enable() *tcpip.Error {\nn.mu.RLock()\nenabled := n.mu.enabled\n@@ -225,8 +228,6 @@ func (n *NIC) enable() *tcpip.Error {\nn.mu.enabled = true\n- n.attachLinkEndpoint()\n-\n// Create an endpoint to receive broadcast packets on this interface.\nif _, ok := n.stack.networkProtocols[header.IPv4ProtocolNumber]; ok {\nif _, err := n.addAddressLocked(ipv4BroadcastAddr, NeverPrimaryEndpoint, permanent, static, false /* deprecated */); err != nil {\n@@ -321,14 +322,6 @@ func (n *NIC) becomeIPv6Host() {\nn.mu.ndp.startSolicitingRouters()\n}\n-// attachLinkEndpoint attaches the NIC to the endpoint, which will enable it\n-// to start delivering packets.\n-func (n *NIC) attachLinkEndpoint() {\n- n.attach.Do(func() {\n- n.linkEP.Attach(n)\n- })\n-}\n-\n// setPromiscuousMode enables or disables promiscuous mode.\nfunc (n *NIC) setPromiscuousMode(enable bool) {\nn.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -881,6 +881,8 @@ type NICOptions struct {\n// CreateNICWithOptions creates a NIC with the provided id, LinkEndpoint, and\n// NICOptions. See the documentation on type NICOptions for details on how\n// NICs can be configured.\n+//\n+// LinkEndpoint.Attach will be called to bind ep with a NetworkDispatcher.\nfunc (s *Stack) CreateNICWithOptions(id tcpip.NICID, ep LinkEndpoint, opts NICOptions) *tcpip.Error {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -900,7 +902,6 @@ func (s *Stack) CreateNICWithOptions(id tcpip.NICID, ep LinkEndpoint, opts NICOp\n}\nn := newNIC(s, id, opts.Name, ep, opts.Context)\n-\ns.nics[id] = n\nif !opts.Disabled {\nreturn n.enable()\n@@ -910,7 +911,7 @@ func (s *Stack) CreateNICWithOptions(id tcpip.NICID, ep LinkEndpoint, opts NICOp\n}\n// CreateNIC creates a NIC with the provided id and LinkEndpoint and calls\n-// `LinkEndpoint.Attach` to start delivering packets to it.\n+// LinkEndpoint.Attach to bind ep with a NetworkDispatcher.\nfunc (s *Stack) CreateNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error {\nreturn s.CreateNICWithOptions(id, ep, NICOptions{})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -239,6 +239,23 @@ func fakeNetFactory() stack.NetworkProtocol {\nreturn &fakeNetworkProtocol{}\n}\n+// linkEPWithMockedAttach is a stack.LinkEndpoint that tests can use to verify\n+// that LinkEndpoint.Attach was called.\n+type linkEPWithMockedAttach struct {\n+ stack.LinkEndpoint\n+ attached bool\n+}\n+\n+// Attach implements stack.LinkEndpoint.Attach.\n+func (l *linkEPWithMockedAttach) Attach(d stack.NetworkDispatcher) {\n+ l.LinkEndpoint.Attach(d)\n+ l.attached = true\n+}\n+\n+func (l *linkEPWithMockedAttach) isAttached() bool {\n+ return l.attached\n+}\n+\nfunc TestNetworkReceive(t *testing.T) {\n// Create a stack with the fake network protocol, one nic, and two\n// addresses attached to it: 1 & 2.\n@@ -510,6 +527,45 @@ func testNoRoute(t *testing.T, s *stack.Stack, nic tcpip.NICID, srcAddr, dstAddr\n}\n}\n+// TestAttachToLinkEndpointImmediately tests that a LinkEndpoint is attached to\n+// a NetworkDispatcher when the NIC is created.\n+func TestAttachToLinkEndpointImmediately(t *testing.T) {\n+ const nicID = 1\n+\n+ tests := []struct {\n+ name string\n+ nicOpts stack.NICOptions\n+ }{\n+ {\n+ name: \"Create enabled NIC\",\n+ nicOpts: stack.NICOptions{Disabled: false},\n+ },\n+ {\n+ name: \"Create disabled NIC\",\n+ nicOpts: stack.NICOptions{Disabled: true},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n+ })\n+\n+ e := linkEPWithMockedAttach{\n+ LinkEndpoint: loopback.New(),\n+ }\n+\n+ if err := s.CreateNICWithOptions(nicID, &e, test.nicOpts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(%d, _, %+v) = %s\", nicID, test.nicOpts, err)\n+ }\n+ if !e.isAttached() {\n+ t.Fatalf(\"link endpoint not attached to a network disatcher\")\n+ }\n+ })\n+ }\n+}\n+\nfunc TestDisableUnknownNIC(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{fakeNetFactory()},\n" } ]
Go
Apache License 2.0
google/gvisor
Attach LinkEndpoint to NetworkDispatcher immediately Tests: stack_test.TestAttachToLinkEndpointImmediately PiperOrigin-RevId: 296474068
259,975
21.02.2020 13:17:44
28,800
3733499952c056cc8496beb01c72dcf53177048e
Fix master installer. Sometimes, when we start a new instance, the file lock on "apt" is locked. Add a loop to the master installer. In addition, the "apt-get install" fails to register runsc in docker, so run the appropriate scripts to get that to happen. Also, add some helpful log messages.
[ { "change_type": "MODIFY", "old_path": "benchmarks/harness/machine.py", "new_path": "benchmarks/harness/machine.py", "diff": "@@ -43,6 +43,8 @@ from benchmarks.harness import machine_mocks\nfrom benchmarks.harness import ssh_connection\nfrom benchmarks.harness import tunnel_dispatcher\n+log = logging.getLogger(__name__)\n+\nclass Machine(object):\n\"\"\"The machine object is the primary object for benchmarks.\n@@ -239,6 +241,7 @@ class RemoteMachine(Machine):\n# Execute the remote installer.\nself.run(\"sudo {dir}/{file}\".format(\ndir=harness.REMOTE_INSTALLERS_PATH, file=installer))\n+\nif results:\nresults[index] = True\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/harness/ssh_connection.py", "new_path": "benchmarks/harness/ssh_connection.py", "diff": "# limitations under the License.\n\"\"\"SSHConnection handles the details of SSH connections.\"\"\"\n-\n+import logging\nimport os\nimport warnings\n@@ -24,6 +24,8 @@ from benchmarks import harness\n# Get rid of paramiko Cryptography Warnings.\nwarnings.filterwarnings(action=\"ignore\", module=\".*paramiko.*\")\n+log = logging.getLogger(__name__)\n+\ndef send_one_file(client: paramiko.SSHClient, path: str,\nremote_dir: str) -> str:\n@@ -94,10 +96,13 @@ class SSHConnection:\nThe contents of stdout and stderr.\n\"\"\"\nwith self._client() as client:\n+ log.info(\"running command: %s\", cmd)\n_, stdout, stderr = client.exec_command(command=cmd)\n- stdout.channel.recv_exit_status()\n+ log.info(\"returned status: %d\", stdout.channel.recv_exit_status())\nstdout = stdout.read().decode(\"utf-8\")\nstderr = stderr.read().decode(\"utf-8\")\n+ log.info(\"stdout: %s\", stdout)\n+ log.info(\"stderr: %s\", stderr)\nreturn stdout, stderr\ndef send_workload(self, name: str) -> str:\n" }, { "change_type": "MODIFY", "old_path": "tools/installers/master.sh", "new_path": "tools/installers/master.sh", "diff": "# limitations under the License.\n# Install runsc from the master branch.\n+set -e\n+\ncurl -fsSL https://gvisor.dev/archive.key | sudo apt-key add -\nadd-apt-repository \"deb https://storage.googleapis.com/gvisor/releases release main\"\n-apt-get update && apt-get install -y runsc\n+while true; do\n+ if apt-get update; then\n+ apt-get install -y runsc\n+ break\n+ fi\n+ result=$?\n+ # Check if apt update failed to aquire the file lock.\n+ if [[ $result -ne 100 ]]; then\n+ exit $result\n+ fi\n+done\n+runsc install\n+service docker restart\n+\n" } ]
Go
Apache License 2.0
google/gvisor
Fix master installer. Sometimes, when we start a new instance, the file lock on "apt" is locked. Add a loop to the master installer. In addition, the "apt-get install" fails to register runsc in docker, so run the appropriate scripts to get that to happen. Also, add some helpful log messages. PiperOrigin-RevId: 296497357
259,858
21.02.2020 15:05:20
28,800
10aa4d3b343255db45f5ca4ff7b51f21a309e10b
Factor platform tags.
[ { "change_type": "MODIFY", "old_path": "test/runner/defs.bzl", "new_path": "test/runner/defs.bzl", "diff": "\"\"\"Defines a rule for syscall test targets.\"\"\"\n-load(\"//tools:defs.bzl\", \"loopback\")\n+load(\"//tools:defs.bzl\", \"default_platform\", \"loopback\", \"platforms\")\ndef _runner_test_impl(ctx):\n# Generate a runner binary.\n@@ -94,19 +94,6 @@ def _syscall_test(\n# Disable off-host networking.\ntags.append(\"requires-net:loopback\")\n- # Add tag to prevent the tests from running in a Bazel sandbox.\n- # TODO(b/120560048): Make the tests run without this tag.\n- tags.append(\"no-sandbox\")\n-\n- # TODO(b/112165693): KVM tests are tagged \"manual\" to until the platform is\n- # more stable.\n- if platform == \"kvm\":\n- tags.append(\"manual\")\n- tags.append(\"requires-kvm\")\n-\n- # TODO(b/112165693): Remove when tests pass reliably.\n- tags.append(\"notap\")\n-\nrunner_args = [\n# Arguments are passed directly to runner binary.\n\"--platform=\" + platform,\n@@ -149,6 +136,8 @@ def syscall_test(\nadd_hostinet: add a hostinet test.\ntags: starting test tags.\n\"\"\"\n+ if not tags:\n+ tags = []\n_syscall_test(\ntest = test,\n@@ -160,24 +149,15 @@ def syscall_test(\ntags = tags,\n)\n+ for (platform, platform_tags) in platforms.items():\n_syscall_test(\ntest = test,\nshard_count = shard_count,\nsize = size,\n- platform = \"kvm\",\n+ platform = platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = tags,\n- )\n-\n- _syscall_test(\n- test = test,\n- shard_count = shard_count,\n- size = size,\n- platform = \"ptrace\",\n- use_tmpfs = use_tmpfs,\n- add_uds_tree = add_uds_tree,\n- tags = tags,\n+ tags = platform_tags + tags,\n)\nif add_overlay:\n@@ -185,10 +165,10 @@ def syscall_test(\ntest = test,\nshard_count = shard_count,\nsize = size,\n- platform = \"ptrace\",\n+ platform = default_platform,\nuse_tmpfs = False, # overlay is adding a writable tmpfs on top of root.\nadd_uds_tree = add_uds_tree,\n- tags = tags,\n+ tags = platforms[default_platform] + tags,\noverlay = True,\n)\n@@ -198,10 +178,10 @@ def syscall_test(\ntest = test,\nshard_count = shard_count,\nsize = size,\n- platform = \"ptrace\",\n+ platform = default_platform,\nuse_tmpfs = use_tmpfs,\nadd_uds_tree = add_uds_tree,\n- tags = tags,\n+ tags = platforms[default_platform] + tags,\nfile_access = \"shared\",\n)\n@@ -210,9 +190,9 @@ def syscall_test(\ntest = test,\nshard_count = shard_count,\nsize = size,\n- platform = \"ptrace\",\n+ platform = default_platform,\nuse_tmpfs = use_tmpfs,\nnetwork = \"host\",\nadd_uds_tree = add_uds_tree,\n- tags = tags,\n+ tags = platforms[default_platform] + tags,\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/bazeldefs/platforms.bzl", "diff": "+\"\"\"List of platforms.\"\"\"\n+\n+# Platform to associated tags.\n+platforms = {\n+ \"ptrace\": [\n+ # TODO(b/120560048): Make the tests run without this tag.\n+ \"no-sandbox\",\n+ ],\n+ \"kvm\": [\n+ \"manual\",\n+ \"local\",\n+ # TODO(b/120560048): Make the tests run without this tag.\n+ \"no-sandbox\",\n+ ],\n+}\n+\n+default_platform = \"ptrace\"\n" }, { "change_type": "MODIFY", "old_path": "tools/defs.bzl", "new_path": "tools/defs.bzl", "diff": "@@ -8,6 +8,7 @@ change for Google-internal and bazel-compatible rules.\nload(\"//tools/go_stateify:defs.bzl\", \"go_stateify\")\nload(\"//tools/go_marshal:defs.bzl\", \"go_marshal\", \"marshal_deps\", \"marshal_test_deps\")\nload(\"//tools/bazeldefs:defs.bzl\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _container_image = \"container_image\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _gbenchmark = \"gbenchmark\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_image = \"go_image\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _go_tool_library = \"go_tool_library\", _gtest = \"gtest\", _loopback = \"loopback\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\", _proto_library = \"proto_library\", _py_binary = \"py_binary\", _py_library = \"py_library\", _py_requirement = \"py_requirement\", _py_test = \"py_test\", _select_arch = \"select_arch\", _select_system = \"select_system\")\n+load(\"//tools/bazeldefs:platforms.bzl\", _default_platform = \"default_platform\", _platforms = \"platforms\")\nload(\"//tools/bazeldefs:tags.bzl\", \"go_suffixes\")\n# Delegate directly.\n@@ -34,6 +35,8 @@ select_system = _select_system\nloopback = _loopback\ndefault_installer = _default_installer\ndefault_net_util = _default_net_util\n+platforms = _platforms\n+default_platform = _default_platform\ndef go_binary(name, **kwargs):\n\"\"\"Wraps the standard go_binary.\n" } ]
Go
Apache License 2.0
google/gvisor
Factor platform tags. PiperOrigin-RevId: 296519566
259,858
24.02.2020 17:28:27
28,800
160d5751ab6a06c22aed7d829a17c88344cc7cf2
Add default behavior for gtest runner.
[ { "change_type": "MODIFY", "old_path": "test/perf/BUILD", "new_path": "test/perf/BUILD", "diff": "@@ -29,7 +29,7 @@ syscall_test(\n)\nsyscall_test(\n- size = \"large\",\n+ size = \"enormous\",\ntest = \"//test/perf/linux:getdents_benchmark\",\n)\n@@ -39,7 +39,7 @@ syscall_test(\n)\nsyscall_test(\n- size = \"large\",\n+ size = \"enormous\",\ntest = \"//test/perf/linux:gettid_benchmark\",\n)\n@@ -87,7 +87,7 @@ syscall_test(\n)\nsyscall_test(\n- size = \"large\",\n+ size = \"enormous\",\ntest = \"//test/perf/linux:signal_benchmark\",\n)\n@@ -102,7 +102,7 @@ syscall_test(\n)\nsyscall_test(\n- size = \"large\",\n+ size = \"enormous\",\nadd_overlay = True,\ntest = \"//test/perf/linux:unlink_benchmark\",\n)\n" }, { "change_type": "MODIFY", "old_path": "test/perf/linux/getdents_benchmark.cc", "new_path": "test/perf/linux/getdents_benchmark.cc", "diff": "@@ -141,7 +141,7 @@ void BM_GetdentsNewFD(benchmark::State& state) {\nstate.SetItemsProcessed(state.iterations());\n}\n-BENCHMARK(BM_GetdentsNewFD)->Range(1, 1 << 16)->UseRealTime();\n+BENCHMARK(BM_GetdentsNewFD)->Range(1, 1 << 12)->UseRealTime();\n} // namespace\n" }, { "change_type": "MODIFY", "old_path": "test/runner/gtest/gtest.go", "new_path": "test/runner/gtest/gtest.go", "diff": "@@ -43,6 +43,10 @@ type TestCase struct {\n// Name is the name of this individual test.\nName string\n+ // all indicates that this will run without flags. This takes\n+ // precendence over benchmark below.\n+ all bool\n+\n// benchmark indicates that this is a benchmark. In this case, the\n// suite will be empty, and we will use the appropriate test and\n// benchmark flags.\n@@ -57,6 +61,9 @@ func (tc TestCase) FullName() string {\n// Args returns arguments to be passed when invoking the test.\nfunc (tc TestCase) Args() []string {\n+ if tc.all {\n+ return []string{} // No arguments.\n+ }\nif tc.benchmark {\nreturn []string{\nfmt.Sprintf(\"%s=^$\", filterTestFlag),\n@@ -81,11 +88,16 @@ func ParseTestCases(testBin string, benchmarks bool, extraArgs ...string) ([]Tes\ncmd := exec.Command(testBin, args...)\nout, err := cmd.Output()\nif err != nil {\n- exitErr, ok := err.(*exec.ExitError)\n- if !ok {\n- return nil, fmt.Errorf(\"could not enumerate gtest tests: %v\", err)\n- }\n- return nil, fmt.Errorf(\"could not enumerate gtest tests: %v\\nstderr:\\n%s\", err, exitErr.Stderr)\n+ // We failed to list tests with the given flags. Just\n+ // return something that will run the binary with no\n+ // flags, which should execute all tests.\n+ return []TestCase{\n+ TestCase{\n+ Suite: \"Default\",\n+ Name: \"All\",\n+ all: true,\n+ },\n+ }, nil\n}\n// Parse test output.\n@@ -114,7 +126,6 @@ func ParseTestCases(testBin string, benchmarks bool, extraArgs ...string) ([]Tes\nSuite: suite,\nName: name,\n})\n-\n}\n// Finished?\n@@ -127,6 +138,8 @@ func ParseTestCases(testBin string, benchmarks bool, extraArgs ...string) ([]Tes\ncmd = exec.Command(testBin, args...)\nout, err = cmd.Output()\nif err != nil {\n+ // We were able to enumerate tests above, but not benchmarks?\n+ // We requested them, so we return an error in this case.\nexitErr, ok := err.(*exec.ExitError)\nif !ok {\nreturn nil, fmt.Errorf(\"could not enumerate gtest benchmarks: %v\", err)\n" } ]
Go
Apache License 2.0
google/gvisor
Add default behavior for gtest runner. PiperOrigin-RevId: 297009116
259,974
21.02.2020 10:28:16
0
93e0c3752981b6a1c5b745faec6506c17480b84b
Enable bluepill dieTrampoline operation on arm64.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "new_path": "pkg/sentry/platform/kvm/bluepill_arm64_unsafe.go", "diff": "@@ -18,9 +18,30 @@ package kvm\nimport (\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/platform/ring0\"\n)\n+// dieArchSetup initialies the state for dieTrampoline.\n+//\n+// The arm64 dieTrampoline requires the vCPU to be set in R1, and the last PC\n+// to be in R0. The trampoline then simulates a call to dieHandler from the\n+// provided PC.\n+//\n//go:nosplit\nfunc dieArchSetup(c *vCPU, context *arch.SignalContext64, guestRegs *userRegs) {\n- // TODO(gvisor.dev/issue/1249): dieTrampoline supporting for Arm64.\n+ // If the vCPU is in user mode, we set the stack to the stored stack\n+ // value in the vCPU itself. We don't want to unwind the user stack.\n+ if guestRegs.Regs.Pstate&ring0.PSR_MODE_MASK == ring0.PSR_MODE_EL0t {\n+ regs := c.CPU.Registers()\n+ context.Regs[0] = regs.Regs[0]\n+ context.Sp = regs.Sp\n+ context.Regs[29] = regs.Regs[29] // stack base address\n+ } else {\n+ context.Regs[0] = guestRegs.Regs.Pc\n+ context.Sp = guestRegs.Regs.Sp\n+ context.Regs[29] = guestRegs.Regs.Regs[29]\n+ context.Pstate = guestRegs.Regs.Pstate\n+ }\n+ context.Regs[1] = uint64(uintptr(unsafe.Pointer(c)))\n+ context.Pc = uint64(dieTrampolineAddr)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/ring0/aarch64.go", "new_path": "pkg/sentry/platform/ring0/aarch64.go", "diff": "@@ -27,26 +27,27 @@ const (\n_PTE_PGT_BASE = 0x7000\n_PTE_PGT_SIZE = 0x1000\n- _PSR_MODE_EL0t = 0x0\n- _PSR_MODE_EL1t = 0x4\n- _PSR_MODE_EL1h = 0x5\n- _PSR_EL_MASK = 0xf\n-\n- _PSR_D_BIT = 0x200\n- _PSR_A_BIT = 0x100\n- _PSR_I_BIT = 0x80\n- _PSR_F_BIT = 0x40\n+ _PSR_D_BIT = 0x00000200\n+ _PSR_A_BIT = 0x00000100\n+ _PSR_I_BIT = 0x00000080\n+ _PSR_F_BIT = 0x00000040\n)\nconst (\n+ // PSR bits\n+ PSR_MODE_EL0t = 0x00000000\n+ PSR_MODE_EL1t = 0x00000004\n+ PSR_MODE_EL1h = 0x00000005\n+ PSR_MODE_MASK = 0x0000000f\n+\n// KernelFlagsSet should always be set in the kernel.\n- KernelFlagsSet = _PSR_MODE_EL1h\n+ KernelFlagsSet = PSR_MODE_EL1h\n// UserFlagsSet are always set in userspace.\n- UserFlagsSet = _PSR_MODE_EL0t\n+ UserFlagsSet = PSR_MODE_EL0t\n- KernelFlagsClear = _PSR_EL_MASK\n- UserFlagsClear = _PSR_EL_MASK\n+ KernelFlagsClear = PSR_MODE_MASK\n+ UserFlagsClear = PSR_MODE_MASK\nPsrDefaultSet = _PSR_D_BIT | _PSR_A_BIT | _PSR_I_BIT | _PSR_F_BIT\n)\n" } ]
Go
Apache License 2.0
google/gvisor
Enable bluepill dieTrampoline operation on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I9e1bf2513c23bdd8c387e5b3c874c6ad3ca9aab0
259,992
25.02.2020 11:13:29
28,800
4d7db46123f020df77cea5c00df4114b7b073845
Add log during process wait in tests TestMultiContainerKillAll timed out under --race. Without logging, we cannot tell if the process list is still increasing, but slowly, or is stuck.
[ { "change_type": "MODIFY", "old_path": "runsc/container/container_test.go", "new_path": "runsc/container/container_test.go", "diff": "@@ -71,6 +71,7 @@ func waitForProcessCount(cont *Container, want int) error {\nreturn &backoff.PermanentError{Err: err}\n}\nif got := len(pss); got != want {\n+ log.Infof(\"Waiting for process count to reach %d. Current: %d\", want, got)\nreturn fmt.Errorf(\"wrong process count, got: %d, want: %d\", got, want)\n}\nreturn nil\n" } ]
Go
Apache License 2.0
google/gvisor
Add log during process wait in tests TestMultiContainerKillAll timed out under --race. Without logging, we cannot tell if the process list is still increasing, but slowly, or is stuck. PiperOrigin-RevId: 297158834
259,858
25.02.2020 12:21:27
28,800
98b693e61b37a62f7b29ce1cab8b4c4c54fa044e
Don't acquire contended lock with the OS thread locked. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine.go", "new_path": "pkg/sentry/platform/kvm/machine.go", "diff": "@@ -329,10 +329,12 @@ func (m *machine) Destroy() {\n}\n// Get gets an available vCPU.\n+//\n+// This will return with the OS thread locked.\nfunc (m *machine) Get() *vCPU {\n+ m.mu.RLock()\nruntime.LockOSThread()\ntid := procid.Current()\n- m.mu.RLock()\n// Check for an exact match.\nif c := m.vCPUs[tid]; c != nil {\n@@ -343,8 +345,22 @@ func (m *machine) Get() *vCPU {\n// The happy path failed. We now proceed to acquire an exclusive lock\n// (because the vCPU map may change), and scan all available vCPUs.\n+ // In this case, we first unlock the OS thread. Otherwise, if mu is\n+ // not available, the current system thread will be parked and a new\n+ // system thread spawned. We avoid this situation by simply refreshing\n+ // tid after relocking the system thread.\nm.mu.RUnlock()\n+ runtime.UnlockOSThread()\nm.mu.Lock()\n+ runtime.LockOSThread()\n+ tid = procid.Current()\n+\n+ // Recheck for an exact match.\n+ if c := m.vCPUs[tid]; c != nil {\n+ c.lock()\n+ m.mu.Unlock()\n+ return c\n+ }\nfor {\n// Scan for an available vCPU.\n" } ]
Go
Apache License 2.0
google/gvisor
Don't acquire contended lock with the OS thread locked. Fixes #1049 PiperOrigin-RevId: 297175164
259,858
25.02.2020 12:22:09
28,800
6def8ea6ac601daa9256a31f818db9f7eb532168
Fix nested logging.
[ { "change_type": "MODIFY", "old_path": "pkg/log/glog.go", "new_path": "pkg/log/glog.go", "diff": "@@ -46,7 +46,7 @@ var pid = os.Getpid()\n// line The line number\n// msg The user-supplied message\n//\n-func (g *GoogleEmitter) Emit(level Level, timestamp time.Time, format string, args ...interface{}) {\n+func (g *GoogleEmitter) Emit(depth int, level Level, timestamp time.Time, format string, args ...interface{}) {\n// Log level.\nprefix := byte('?')\nswitch level {\n@@ -64,9 +64,7 @@ func (g *GoogleEmitter) Emit(level Level, timestamp time.Time, format string, ar\nmicrosecond := int(timestamp.Nanosecond() / 1000)\n// 0 = this frame.\n- // 1 = Debugf, etc.\n- // 2 = Caller.\n- _, file, line, ok := runtime.Caller(2)\n+ _, file, line, ok := runtime.Caller(depth + 1)\nif ok {\n// Trim any directory path from the file.\nslash := strings.LastIndexByte(file, byte('/'))\n" }, { "change_type": "MODIFY", "old_path": "pkg/log/json.go", "new_path": "pkg/log/json.go", "diff": "@@ -62,7 +62,7 @@ type JSONEmitter struct {\n}\n// Emit implements Emitter.Emit.\n-func (e JSONEmitter) Emit(level Level, timestamp time.Time, format string, v ...interface{}) {\n+func (e JSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...interface{}) {\nj := jsonLog{\nMsg: fmt.Sprintf(format, v...),\nLevel: level,\n" }, { "change_type": "MODIFY", "old_path": "pkg/log/json_k8s.go", "new_path": "pkg/log/json_k8s.go", "diff": "@@ -33,7 +33,7 @@ type K8sJSONEmitter struct {\n}\n// Emit implements Emitter.Emit.\n-func (e *K8sJSONEmitter) Emit(level Level, timestamp time.Time, format string, v ...interface{}) {\n+func (e *K8sJSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...interface{}) {\nj := k8sJSONLog{\nLog: fmt.Sprintf(format, v...),\nLevel: level,\n" }, { "change_type": "MODIFY", "old_path": "pkg/log/log.go", "new_path": "pkg/log/log.go", "diff": "@@ -79,7 +79,7 @@ func (l Level) String() string {\ntype Emitter interface {\n// Emit emits the given log statement. This allows for control over the\n// timestamp used for logging.\n- Emit(level Level, timestamp time.Time, format string, v ...interface{})\n+ Emit(depth int, level Level, timestamp time.Time, format string, v ...interface{})\n}\n// Writer writes the output to the given writer.\n@@ -142,7 +142,7 @@ func (l *Writer) Write(data []byte) (int, error) {\n}\n// Emit emits the message.\n-func (l *Writer) Emit(level Level, timestamp time.Time, format string, args ...interface{}) {\n+func (l *Writer) Emit(_ int, _ Level, _ time.Time, format string, args ...interface{}) {\nfmt.Fprintf(l, format, args...)\n}\n@@ -150,9 +150,9 @@ func (l *Writer) Emit(level Level, timestamp time.Time, format string, args ...i\ntype MultiEmitter []Emitter\n// Emit emits to all emitters.\n-func (m *MultiEmitter) Emit(level Level, timestamp time.Time, format string, v ...interface{}) {\n+func (m *MultiEmitter) Emit(depth int, level Level, timestamp time.Time, format string, v ...interface{}) {\nfor _, e := range *m {\n- e.Emit(level, timestamp, format, v...)\n+ e.Emit(1+depth, level, timestamp, format, v...)\n}\n}\n@@ -167,7 +167,7 @@ type TestEmitter struct {\n}\n// Emit emits to the TestLogger.\n-func (t *TestEmitter) Emit(level Level, timestamp time.Time, format string, v ...interface{}) {\n+func (t *TestEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...interface{}) {\nt.Logf(format, v...)\n}\n@@ -198,22 +198,37 @@ type BasicLogger struct {\n// Debugf implements logger.Debugf.\nfunc (l *BasicLogger) Debugf(format string, v ...interface{}) {\n- if l.IsLogging(Debug) {\n- l.Emit(Debug, time.Now(), format, v...)\n- }\n+ l.DebugfAtDepth(1, format, v...)\n}\n// Infof implements logger.Infof.\nfunc (l *BasicLogger) Infof(format string, v ...interface{}) {\n- if l.IsLogging(Info) {\n- l.Emit(Info, time.Now(), format, v...)\n- }\n+ l.InfofAtDepth(1, format, v...)\n}\n// Warningf implements logger.Warningf.\nfunc (l *BasicLogger) Warningf(format string, v ...interface{}) {\n+ l.WarningfAtDepth(1, format, v...)\n+}\n+\n+// DebugfAtDepth logs at a specific depth.\n+func (l *BasicLogger) DebugfAtDepth(depth int, format string, v ...interface{}) {\n+ if l.IsLogging(Debug) {\n+ l.Emit(1+depth, Debug, time.Now(), format, v...)\n+ }\n+}\n+\n+// InfofAtDepth logs at a specific depth.\n+func (l *BasicLogger) InfofAtDepth(depth int, format string, v ...interface{}) {\n+ if l.IsLogging(Info) {\n+ l.Emit(1+depth, Info, time.Now(), format, v...)\n+ }\n+}\n+\n+// WarningfAtDepth logs at a specific depth.\n+func (l *BasicLogger) WarningfAtDepth(depth int, format string, v ...interface{}) {\nif l.IsLogging(Warning) {\n- l.Emit(Warning, time.Now(), format, v...)\n+ l.Emit(1+depth, Warning, time.Now(), format, v...)\n}\n}\n@@ -257,17 +272,32 @@ func SetLevel(newLevel Level) {\n// Debugf logs to the global logger.\nfunc Debugf(format string, v ...interface{}) {\n- Log().Debugf(format, v...)\n+ Log().DebugfAtDepth(1, format, v...)\n}\n// Infof logs to the global logger.\nfunc Infof(format string, v ...interface{}) {\n- Log().Infof(format, v...)\n+ Log().InfofAtDepth(1, format, v...)\n}\n// Warningf logs to the global logger.\nfunc Warningf(format string, v ...interface{}) {\n- Log().Warningf(format, v...)\n+ Log().WarningfAtDepth(1, format, v...)\n+}\n+\n+// DebugfAtDepth logs to the global logger.\n+func DebugfAtDepth(depth int, format string, v ...interface{}) {\n+ Log().DebugfAtDepth(1+depth, format, v...)\n+}\n+\n+// InfofAtDepth logs to the global logger.\n+func InfofAtDepth(depth int, format string, v ...interface{}) {\n+ Log().InfofAtDepth(1+depth, format, v...)\n+}\n+\n+// WarningfAtDepth logs to the global logger.\n+func WarningfAtDepth(depth int, format string, v ...interface{}) {\n+ Log().WarningfAtDepth(1+depth, format, v...)\n}\n// defaultStackSize is the default buffer size to allocate for stack traces.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_log.go", "new_path": "pkg/sentry/kernel/task_log.go", "diff": "@@ -32,21 +32,21 @@ const (\n// Infof logs an formatted info message by calling log.Infof.\nfunc (t *Task) Infof(fmt string, v ...interface{}) {\nif log.IsLogging(log.Info) {\n- log.Infof(t.logPrefix.Load().(string)+fmt, v...)\n+ log.InfofAtDepth(1, t.logPrefix.Load().(string)+fmt, v...)\n}\n}\n// Warningf logs a warning string by calling log.Warningf.\nfunc (t *Task) Warningf(fmt string, v ...interface{}) {\nif log.IsLogging(log.Warning) {\n- log.Warningf(t.logPrefix.Load().(string)+fmt, v...)\n+ log.WarningfAtDepth(1, t.logPrefix.Load().(string)+fmt, v...)\n}\n}\n// Debugf creates a debug string that includes the task ID.\nfunc (t *Task) Debugf(fmt string, v ...interface{}) {\nif log.IsLogging(log.Debug) {\n- log.Debugf(t.logPrefix.Load().(string)+fmt, v...)\n+ log.DebugfAtDepth(1, t.logPrefix.Load().(string)+fmt, v...)\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix nested logging. PiperOrigin-RevId: 297175316
259,992
25.02.2020 13:42:34
28,800
72e3f3a3eef3a1dc02db0ff71f98a5d7fe89a6e3
Add option to skip stuck tasks waiting for address space
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/kernel.go", "new_path": "pkg/sentry/kernel/kernel.go", "diff": "@@ -247,6 +247,10 @@ type Kernel struct {\n// VFS keeps the filesystem state used across the kernel.\nvfs vfs.VirtualFilesystem\n+\n+ // If set to true, report address space activation waits as if the task is in\n+ // external wait so that the watchdog doesn't report the task stuck.\n+ SleepForAddressSpaceActivation bool\n}\n// InitKernelArgs holds arguments to Init.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_context.go", "new_path": "pkg/sentry/kernel/task_context.go", "diff": "@@ -140,7 +140,7 @@ func (k *Kernel) LoadTaskImage(ctx context.Context, args loader.LoadArgs) (*Task\n}\n// Prepare a new user address space to load into.\n- m := mm.NewMemoryManager(k, k)\n+ m := mm.NewMemoryManager(k, k, k.SleepForAddressSpaceActivation)\ndefer m.DecUsers(ctx)\nargs.MemoryManager = m\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_exec.go", "new_path": "pkg/sentry/kernel/task_exec.go", "diff": "@@ -220,7 +220,7 @@ func (r *runSyscallAfterExecStop) execute(t *Task) taskRunState {\nt.mu.Unlock()\nt.unstopVforkParent()\n// NOTE(b/30316266): All locks must be dropped prior to calling Activate.\n- t.MemoryManager().Activate()\n+ t.MemoryManager().Activate(t)\nt.ptraceExec(oldTID)\nreturn (*runSyscallExit)(nil)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/task_usermem.go", "new_path": "pkg/sentry/kernel/task_usermem.go", "diff": "@@ -30,7 +30,7 @@ var MAX_RW_COUNT = int(usermem.Addr(math.MaxInt32).RoundDown())\n// Activate ensures that the task has an active address space.\nfunc (t *Task) Activate() {\nif mm := t.MemoryManager(); mm != nil {\n- if err := mm.Activate(); err != nil {\n+ if err := mm.Activate(t); err != nil {\npanic(\"unable to activate mm: \" + err.Error())\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/address_space.go", "new_path": "pkg/sentry/mm/address_space.go", "diff": "@@ -18,6 +18,7 @@ import (\n\"fmt\"\n\"sync/atomic\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -38,7 +39,7 @@ func (mm *MemoryManager) AddressSpace() platform.AddressSpace {\n//\n// When this MemoryManager is no longer needed by a task, it should call\n// Deactivate to release the reference.\n-func (mm *MemoryManager) Activate() error {\n+func (mm *MemoryManager) Activate(ctx context.Context) error {\n// Fast path: the MemoryManager already has an active\n// platform.AddressSpace, and we just need to indicate that we need it too.\nfor {\n@@ -91,16 +92,20 @@ func (mm *MemoryManager) Activate() error {\nif as == nil {\n// AddressSpace is unavailable, we must wait.\n//\n- // activeMu must not be held while waiting, as the user\n- // of the address space we are waiting on may attempt\n- // to take activeMu.\n- //\n- // Don't call UninterruptibleSleepStart to register the\n- // wait to allow the watchdog stuck task to trigger in\n- // case a process is starved waiting for the address\n- // space.\n+ // activeMu must not be held while waiting, as the user of the address\n+ // space we are waiting on may attempt to take activeMu.\nmm.activeMu.Unlock()\n+\n+ sleep := mm.p.CooperativelySchedulesAddressSpace() && mm.sleepForActivation\n+ if sleep {\n+ // Mark this task sleeping while waiting for the address space to\n+ // prevent the watchdog from reporting it as a stuck task.\n+ ctx.UninterruptibleSleepStart(false)\n+ }\n<-c\n+ if sleep {\n+ ctx.UninterruptibleSleepFinish(false)\n+ }\ncontinue\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/lifecycle.go", "new_path": "pkg/sentry/mm/lifecycle.go", "diff": "@@ -28,7 +28,7 @@ import (\n)\n// NewMemoryManager returns a new MemoryManager with no mappings and 1 user.\n-func NewMemoryManager(p platform.Platform, mfp pgalloc.MemoryFileProvider) *MemoryManager {\n+func NewMemoryManager(p platform.Platform, mfp pgalloc.MemoryFileProvider, sleepForActivation bool) *MemoryManager {\nreturn &MemoryManager{\np: p,\nmfp: mfp,\n@@ -38,6 +38,7 @@ func NewMemoryManager(p platform.Platform, mfp pgalloc.MemoryFileProvider) *Memo\nauxv: arch.Auxv{},\ndumpability: UserDumpable,\naioManager: aioManager{contexts: make(map[uint64]*AIOContext)},\n+ sleepForActivation: sleepForActivation,\n}\n}\n@@ -82,6 +83,7 @@ func (mm *MemoryManager) Fork(ctx context.Context) (*MemoryManager, error) {\nexecutable: mm.executable,\ndumpability: mm.dumpability,\naioManager: aioManager{contexts: make(map[uint64]*AIOContext)},\n+ sleepForActivation: mm.sleepForActivation,\n}\n// Copy vmas.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm.go", "new_path": "pkg/sentry/mm/mm.go", "diff": "@@ -226,6 +226,11 @@ type MemoryManager struct {\n// aioManager keeps track of AIOContexts used for async IOs. AIOManager\n// must be cloned when CLONE_VM is used.\naioManager aioManager\n+\n+ // sleepForActivation indicates whether the task should report to be sleeping\n+ // before trying to activate the address space. When set to true, delays in\n+ // activation are not reported as stuck tasks by the watchdog.\n+ sleepForActivation bool\n}\n// vma represents a virtual memory area.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm_test.go", "new_path": "pkg/sentry/mm/mm_test.go", "diff": "@@ -31,7 +31,7 @@ import (\nfunc testMemoryManager(ctx context.Context) *MemoryManager {\np := platform.FromContext(ctx)\nmfp := pgalloc.MemoryFileProviderFromContext(ctx)\n- mm := NewMemoryManager(p, mfp)\n+ mm := NewMemoryManager(p, mfp, false)\nmm.layout = arch.MmapLayout{\nMinAddr: p.MinUserAddress(),\nMaxAddr: p.MaxUserAddress(),\n" } ]
Go
Apache License 2.0
google/gvisor
Add option to skip stuck tasks waiting for address space PiperOrigin-RevId: 297192390
259,896
25.02.2020 15:03:51
28,800
acc405ba60834f5dce9ce04cd762d5cda02224cb
Add nat table support for iptables. commit the changes for the comments.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -250,8 +250,24 @@ type XTErrorTarget struct {\n// SizeOfXTErrorTarget is the size of an XTErrorTarget.\nconst SizeOfXTErrorTarget = 64\n+// Flag values for NfNATIPV4Range. The values indicate whether to map\n+// protocol specific part(ports) or IPs. It corresponds to values in\n+// include/uapi/linux/netfilter/nf_nat.h.\n+const (\n+ NF_NAT_RANGE_MAP_IPS = 1 << 0\n+ NF_NAT_RANGE_PROTO_SPECIFIED = 1 << 1\n+ NF_NAT_RANGE_PROTO_RANDOM = 1 << 2\n+ NF_NAT_RANGE_PERSISTENT = 1 << 3\n+ NF_NAT_RANGE_PROTO_RANDOM_FULLY = 1 << 4\n+ NF_NAT_RANGE_PROTO_RANDOM_ALL = (NF_NAT_RANGE_PROTO_RANDOM | NF_NAT_RANGE_PROTO_RANDOM_FULLY)\n+ NF_NAT_RANGE_MASK = (NF_NAT_RANGE_MAP_IPS |\n+ NF_NAT_RANGE_PROTO_SPECIFIED | NF_NAT_RANGE_PROTO_RANDOM |\n+ NF_NAT_RANGE_PERSISTENT | NF_NAT_RANGE_PROTO_RANDOM_FULLY)\n+)\n+\n// NfNATIPV4Range. It corresponds to struct nf_nat_ipv4_range\n-// in include/uapi/linux/netfilter/nf_nat.h.\n+// in include/uapi/linux/netfilter/nf_nat.h. The fields are in\n+// network byte order.\ntype NfNATIPV4Range struct {\nFlags uint32\nMinIP [4]byte\n@@ -263,11 +279,12 @@ type NfNATIPV4Range struct {\n// NfNATIPV4MultiRangeCompat. It corresponds to struct\n// nf_nat_ipv4_multi_range_compat in include/uapi/linux/netfilter/nf_nat.h.\ntype NfNATIPV4MultiRangeCompat struct {\n- Rangesize uint32\n- RangeIPV4 [1]NfNATIPV4Range\n+ RangeSize uint32\n+ RangeIPV4 NfNATIPV4Range\n}\n// XTRedirectTarget triggers a redirect when reached.\n+// Adding 4 bytes of padding to make the struct 8 byte aligned.\ntype XTRedirectTarget struct {\nTarget XTEntryTarget\nNfRange NfNATIPV4MultiRangeCompat\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -288,6 +289,7 @@ func marshalRedirectTarget() []byte {\nTargetSize: linux.SizeOfXTRedirectTarget,\n},\n}\n+ copy(target.Target.Name[:], redirectTargetName)\nret := make([]byte, 0, linux.SizeOfXTRedirectTarget)\nreturn binary.Marshal(ret, usermem.ByteOrder, target)\n@@ -405,7 +407,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nnflog(\"entry doesn't have enough room for its target (only %d bytes remain)\", len(optVal))\nreturn syserr.ErrInvalidArgument\n}\n- target, err := parseTarget(optVal[:targetSize])\n+ target, err := parseTarget(filter, optVal[:targetSize])\nif err != nil {\nnflog(\"failed to parse target: %v\", err)\nreturn syserr.ErrInvalidArgument\n@@ -552,7 +554,7 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\n// parseTarget parses a target from optVal. optVal should contain only the\n// target.\n-func parseTarget(optVal []byte) (iptables.Target, error) {\n+func parseTarget(filter iptables.IPHeaderFilter, optVal []byte) (iptables.Target, error) {\nnflog(\"set entries: parsing target of size %d\", len(optVal))\nif len(optVal) < linux.SizeOfXTEntryTarget {\nreturn nil, fmt.Errorf(\"optVal has insufficient size for entry target %d\", len(optVal))\n@@ -604,6 +606,10 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\nreturn nil, fmt.Errorf(\"netfilter.SetEntries: optVal has insufficient size for redirect target %d\", len(optVal))\n}\n+ if filter.Protocol != header.TCPProtocolNumber && filter.Protocol != header.UDPProtocolNumber {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+\nvar redirectTarget linux.XTRedirectTarget\nbuf = optVal[:linux.SizeOfXTRedirectTarget]\nbinary.Unmarshal(buf, usermem.ByteOrder, &redirectTarget)\n@@ -612,21 +618,30 @@ func parseTarget(optVal []byte) (iptables.Target, error) {\nvar target iptables.RedirectTarget\nnfRange := redirectTarget.NfRange\n- target.RangeSize = nfRange.Rangesize\n- target.Flags = nfRange.RangeIPV4[0].Flags\n+ // RangeSize should be 1.\n+ if nfRange.RangeSize != 1 {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument\")\n+ }\n+\n+ // TODO(gvisor.dev/issue/170): Check if the flags are valid.\n+ // Also check if we need to map ports or IP.\n+ // For now, redirect target only supports dest port change.\n+ if nfRange.RangeIPV4.Flags&linux.NF_NAT_RANGE_PROTO_SPECIFIED == 0 {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument.\")\n+ }\n+ target.Flags = nfRange.RangeIPV4.Flags\n- target.MinIP = tcpip.Address(nfRange.RangeIPV4[0].MinIP[:])\n- target.MaxIP = tcpip.Address(nfRange.RangeIPV4[0].MaxIP[:])\n+ target.MinIP = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\n+ target.MaxIP = tcpip.Address(nfRange.RangeIPV4.MaxIP[:])\n// Convert port from big endian to little endian.\nport := make([]byte, 2)\n- binary.BigEndian.PutUint16(port, nfRange.RangeIPV4[0].MinPort)\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MinPort)\ntarget.MinPort = binary.LittleEndian.Uint16(port)\n- binary.BigEndian.PutUint16(port, nfRange.RangeIPV4[0].MaxPort)\n+ binary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MaxPort)\ntarget.MaxPort = binary.LittleEndian.Uint16(port)\nreturn target, nil\n-\n}\n// Unknown target.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -207,7 +207,7 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\nunderflow := table.Rules[table.Underflows[hook]]\n// Underflow is guaranteed to be an unconditional\n// ACCEPT or DROP.\n- switch v, _ := underflow.Target.Action(pkt); v {\n+ switch v, _ := underflow.Target.Action(pkt, underflow.Filter); v {\ncase RuleAccept:\nreturn TableAccept\ncase RuleDrop:\n@@ -233,6 +233,12 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\nfunc (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) RuleVerdict {\nrule := table.Rules[ruleIdx]\n+ // If pkt.NetworkHeader hasn't been set yet, it will be contained in\n+ // pkt.Data.First().\n+ if pkt.NetworkHeader == nil {\n+ pkt.NetworkHeader = pkt.Data.First()\n+ }\n+\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\nif rule.Filter.Protocol != 0 && rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\n@@ -252,6 +258,6 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\n}\n// All the matchers matched, so run the target.\n- verdict, _ := rule.Target.Action(pkt)\n+ verdict, _ := rule.Target.Action(pkt, rule.Filter)\nreturn verdict\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "@@ -26,7 +26,7 @@ import (\ntype AcceptTarget struct{}\n// Action implements Target.Action.\n-func (AcceptTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (AcceptTarget) Action(packet tcpip.PacketBuffer, filter IPHeaderFilter) (RuleVerdict, string) {\nreturn RuleAccept, \"\"\n}\n@@ -34,7 +34,7 @@ func (AcceptTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\ntype DropTarget struct{}\n// Action implements Target.Action.\n-func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (DropTarget) Action(packet tcpip.PacketBuffer, filter IPHeaderFilter) (RuleVerdict, string) {\nreturn RuleDrop, \"\"\n}\n@@ -43,7 +43,7 @@ func (DropTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\ntype ErrorTarget struct{}\n// Action implements Target.Action.\n-func (ErrorTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (ErrorTarget) Action(packet tcpip.PacketBuffer, filter IPHeaderFilter) (RuleVerdict, string) {\nlog.Debugf(\"ErrorTarget triggered.\")\nreturn RuleDrop, \"\"\n}\n@@ -54,7 +54,7 @@ type UserChainTarget struct {\n}\n// Action implements Target.Action.\n-func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (UserChainTarget) Action(tcpip.PacketBuffer, IPHeaderFilter) (RuleVerdict, string) {\npanic(\"UserChainTarget should never be called.\")\n}\n@@ -63,29 +63,55 @@ func (UserChainTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\ntype ReturnTarget struct{}\n// Action implements Target.Action.\n-func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, string) {\n+func (ReturnTarget) Action(tcpip.PacketBuffer, IPHeaderFilter) (RuleVerdict, string) {\nreturn RuleReturn, \"\"\n}\n// RedirectTarget redirects the packet by modifying the destination port/IP.\n+// Min and Max values for IP and Ports in the struct indicate the range of\n+// values which can be used to redirect.\ntype RedirectTarget struct {\n- RangeSize uint32\n+ // Flags to check if the redirect is for address or ports.\nFlags uint32\n+\n+ // Min address used to redirect.\nMinIP tcpip.Address\n+\n+ // Max address used to redirect.\nMaxIP tcpip.Address\n+\n+ // Min port used to redirect.\nMinPort uint16\n+\n+ // Max port used to redirect.\nMaxPort uint16\n}\n// Action implements Target.Action.\n-func (rt RedirectTarget) Action(packet tcpip.PacketBuffer) (RuleVerdict, string) {\n- log.Infof(\"RedirectTarget triggered.\")\n+func (rt RedirectTarget) Action(pkt tcpip.PacketBuffer, filter IPHeaderFilter) (RuleVerdict, string) {\n+ headerView := pkt.Data.First()\n- // TODO(gvisor.dev/issue/170): Checking only for UDP protocol.\n- // We're yet to support for TCP protocol.\n- headerView := packet.Data.First()\n- h := header.UDP(headerView)\n- h.SetDestinationPort(rt.MinPort)\n+ // Network header should be set.\n+ netHeader := header.IPv4(headerView)\n+ if netHeader == nil {\n+ return RuleDrop, \"\"\n+ }\n+ // TODO(gvisor.dev/issue/170): Check Flags in RedirectTarget if\n+ // we need to change dest address (for OUTPUT chain) or ports.\n+ hlen := int(netHeader.HeaderLength())\n+\n+ switch protocol := filter.Protocol; protocol {\n+ case header.UDPProtocolNumber:\n+ udp := header.UDP(headerView[hlen:])\n+ udp.SetDestinationPort(rt.MinPort)\n+ case header.TCPProtocolNumber:\n+ // TODO(gvisor.dev/issue/170): Need to recompute checksum\n+ // and implement nat connection tracking to support TCP.\n+ tcp := header.TCP(headerView[hlen:])\n+ tcp.SetDestinationPort(rt.MinPort)\n+ default:\n+ return RuleDrop, \"\"\n+ }\nreturn RuleAccept, \"\"\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -63,7 +63,7 @@ const (\n// TableAccept indicates the packet should continue through netstack.\nTableAccept TableVerdict = iota\n- // TableAccept indicates the packet should be dropped.\n+ // TableDrop indicates the packet should be dropped.\nTableDrop\n)\n@@ -175,5 +175,5 @@ type Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n// Jump, it also returns the name of the chain to jump to.\n- Action(packet tcpip.PacketBuffer) (RuleVerdict, string)\n+ Action(packet tcpip.PacketBuffer, filter IPHeaderFilter) (RuleVerdict, string)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -1087,19 +1087,8 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\n// TODO(gvisor.dev/issue/170): Not supporting iptables for IPv6 yet.\nif protocol == header.IPv4ProtocolNumber {\n- newPkt := pkt.Clone()\n-\n- headerView := newPkt.Data.First()\n- h := header.IPv4(headerView)\n- newPkt.NetworkHeader = headerView[:h.HeaderLength()]\n-\n- hlen := int(h.HeaderLength())\n- tlen := int(h.TotalLength())\n- newPkt.Data.TrimFront(hlen)\n- newPkt.Data.CapLength(tlen - hlen)\n-\nipt := n.stack.IPTables()\n- if ok := ipt.Check(iptables.Prerouting, newPkt); !ok {\n+ if ok := ipt.Check(iptables.Prerouting, pkt); !ok {\n// iptables is telling us to drop the packet.\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/nat.go", "new_path": "test/iptables/nat.go", "diff": "@@ -71,20 +71,12 @@ func (NATRedirectTCPPort) ContainerAction(ip net.IP) error {\n}\n// Listen for TCP packets on redirect port.\n- if err := listenTCP(redirectPort, sendloopDuration); err != nil {\n- return fmt.Errorf(\"connection on port %d should be accepted, but got error %v\", redirectPort, err)\n- }\n-\n- return nil\n+ return listenTCP(redirectPort, sendloopDuration)\n}\n// LocalAction implements TestCase.LocalAction.\nfunc (NATRedirectTCPPort) LocalAction(ip net.IP) error {\n- if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err != nil {\n- return fmt.Errorf(\"connection destined to port %d should be accepted, but got error %v\", dropPort, err)\n- }\n-\n- return nil\n+ return connectTCP(ip, dropPort, acceptPort, sendloopDuration)\n}\n// NATDropUDP tests that packets are not received in ports other than redirect port.\n" } ]
Go
Apache License 2.0
google/gvisor
Add nat table support for iptables. - commit the changes for the comments.
260,004
25.02.2020 15:15:28
28,800
5f1f9dd9d23d2b805c77b5c38d5900d13e6a29fe
Use link-local source address for link-local multicast Tests: header_test.TestIsV6LinkLocalMulticastAddress header_test.TestScopeForIPv6Address stack_test.TestIPv6SourceAddressSelectionScopeAndSameAddress
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6.go", "new_path": "pkg/tcpip/header/ipv6.go", "diff": "@@ -115,6 +115,19 @@ const (\n// for the secret key used to generate an opaque interface identifier as\n// outlined by RFC 7217.\nOpaqueIIDSecretKeyMinBytes = 16\n+\n+ // ipv6MulticastAddressScopeByteIdx is the byte where the scope (scop) field\n+ // is located within a multicast IPv6 address, as per RFC 4291 section 2.7.\n+ ipv6MulticastAddressScopeByteIdx = 1\n+\n+ // ipv6MulticastAddressScopeMask is the mask for the scope (scop) field,\n+ // within the byte holding the field, as per RFC 4291 section 2.7.\n+ ipv6MulticastAddressScopeMask = 0xF\n+\n+ // ipv6LinkLocalMulticastScope is the value of the scope (scop) field within\n+ // a multicast IPv6 address that indicates the address has link-local scope,\n+ // as per RFC 4291 section 2.7.\n+ ipv6LinkLocalMulticastScope = 2\n)\n// IPv6EmptySubnet is the empty IPv6 subnet. It may also be known as the\n@@ -340,6 +353,12 @@ func IsV6LinkLocalAddress(addr tcpip.Address) bool {\nreturn addr[0] == 0xfe && (addr[1]&0xc0) == 0x80\n}\n+// IsV6LinkLocalMulticastAddress determines if the provided address is an IPv6\n+// link-local multicast address.\n+func IsV6LinkLocalMulticastAddress(addr tcpip.Address) bool {\n+ return IsV6MulticastAddress(addr) && addr[ipv6MulticastAddressScopeByteIdx]&ipv6MulticastAddressScopeMask == ipv6LinkLocalMulticastScope\n+}\n+\n// IsV6UniqueLocalAddress determines if the provided address is an IPv6\n// unique-local address (within the prefix FC00::/7).\nfunc IsV6UniqueLocalAddress(addr tcpip.Address) bool {\n@@ -411,6 +430,9 @@ func ScopeForIPv6Address(addr tcpip.Address) (IPv6AddressScope, *tcpip.Error) {\n}\nswitch {\n+ case IsV6LinkLocalMulticastAddress(addr):\n+ return LinkLocalScope, nil\n+\ncase IsV6LinkLocalAddress(addr):\nreturn LinkLocalScope, nil\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/ipv6_test.go", "new_path": "pkg/tcpip/header/ipv6_test.go", "diff": "@@ -29,6 +29,7 @@ import (\nconst (\nlinkAddr = tcpip.LinkAddress(\"\\x02\\x02\\x03\\x04\\x05\\x06\")\nlinkLocalAddr = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n+ linkLocalMulticastAddr = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nuniqueLocalAddr1 = tcpip.Address(\"\\xfc\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nuniqueLocalAddr2 = tcpip.Address(\"\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\nglobalAddr = tcpip.Address(\"\\xa0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n@@ -256,6 +257,85 @@ func TestIsV6UniqueLocalAddress(t *testing.T) {\n}\n}\n+func TestIsV6LinkLocalMulticastAddress(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ addr tcpip.Address\n+ expected bool\n+ }{\n+ {\n+ name: \"Valid Link Local Multicast\",\n+ addr: linkLocalMulticastAddr,\n+ expected: true,\n+ },\n+ {\n+ name: \"Valid Link Local Multicast with flags\",\n+ addr: \"\\xff\\xf2\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\",\n+ expected: true,\n+ },\n+ {\n+ name: \"Link Local Unicast\",\n+ addr: linkLocalAddr,\n+ expected: false,\n+ },\n+ {\n+ name: \"IPv4 Multicast\",\n+ addr: \"\\xe0\\x00\\x00\\x01\",\n+ expected: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ if got := header.IsV6LinkLocalMulticastAddress(test.addr); got != test.expected {\n+ t.Errorf(\"got header.IsV6LinkLocalMulticastAddress(%s) = %t, want = %t\", test.addr, got, test.expected)\n+ }\n+ })\n+ }\n+}\n+\n+func TestIsV6LinkLocalAddress(t *testing.T) {\n+ tests := []struct {\n+ name string\n+ addr tcpip.Address\n+ expected bool\n+ }{\n+ {\n+ name: \"Valid Link Local Unicast\",\n+ addr: linkLocalAddr,\n+ expected: true,\n+ },\n+ {\n+ name: \"Link Local Multicast\",\n+ addr: linkLocalMulticastAddr,\n+ expected: false,\n+ },\n+ {\n+ name: \"Unique Local\",\n+ addr: uniqueLocalAddr1,\n+ expected: false,\n+ },\n+ {\n+ name: \"Global\",\n+ addr: globalAddr,\n+ expected: false,\n+ },\n+ {\n+ name: \"IPv4 Link Local\",\n+ addr: \"\\xa9\\xfe\\x00\\x01\",\n+ expected: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ if got := header.IsV6LinkLocalAddress(test.addr); got != test.expected {\n+ t.Errorf(\"got header.IsV6LinkLocalAddress(%s) = %t, want = %t\", test.addr, got, test.expected)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestScopeForIPv6Address(t *testing.T) {\ntests := []struct {\nname string\n@@ -270,11 +350,17 @@ func TestScopeForIPv6Address(t *testing.T) {\nerr: nil,\n},\n{\n- name: \"Link Local\",\n+ name: \"Link Local Unicast\",\naddr: linkLocalAddr,\nscope: header.LinkLocalScope,\nerr: nil,\n},\n+ {\n+ name: \"Link Local Multicast\",\n+ addr: linkLocalMulticastAddr,\n+ scope: header.LinkLocalScope,\n+ err: nil,\n+ },\n{\nname: \"Global\",\naddr: globalAddr,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2792,6 +2792,7 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nconst (\nlinkLocalAddr1 = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nlinkLocalAddr2 = tcpip.Address(\"\\xfe\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\n+ linkLocalMulticastAddr = tcpip.Address(\"\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nuniqueLocalAddr1 = tcpip.Address(\"\\xfc\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nuniqueLocalAddr2 = tcpip.Address(\"\\xfd\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\nglobalAddr1 = tcpip.Address(\"\\xa0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\n@@ -2869,6 +2870,18 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nconnectAddr: linkLocalAddr2,\nexpectedLocalAddr: linkLocalAddr1,\n},\n+ {\n+ name: \"Link Local most preferred for link local multicast (last address)\",\n+ nicAddrs: []tcpip.Address{globalAddr1, uniqueLocalAddr1, linkLocalAddr1},\n+ connectAddr: linkLocalMulticastAddr,\n+ expectedLocalAddr: linkLocalAddr1,\n+ },\n+ {\n+ name: \"Link Local most preferred for link local multicast (first address)\",\n+ nicAddrs: []tcpip.Address{linkLocalAddr1, uniqueLocalAddr1, globalAddr1},\n+ connectAddr: linkLocalMulticastAddr,\n+ expectedLocalAddr: linkLocalAddr1,\n+ },\n{\nname: \"Unique Local most preferred (last address)\",\nnicAddrs: []tcpip.Address{uniqueLocalAddr1, globalAddr1, linkLocalAddr1},\n" } ]
Go
Apache License 2.0
google/gvisor
Use link-local source address for link-local multicast Tests: - header_test.TestIsV6LinkLocalMulticastAddress - header_test.TestScopeForIPv6Address - stack_test.TestIPv6SourceAddressSelectionScopeAndSameAddress PiperOrigin-RevId: 297215576
259,854
25.02.2020 15:34:20
28,800
87288b26a1c40776da31c1edcbe9b1f3a6f5c1ed
Add netlink sockopt logging to strace.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/strace/socket.go", "new_path": "pkg/sentry/strace/socket.go", "diff": "@@ -632,4 +632,13 @@ var sockOptNames = map[uint64]abi.ValueSet{\nlinux.MCAST_MSFILTER: \"MCAST_MSFILTER\",\nlinux.IPV6_ADDRFORM: \"IPV6_ADDRFORM\",\n},\n+ linux.SOL_NETLINK: {\n+ linux.NETLINK_BROADCAST_ERROR: \"NETLINK_BROADCAST_ERROR\",\n+ linux.NETLINK_CAP_ACK: \"NETLINK_CAP_ACK\",\n+ linux.NETLINK_DUMP_STRICT_CHK: \"NETLINK_DUMP_STRICT_CHK\",\n+ linux.NETLINK_EXT_ACK: \"NETLINK_EXT_ACK\",\n+ linux.NETLINK_LIST_MEMBERSHIPS: \"NETLINK_LIST_MEMBERSHIPS\",\n+ linux.NETLINK_NO_ENOBUFS: \"NETLINK_NO_ENOBUFS\",\n+ linux.NETLINK_PKTINFO: \"NETLINK_PKTINFO\",\n+ },\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add netlink sockopt logging to strace. PiperOrigin-RevId: 297220008
259,845
25.02.2020 16:03:22
-32,400
6eb4ea30088a19428d6dfde965985e844b7a9a2a
user_guide: modify debug option
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/debugging.md", "new_path": "content/docs/user_guide/debugging.md", "diff": "@@ -107,7 +107,7 @@ execute `runsc debug` to collect profile information and save to a file. Here ar\nthe options available:\n* **--profile-heap:** Generates heap profile to the speficied file.\n-* **--profile-cpu:** Enables CPU profiler, waits for `--profile-delay` seconds\n+* **--profile-cpu:** Enables CPU profiler, waits for `--duration` seconds\nand generates CPU profile to the speficied file.\nFor example:\n@@ -117,7 +117,7 @@ docker run --runtime=runsc-prof --rm -d alpine sh -c \"while true; do echo runnin\n63254c6ab3a6989623fa1fb53616951eed31ac605a2637bb9ddba5d8d404b35b\nsudo runsc --root /var/run/docker/runtime-runsc-prof/moby debug --profile-heap=/tmp/heap.prof 63254c6ab3a6989623fa1fb53616951eed31ac605a2637bb9ddba5d8d404b35b\n-sudo runsc --root /var/run/docker/runtime-runsc-prof/moby debug --profile-cpu=/tmp/cpu.prof --profile-delay=30 63254c6ab3a6989623fa1fb53616951eed31ac605a2637bb9ddba5d8d404b35b\n+sudo runsc --root /var/run/docker/runtime-runsc-prof/moby debug --profile-cpu=/tmp/cpu.prof --duration=30s 63254c6ab3a6989623fa1fb53616951eed31ac605a2637bb9ddba5d8d404b35b\n```\nThe resulting files can be opened using `go tool pprof` or [pprof][]. The examples\n" } ]
Go
Apache License 2.0
google/gvisor
user_guide: modify debug option
259,974
25.02.2020 07:30:12
0
73201f4c5700ce7af404b968698b86d80989ab1e
Code Clean: Move arch independent codes to common file in kvm pkg.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm.go", "new_path": "pkg/sentry/platform/kvm/kvm.go", "diff": "@@ -27,6 +27,38 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n+// userMemoryRegion is a region of physical memory.\n+//\n+// This mirrors kvm_memory_region.\n+type userMemoryRegion struct {\n+ slot uint32\n+ flags uint32\n+ guestPhysAddr uint64\n+ memorySize uint64\n+ userspaceAddr uint64\n+}\n+\n+// runData is the run structure. This may be mapped for synchronous register\n+// access (although that doesn't appear to be supported by my kernel at least).\n+//\n+// This mirrors kvm_run.\n+type runData struct {\n+ requestInterruptWindow uint8\n+ _ [7]uint8\n+\n+ exitReason uint32\n+ readyForInterruptInjection uint8\n+ ifFlag uint8\n+ _ [2]uint8\n+\n+ cr8 uint64\n+ apicBase uint64\n+\n+ // This is the union data for exits. Interpretation depends entirely on\n+ // the exitReason above (see vCPU code for more information).\n+ data [32]uint64\n+}\n+\n// KVM represents a lightweight VM context.\ntype KVM struct {\nplatform.NoCPUPreemptionDetection\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_amd64.go", "new_path": "pkg/sentry/platform/kvm/kvm_amd64.go", "diff": "@@ -21,17 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/platform/ring0\"\n)\n-// userMemoryRegion is a region of physical memory.\n-//\n-// This mirrors kvm_memory_region.\n-type userMemoryRegion struct {\n- slot uint32\n- flags uint32\n- guestPhysAddr uint64\n- memorySize uint64\n- userspaceAddr uint64\n-}\n-\n// userRegs represents KVM user registers.\n//\n// This mirrors kvm_regs.\n@@ -169,27 +158,6 @@ type modelControlRegisters struct {\nentries [16]modelControlRegister\n}\n-// runData is the run structure. This may be mapped for synchronous register\n-// access (although that doesn't appear to be supported by my kernel at least).\n-//\n-// This mirrors kvm_run.\n-type runData struct {\n- requestInterruptWindow uint8\n- _ [7]uint8\n-\n- exitReason uint32\n- readyForInterruptInjection uint8\n- ifFlag uint8\n- _ [2]uint8\n-\n- cr8 uint64\n- apicBase uint64\n-\n- // This is the union data for exits. Interpretation depends entirely on\n- // the exitReason above (see vCPU code for more information).\n- data [32]uint64\n-}\n-\n// cpuidEntry is a single CPUID entry.\n//\n// This mirrors kvm_cpuid_entry2.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm_arm64.go", "new_path": "pkg/sentry/platform/kvm/kvm_arm64.go", "diff": "@@ -20,17 +20,6 @@ import (\n\"syscall\"\n)\n-// userMemoryRegion is a region of physical memory.\n-//\n-// This mirrors kvm_memory_region.\n-type userMemoryRegion struct {\n- slot uint32\n- flags uint32\n- guestPhysAddr uint64\n- memorySize uint64\n- userspaceAddr uint64\n-}\n-\ntype kvmOneReg struct {\nid uint64\naddr uint64\n@@ -53,27 +42,6 @@ type userRegs struct {\nfpRegs userFpsimdState\n}\n-// runData is the run structure. This may be mapped for synchronous register\n-// access (although that doesn't appear to be supported by my kernel at least).\n-//\n-// This mirrors kvm_run.\n-type runData struct {\n- requestInterruptWindow uint8\n- _ [7]uint8\n-\n- exitReason uint32\n- readyForInterruptInjection uint8\n- ifFlag uint8\n- _ [2]uint8\n-\n- cr8 uint64\n- apicBase uint64\n-\n- // This is the union data for exits. Interpretation depends entirely on\n- // the exitReason above (see vCPU code for more information).\n- data [32]uint64\n-}\n-\n// updateGlobalOnce does global initialization. It has to be called only once.\nfunc updateGlobalOnce(fd int) error {\nphysicalInit()\n" } ]
Go
Apache License 2.0
google/gvisor
Code Clean: Move arch independent codes to common file in kvm pkg. Signed-off-by: Haibo Xu <[email protected]> Change-Id: Iefbdf53e8e8d6d23ae75d8a2ff0d2a6e71f414d8
259,858
25.02.2020 19:03:23
28,800
fba479b3c78621cb122af20d1d677fe9193a971c
Fix DATA RACE in fs.MayDelete. MayDelete must lock the directory also, otherwise concurrent renames may race. Note that this also changes the methods to be aligned with the actual Remove and RemoveDirectory methods to minimize confusion when reading the code. (It was hard to see that resolution was correct.)
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/dirent.go", "new_path": "pkg/sentry/fs/dirent.go", "diff": "@@ -1438,8 +1438,8 @@ func lockForRename(oldParent *Dirent, oldName string, newParent *Dirent, newName\n}, nil\n}\n-func checkSticky(ctx context.Context, dir *Dirent, victim *Dirent) error {\n- uattr, err := dir.Inode.UnstableAttr(ctx)\n+func (d *Dirent) checkSticky(ctx context.Context, victim *Dirent) error {\n+ uattr, err := d.Inode.UnstableAttr(ctx)\nif err != nil {\nreturn syserror.EPERM\n}\n@@ -1465,30 +1465,33 @@ func checkSticky(ctx context.Context, dir *Dirent, victim *Dirent) error {\nreturn syserror.EPERM\n}\n-// MayDelete determines whether `name`, a child of `dir`, can be deleted or\n+// MayDelete determines whether `name`, a child of `d`, can be deleted or\n// renamed by `ctx`.\n//\n// Compare Linux kernel fs/namei.c:may_delete.\n-func MayDelete(ctx context.Context, root, dir *Dirent, name string) error {\n- if err := dir.Inode.CheckPermission(ctx, PermMask{Write: true, Execute: true}); err != nil {\n+func (d *Dirent) MayDelete(ctx context.Context, root *Dirent, name string) error {\n+ if err := d.Inode.CheckPermission(ctx, PermMask{Write: true, Execute: true}); err != nil {\nreturn err\n}\n- victim, err := dir.Walk(ctx, root, name)\n+ unlock := d.lockDirectory()\n+ defer unlock()\n+\n+ victim, err := d.walk(ctx, root, name, true /* may unlock */)\nif err != nil {\nreturn err\n}\ndefer victim.DecRef()\n- return mayDelete(ctx, dir, victim)\n+ return d.mayDelete(ctx, victim)\n}\n// mayDelete determines whether `victim`, a child of `dir`, can be deleted or\n// renamed by `ctx`.\n//\n// Preconditions: `dir` is writable and executable by `ctx`.\n-func mayDelete(ctx context.Context, dir, victim *Dirent) error {\n- if err := checkSticky(ctx, dir, victim); err != nil {\n+func (d *Dirent) mayDelete(ctx context.Context, victim *Dirent) error {\n+ if err := d.checkSticky(ctx, victim); err != nil {\nreturn err\n}\n@@ -1542,7 +1545,7 @@ func Rename(ctx context.Context, root *Dirent, oldParent *Dirent, oldName string\ndefer renamed.DecRef()\n// Check that the renamed dirent is deletable.\n- if err := mayDelete(ctx, oldParent, renamed); err != nil {\n+ if err := oldParent.mayDelete(ctx, renamed); err != nil {\nreturn err\n}\n@@ -1580,7 +1583,7 @@ func Rename(ctx context.Context, root *Dirent, oldParent *Dirent, oldName string\n// across the Rename, so must call DecRef manually (no defer).\n// Check that we can delete replaced.\n- if err := mayDelete(ctx, newParent, replaced); err != nil {\n+ if err := newParent.mayDelete(ctx, replaced); err != nil {\nreplaced.DecRef()\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_file.go", "new_path": "pkg/sentry/syscalls/linux/sys_file.go", "diff": "@@ -1236,7 +1236,7 @@ func rmdirAt(t *kernel.Task, dirFD int32, addr usermem.Addr) error {\nreturn syserror.ENOTEMPTY\n}\n- if err := fs.MayDelete(t, root, d, name); err != nil {\n+ if err := d.MayDelete(t, root, name); err != nil {\nreturn err\n}\n@@ -1517,7 +1517,7 @@ func unlinkAt(t *kernel.Task, dirFD int32, addr usermem.Addr) error {\nreturn syserror.ENOTDIR\n}\n- if err := fs.MayDelete(t, root, d, name); err != nil {\n+ if err := d.MayDelete(t, root, name); err != nil {\nreturn err\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix DATA RACE in fs.MayDelete. MayDelete must lock the directory also, otherwise concurrent renames may race. Note that this also changes the methods to be aligned with the actual Remove and RemoveDirectory methods to minimize confusion when reading the code. (It was hard to see that resolution was correct.) PiperOrigin-RevId: 297258304
259,885
25.02.2020 19:12:22
28,800
a92087f0f8fe82ce99414ec99ffe33e514cb21f6
Add VFS.NewDisconnectedMount(). Analogous to Linux's kern_mount().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -139,6 +139,23 @@ func (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth\nreturn mntns, nil\n}\n+// NewDisconnectedMount returns a Mount representing fs with the given root\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+ fs.IncRef()\n+ if root != nil {\n+ root.IncRef()\n+ }\n+ return &Mount{\n+ vfs: vfs,\n+ fs: fs,\n+ root: root,\n+ refs: 1,\n+ }, nil\n+}\n+\n// MountAt creates and mounts a Filesystem configured by the given arguments.\nfunc (vfs *VirtualFilesystem) MountAt(ctx context.Context, creds *auth.Credentials, source string, target *PathOperation, fsTypeName string, opts *MountOptions) error {\nrft := vfs.getFilesystemType(fsTypeName)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -126,17 +126,23 @@ func (vfs *VirtualFilesystem) Init() error {\n// Construct vfs.anonMount.\nanonfsDevMinor, err := vfs.GetAnonBlockDevMinor()\nif err != nil {\n- return err\n+ // This shouldn't be possible since anonBlockDevMinorNext was\n+ // initialized to 1 above (no device numbers have been allocated yet).\n+ panic(fmt.Sprintf(\"VirtualFilesystem.Init: device number allocation for anonfs failed: %v\", err))\n}\nanonfs := anonFilesystem{\ndevMinor: anonfsDevMinor,\n}\nanonfs.vfsfs.Init(vfs, &anonfs)\n- vfs.anonMount = &Mount{\n- vfs: vfs,\n- fs: &anonfs.vfsfs,\n- refs: 1,\n+ defer anonfs.vfsfs.DecRef()\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+ vfs.anonMount = anonMount\n+\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add VFS.NewDisconnectedMount(). Analogous to Linux's kern_mount(). PiperOrigin-RevId: 297259580
259,891
14.02.2020 17:19:32
28,800
408979e619c4b5df74503c7a887aaaa06fd0d730
iptables: filter by IP address (and range) Enables commands such as: $ iptables -A INPUT -d 127.0.0.1 -j ACCEPT $ iptables -t nat -A PREROUTING ! -d 127.0.0.1 -j REDIRECT Also adds a bunch of REDIRECT+destination tests.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -158,10 +158,36 @@ type IPTIP struct {\n// Flags define matching behavior for the IP header.\nFlags uint8\n- // InverseFlags invert the meaning of fields in struct IPTIP.\n+ // InverseFlags invert the meaning of fields in struct IPTIP. See the\n+ // IPT_INV_* flags.\nInverseFlags uint8\n}\n+// Inverts the meaning of the Protocol field. Corresponds to a constant in\n+// include/uapi/linux/netfilter/x_tables.h.\n+const XT_INV_PROTO = 0x40\n+\n+// Flags in IPTIP.InverseFlags. Corresponding constants are in\n+// include/uapi/linux/netfilter_ipv4/ip_tables.h.\n+const (\n+ // Invert the meaning of InputInterface.\n+ IPT_INV_VIA_IN = 0x01\n+ // Invert the meaning of OutputInterface.\n+ IPT_INV_VIA_OUT = 0x02\n+ // Unclear what this is, as no references to it exist in the kernel.\n+ IPT_INV_TOS = 0x04\n+ // Invert the meaning of Src.\n+ IPT_INV_SRCIP = 0x08\n+ // Invert the meaning of Dst.\n+ IPT_INV_DSTIP = 0x10\n+ // Invert the meaning of the IPT_F_FRAG flag.\n+ IPT_INV_FRAG = 0x20\n+ // Invert the meaning of the Protocol field.\n+ IPT_INV_PROTO = XT_INV_PROTO\n+ // Enable all flags.\n+ IPT_INV_MASK = 0x7F\n+)\n+\n// SizeOfIPTIP is the size of an IPTIP.\nconst SizeOfIPTIP = 84\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n@@ -630,8 +631,14 @@ func filterFromIPTIP(iptip linux.IPTIP) (iptables.IPHeaderFilter, error) {\nif containsUnsupportedFields(iptip) {\nreturn iptables.IPHeaderFilter{}, fmt.Errorf(\"unsupported fields in struct iptip: %+v\", iptip)\n}\n+ if len(iptip.Dst) != header.IPv4AddressSize || len(iptip.DstMask) != header.IPv4AddressSize {\n+ return iptables.IPHeaderFilter{}, fmt.Errorf(\"incorrect length of destination (%d) and/or destination mask (%d) fields\", len(iptip.Dst), len(iptip.DstMask))\n+ }\nreturn iptables.IPHeaderFilter{\nProtocol: tcpip.TransportProtocolNumber(iptip.Protocol),\n+ Dst: tcpip.Address(iptip.Dst[:]),\n+ DstMask: tcpip.Address(iptip.DstMask[:]),\n+ DstInvert: iptip.InverseFlags&linux.IPT_INV_DSTIP != 0,\n}, nil\n}\n@@ -639,16 +646,16 @@ func containsUnsupportedFields(iptip linux.IPTIP) bool {\n// Currently we check that everything except protocol is zeroed.\nvar emptyInetAddr = linux.InetAddr{}\nvar emptyInterface = [linux.IFNAMSIZ]byte{}\n- return iptip.Dst != emptyInetAddr ||\n- iptip.Src != emptyInetAddr ||\n+ // Disable any supported inverse flags.\n+ inverseMask := uint8(linux.IPT_INV_DSTIP)\n+ return iptip.Src != emptyInetAddr ||\niptip.SrcMask != emptyInetAddr ||\n- iptip.DstMask != emptyInetAddr ||\niptip.InputInterface != emptyInterface ||\niptip.OutputInterface != emptyInterface ||\niptip.InputInterfaceMask != emptyInterface ||\niptip.OutputInterfaceMask != emptyInterface ||\niptip.Flags != 0 ||\n- iptip.InverseFlags != 0\n+ iptip.InverseFlags&^inverseMask != 0\n}\nfunc validUnderflow(rule iptables.Rule) bool {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -240,9 +240,8 @@ func (it *IPTables) checkChain(hook Hook, pkt tcpip.PacketBuffer, table Table, r\nfunc (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) (RuleVerdict, int) {\nrule := table.Rules[ruleIdx]\n- // First check whether the packet matches the IP header filter.\n- // TODO(gvisor.dev/issue/170): Support other fields of the filter.\n- if rule.Filter.Protocol != 0 && rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\n+ // Check whether the packet matches the IP header filter.\n+ if !filterMatch(rule.Filter, header.IPv4(pkt.NetworkHeader)) {\n// Continue on to the next rule.\nreturn RuleJump, ruleIdx + 1\n}\n@@ -263,3 +262,26 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\n// All the matchers matched, so run the target.\nreturn rule.Target.Action(pkt)\n}\n+\n+func filterMatch(filter IPHeaderFilter, hdr header.IPv4) bool {\n+ // TODO(gvisor.dev/issue/170): Support other fields of the filter.\n+ // Check the transport protocol.\n+ if filter.Protocol != 0 && filter.Protocol != hdr.TransportProtocol() {\n+ return false\n+ }\n+\n+ // Check the destination IP.\n+ dest := hdr.DestinationAddress()\n+ matches := true\n+ for i := range filter.Dst {\n+ if dest[i]&filter.DstMask[i] != filter.Dst[i] {\n+ matches = false\n+ break\n+ }\n+ }\n+ if matches == filter.DstInvert {\n+ return false\n+ }\n+\n+ return true\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -144,6 +144,18 @@ type Rule struct {\ntype IPHeaderFilter struct {\n// Protocol matches the transport protocol.\nProtocol tcpip.TransportProtocolNumber\n+\n+ // Dst matches the destination IP address.\n+ Dst tcpip.Address\n+\n+ // DstMask masks bits of the destination IP address when comparing with\n+ // Dst.\n+ DstMask tcpip.Address\n+\n+ // DstInvert inverts the meaning of the destination IP check, i.e. when\n+ // true the filter will match packets that fail the destination\n+ // comparison.\n+ DstInvert bool\n}\n// A Matcher is the interface for matching packets.\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -47,6 +47,8 @@ func init() {\nRegisterTestCase(FilterInputJumpReturnDrop{})\nRegisterTestCase(FilterInputJumpBuiltin{})\nRegisterTestCase(FilterInputJumpTwice{})\n+ RegisterTestCase(FilterInputDestination{})\n+ RegisterTestCase(FilterInputInvertDestination{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -595,3 +597,66 @@ func (FilterInputJumpTwice) ContainerAction(ip net.IP) error {\nfunc (FilterInputJumpTwice) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// FilterInputDestination verifies that we can filter packets via `-d\n+// <ipaddr>`.\n+type FilterInputDestination struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDestination) Name() string {\n+ return \"FilterInputDestination\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDestination) ContainerAction(ip net.IP) error {\n+ addrs, err := localAddrs()\n+ if err != nil {\n+ return err\n+ }\n+\n+ // Make INPUT's default action DROP, then ACCEPT all packets bound for\n+ // this machine.\n+ rules := [][]string{{\"-P\", \"INPUT\", \"DROP\"}}\n+ for _, addr := range addrs {\n+ rules = append(rules, []string{\"-A\", \"INPUT\", \"-d\", addr, \"-j\", \"ACCEPT\"})\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDestination) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// FilterInputDestination verifies that we can filter packets via `! -d\n+// <ipaddr>`.\n+type FilterInputInvertDestination struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputInvertDestination) Name() string {\n+ return \"FilterInputInvertDestination\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputInvertDestination) ContainerAction(ip net.IP) error {\n+ // Make INPUT's default action DROP, then ACCEPT all packets not bound\n+ // for 127.0.0.1.\n+ rules := [][]string{\n+ {\"-P\", \"INPUT\", \"DROP\"},\n+ {\"-A\", \"INPUT\", \"!\", \"-d\", localIP, \"-j\", \"ACCEPT\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputInvertDestination) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_output.go", "new_path": "test/iptables/filter_output.go", "diff": "@@ -22,6 +22,8 @@ import (\nfunc init() {\nRegisterTestCase(FilterOutputDropTCPDestPort{})\nRegisterTestCase(FilterOutputDropTCPSrcPort{})\n+ RegisterTestCase(FilterOutputDestination{})\n+ RegisterTestCase(FilterOutputInvertDestination{})\n}\n// FilterOutputDropTCPDestPort tests that connections are not accepted on specified source ports.\n@@ -85,3 +87,57 @@ func (FilterOutputDropTCPSrcPort) LocalAction(ip net.IP) error {\nreturn nil\n}\n+\n+// FilterOutputDestination tests that we can selectively allow packets to\n+// certain destinations.\n+type FilterOutputDestination struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterOutputDestination) Name() string {\n+ return \"FilterOutputDestination\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterOutputDestination) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n+ {\"-A\", \"OUTPUT\", \"-d\", ip.String(), \"-j\", \"ACCEPT\"},\n+ {\"-P\", \"OUTPUT\", \"DROP\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterOutputDestination) LocalAction(ip net.IP) error {\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// FilterOutputInvertDestination tests that we can selectively allow packets\n+// not headed for a particular destination.\n+type FilterOutputInvertDestination struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterOutputInvertDestination) Name() string {\n+ return \"FilterOutputInvertDestination\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterOutputInvertDestination) ContainerAction(ip net.IP) error {\n+ rules := [][]string{\n+ {\"-A\", \"OUTPUT\", \"!\", \"-d\", localIP, \"-j\", \"ACCEPT\"},\n+ {\"-P\", \"OUTPUT\", \"DROP\"},\n+ }\n+ if err := filterTableRules(rules); err != nil {\n+ return err\n+ }\n+\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterOutputInvertDestination) LocalAction(ip net.IP) error {\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -285,3 +285,69 @@ func TestJumpTwice(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\n+func TestInputDestination(t *testing.T) {\n+ if err := singleTest(FilterInputDestination{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestInputInvertDestination(t *testing.T) {\n+ if err := singleTest(FilterInputInvertDestination{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestOutputDestination(t *testing.T) {\n+ if err := singleTest(FilterOutputDestination{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestOutputInvertDestination(t *testing.T) {\n+ if err := singleTest(FilterOutputInvertDestination{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATOutRedirectIP(t *testing.T) {\n+ if err := singleTest(NATOutRedirectIP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATOutDontRedirectIP(t *testing.T) {\n+ if err := singleTest(NATOutDontRedirectIP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATOutRedirectInvert(t *testing.T) {\n+ if err := singleTest(NATOutRedirectInvert{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATPreRedirectIP(t *testing.T) {\n+ if err := singleTest(NATPreRedirectIP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATPreDontRedirectIP(t *testing.T) {\n+ if err := singleTest(NATPreDontRedirectIP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATPreRedirectInvert(t *testing.T) {\n+ if err := singleTest(NATPreRedirectInvert{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestNATRedirectRequiresProtocol(t *testing.T) {\n+ if err := singleTest(NATRedirectRequiresProtocol{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_util.go", "new_path": "test/iptables/iptables_util.go", "diff": "@@ -24,6 +24,7 @@ import (\n)\nconst iptablesBinary = \"iptables\"\n+const localIP = \"127.0.0.1\"\n// filterTable calls `iptables -t filter` with the given args.\nfunc filterTable(args ...string) error {\n@@ -46,8 +47,17 @@ func tableCmd(table string, args []string) error {\n// filterTableRules is like filterTable, but runs multiple iptables commands.\nfunc filterTableRules(argsList [][]string) error {\n+ return tableRules(\"filter\", argsList)\n+}\n+\n+// natTableRules is like natTable, but runs multiple iptables commands.\n+func natTableRules(argsList [][]string) error {\n+ return tableRules(\"nat\", argsList)\n+}\n+\n+func tableRules(table string, argsList [][]string) error {\nfor _, args := range argsList {\n- if err := filterTable(args...); err != nil {\n+ if err := tableCmd(table, args); err != nil {\nreturn err\n}\n}\n@@ -149,3 +159,16 @@ func connectTCP(ip net.IP, remotePort, localPort int, timeout time.Duration) err\nreturn nil\n}\n+\n+// localAddrs returns a list of local network interface addresses.\n+func localAddrs() ([]string, error) {\n+ addrs, err := net.InterfaceAddrs()\n+ if err != nil {\n+ return nil, err\n+ }\n+ addrStrs := make([]string, 0, len(addrs))\n+ for _, addr := range addrs {\n+ addrStrs = append(addrStrs, addr.String())\n+ }\n+ return addrStrs, nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/nat.go", "new_path": "test/iptables/nat.go", "diff": "package iptables\nimport (\n+ \"errors\"\n\"fmt\"\n\"net\"\n+ \"time\"\n)\nconst (\n@@ -26,6 +28,13 @@ const (\nfunc init() {\nRegisterTestCase(NATRedirectUDPPort{})\nRegisterTestCase(NATDropUDP{})\n+ RegisterTestCase(NATPreRedirectIP{})\n+ RegisterTestCase(NATPreDontRedirectIP{})\n+ RegisterTestCase(NATPreRedirectInvert{})\n+ RegisterTestCase(NATOutRedirectIP{})\n+ RegisterTestCase(NATOutDontRedirectIP{})\n+ RegisterTestCase(NATOutRedirectInvert{})\n+ RegisterTestCase(NATRedirectRequiresProtocol{})\n}\n// NATRedirectUDPPort tests that packets are redirected to different port.\n@@ -53,7 +62,8 @@ func (NATRedirectUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n-// NATDropUDP tests that packets are not received in ports other than redirect port.\n+// NATDropUDP tests that packets are not received in ports other than redirect\n+// port.\ntype NATDropUDP struct{}\n// Name implements TestCase.Name.\n@@ -78,3 +88,192 @@ func (NATDropUDP) ContainerAction(ip net.IP) error {\nfunc (NATDropUDP) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// NATOutRedirectIP uses iptables to select packets based on destination IP and\n+// redirects them.\n+type NATOutRedirectIP struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATOutRedirectIP) Name() string {\n+ return \"NATOutRedirectIP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATOutRedirectIP) ContainerAction(ip net.IP) error {\n+ // Redirect OUTPUT packets to a listening localhost port.\n+ dest := net.IP([]byte{200, 0, 0, 2})\n+ return loopbackTest(dest, \"-A\", \"OUTPUT\", \"-d\", dest.String(), \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-port\", fmt.Sprintf(\"%d\", acceptPort))\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATOutRedirectIP) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// NATOutDontRedirectIP tests that iptables matching with \"-d\" does not match\n+// packets it shouldn't.\n+type NATOutDontRedirectIP struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATOutDontRedirectIP) Name() string {\n+ return \"NATOutDontRedirectIP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATOutDontRedirectIP) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"OUTPUT\", \"-d\", localIP, \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-port\", fmt.Sprintf(\"%d\", dropPort)); err != nil {\n+ return err\n+ }\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATOutDontRedirectIP) LocalAction(ip net.IP) error {\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// NATOutRedirectInvert tests that iptables can match with \"! -d\".\n+type NATOutRedirectInvert struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATOutRedirectInvert) Name() string {\n+ return \"NATOutRedirectInvert\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATOutRedirectInvert) ContainerAction(ip net.IP) error {\n+ // Redirect OUTPUT packets to a listening localhost port.\n+ dest := []byte{200, 0, 0, 3}\n+ destStr := \"200.0.0.2\"\n+ return loopbackTest(dest, \"-A\", \"OUTPUT\", \"!\", \"-d\", destStr, \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-port\", fmt.Sprintf(\"%d\", acceptPort))\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATOutRedirectInvert) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// NATPreRedirectIP tests that we can use iptables to select packets based on\n+// destination IP and redirect them.\n+type NATPreRedirectIP struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATPreRedirectIP) Name() string {\n+ return \"NATPreRedirectIP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATPreRedirectIP) ContainerAction(ip net.IP) error {\n+ addrs, err := localAddrs()\n+ if err != nil {\n+ return err\n+ }\n+\n+ var rules [][]string\n+ for _, addr := range addrs {\n+ rules = append(rules, []string{\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-d\", addr, \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", acceptPort)})\n+ }\n+ if err := natTableRules(rules); err != nil {\n+ return err\n+ }\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATPreRedirectIP) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, dropPort, sendloopDuration)\n+}\n+\n+// NATPreDontRedirectIP tests that iptables matching with \"-d\" does not match\n+// packets it shouldn't.\n+type NATPreDontRedirectIP struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATPreDontRedirectIP) Name() string {\n+ return \"NATPreDontRedirectIP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATPreDontRedirectIP) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-d\", localIP, \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", dropPort)); err != nil {\n+ return err\n+ }\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATPreDontRedirectIP) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// NATPreRedirectInvert tests that iptables can match with \"! -d\".\n+type NATPreRedirectInvert struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATPreRedirectInvert) Name() string {\n+ return \"NATPreRedirectInvert\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATPreRedirectInvert) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-p\", \"udp\", \"!\", \"-d\", localIP, \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", acceptPort)); err != nil {\n+ return err\n+ }\n+ return listenUDP(acceptPort, sendloopDuration)\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATPreRedirectInvert) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, dropPort, sendloopDuration)\n+}\n+\n+// NATRedirectRequiresProtocol tests that use of the --to-ports flag requires a\n+// protocol to be specified with -p.\n+type NATRedirectRequiresProtocol struct{}\n+\n+// Name implements TestCase.Name.\n+func (NATRedirectRequiresProtocol) Name() string {\n+ return \"NATRedirectRequiresProtocol\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (NATRedirectRequiresProtocol) ContainerAction(ip net.IP) error {\n+ if err := natTable(\"-A\", \"PREROUTING\", \"-d\", localIP, \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", acceptPort)); err == nil {\n+ return errors.New(\"expected an error using REDIRECT --to-ports without a protocol\")\n+ }\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (NATRedirectRequiresProtocol) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// loopbackTests runs an iptables rule and ensures that packets sent to\n+// dest:dropPort are received by localhost:acceptPort.\n+func loopbackTest(dest net.IP, args ...string) error {\n+ if err := natTable(args...); err != nil {\n+ return err\n+ }\n+ sendCh := make(chan error)\n+ listenCh := make(chan error)\n+ go func() {\n+ sendCh <- sendUDPLoop(dest, dropPort, sendloopDuration)\n+ }()\n+ go func() {\n+ listenCh <- listenUDP(acceptPort, sendloopDuration)\n+ }()\n+ select {\n+ case err := <-listenCh:\n+ if err != nil {\n+ return err\n+ }\n+ case <-time.After(sendloopDuration):\n+ return errors.New(\"timed out\")\n+ }\n+ // sendCh will always take the full sendloop time.\n+ return <-sendCh\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
iptables: filter by IP address (and range) Enables commands such as: $ iptables -A INPUT -d 127.0.0.1 -j ACCEPT $ iptables -t nat -A PREROUTING ! -d 127.0.0.1 -j REDIRECT Also adds a bunch of REDIRECT+destination tests.
259,985
26.02.2020 19:28:20
28,800
8fb84f78adfc0dba964ebe97edb51ebf8a80f752
Fix construct of linux.Stat for arm64.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/BUILD", "new_path": "pkg/sentry/syscalls/linux/BUILD", "diff": "@@ -42,6 +42,8 @@ go_library(\n\"sys_socket.go\",\n\"sys_splice.go\",\n\"sys_stat.go\",\n+ \"sys_stat_amd64.go\",\n+ \"sys_stat_arm64.go\",\n\"sys_sync.go\",\n\"sys_sysinfo.go\",\n\"sys_syslog.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_stat.go", "new_path": "pkg/sentry/syscalls/linux/sys_stat.go", "diff": "@@ -25,24 +25,6 @@ import (\n// LINT.IfChange\n-func statFromAttrs(t *kernel.Task, sattr fs.StableAttr, uattr fs.UnstableAttr) linux.Stat {\n- return linux.Stat{\n- Dev: sattr.DeviceID,\n- Ino: sattr.InodeID,\n- Nlink: uattr.Links,\n- Mode: sattr.Type.LinuxType() | uint32(uattr.Perms.LinuxMode()),\n- UID: uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()),\n- GID: uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()),\n- Rdev: uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)),\n- Size: uattr.Size,\n- Blksize: sattr.BlockSize,\n- Blocks: uattr.Usage / 512,\n- ATime: uattr.AccessTime.Timespec(),\n- MTime: uattr.ModificationTime.Timespec(),\n- CTime: uattr.StatusChangeTime.Timespec(),\n- }\n-}\n-\n// Stat implements linux syscall stat(2).\nfunc Stat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\naddr := args[0].Pointer()\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_stat_amd64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build amd64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+)\n+\n+// LINT.IfChange\n+\n+func statFromAttrs(t *kernel.Task, sattr fs.StableAttr, uattr fs.UnstableAttr) linux.Stat {\n+ return linux.Stat{\n+ Dev: sattr.DeviceID,\n+ Ino: sattr.InodeID,\n+ Nlink: uattr.Links,\n+ Mode: sattr.Type.LinuxType() | uint32(uattr.Perms.LinuxMode()),\n+ UID: uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()),\n+ GID: uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()),\n+ Rdev: uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)),\n+ Size: uattr.Size,\n+ Blksize: sattr.BlockSize,\n+ Blocks: uattr.Usage / 512,\n+ ATime: uattr.AccessTime.Timespec(),\n+ MTime: uattr.ModificationTime.Timespec(),\n+ CTime: uattr.StatusChangeTime.Timespec(),\n+ }\n+}\n+\n+// LINT.ThenChange(vfs2/stat_amd64.go)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_stat_arm64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+)\n+\n+// LINT.IfChange\n+\n+func statFromAttrs(t *kernel.Task, sattr fs.StableAttr, uattr fs.UnstableAttr) linux.Stat {\n+ return linux.Stat{\n+ Dev: sattr.DeviceID,\n+ Ino: sattr.InodeID,\n+ Nlink: uint32(uattr.Links),\n+ Mode: sattr.Type.LinuxType() | uint32(uattr.Perms.LinuxMode()),\n+ UID: uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()),\n+ GID: uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()),\n+ Rdev: uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)),\n+ Size: uattr.Size,\n+ Blksize: int32(sattr.BlockSize),\n+ Blocks: uattr.Usage / 512,\n+ ATime: uattr.AccessTime.Timespec(),\n+ MTime: uattr.ModificationTime.Timespec(),\n+ CTime: uattr.StatusChangeTime.Timespec(),\n+ }\n+}\n+\n+// LINT.ThenChange(vfs2/stat_arm64.go)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD", "diff": "@@ -22,6 +22,8 @@ go_library(\n\"read_write.go\",\n\"setstat.go\",\n\"stat.go\",\n+ \"stat_amd64.go\",\n+ \"stat_arm64.go\",\n\"sync.go\",\n\"xattr.go\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/vfs2/stat.go", "new_path": "pkg/sentry/syscalls/linux/vfs2/stat.go", "diff": "@@ -113,29 +113,6 @@ func fstatat(t *kernel.Task, dirfd int32, pathAddr, statAddr usermem.Addr, flags\nreturn stat.CopyOut(t, statAddr)\n}\n-// This takes both input and output as pointer arguments to avoid copying large\n-// structs.\n-func convertStatxToUserStat(t *kernel.Task, statx *linux.Statx, stat *linux.Stat) {\n- // Linux just copies fields from struct kstat without regard to struct\n- // kstat::result_mask (fs/stat.c:cp_new_stat()), so we do too.\n- userns := t.UserNamespace()\n- *stat = linux.Stat{\n- Dev: uint64(linux.MakeDeviceID(uint16(statx.DevMajor), statx.DevMinor)),\n- Ino: statx.Ino,\n- Nlink: uint64(statx.Nlink),\n- Mode: uint32(statx.Mode),\n- UID: uint32(auth.KUID(statx.UID).In(userns).OrOverflow()),\n- GID: uint32(auth.KGID(statx.GID).In(userns).OrOverflow()),\n- Rdev: uint64(linux.MakeDeviceID(uint16(statx.RdevMajor), statx.RdevMinor)),\n- Size: int64(statx.Size),\n- Blksize: int64(statx.Blksize),\n- Blocks: int64(statx.Blocks),\n- ATime: timespecFromStatxTimestamp(statx.Atime),\n- MTime: timespecFromStatxTimestamp(statx.Mtime),\n- CTime: timespecFromStatxTimestamp(statx.Ctime),\n- }\n-}\n-\nfunc timespecFromStatxTimestamp(sxts linux.StatxTimestamp) linux.Timespec {\nreturn linux.Timespec{\nSec: sxts.Sec,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/vfs2/stat_amd64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build amd64\n+\n+package vfs2\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+)\n+\n+// This takes both input and output as pointer arguments to avoid copying large\n+// structs.\n+func convertStatxToUserStat(t *kernel.Task, statx *linux.Statx, stat *linux.Stat) {\n+ // Linux just copies fields from struct kstat without regard to struct\n+ // kstat::result_mask (fs/stat.c:cp_new_stat()), so we do too.\n+ userns := t.UserNamespace()\n+ *stat = linux.Stat{\n+ Dev: uint64(linux.MakeDeviceID(uint16(statx.DevMajor), statx.DevMinor)),\n+ Ino: statx.Ino,\n+ Nlink: uint64(statx.Nlink),\n+ Mode: uint32(statx.Mode),\n+ UID: uint32(auth.KUID(statx.UID).In(userns).OrOverflow()),\n+ GID: uint32(auth.KGID(statx.GID).In(userns).OrOverflow()),\n+ Rdev: uint64(linux.MakeDeviceID(uint16(statx.RdevMajor), statx.RdevMinor)),\n+ Size: int64(statx.Size),\n+ Blksize: int64(statx.Blksize),\n+ Blocks: int64(statx.Blocks),\n+ ATime: timespecFromStatxTimestamp(statx.Atime),\n+ MTime: timespecFromStatxTimestamp(statx.Mtime),\n+ CTime: timespecFromStatxTimestamp(statx.Ctime),\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/vfs2/stat_arm64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package vfs2\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+)\n+\n+// This takes both input and output as pointer arguments to avoid copying large\n+// structs.\n+func convertStatxToUserStat(t *kernel.Task, statx *linux.Statx, stat *linux.Stat) {\n+ // Linux just copies fields from struct kstat without regard to struct\n+ // kstat::result_mask (fs/stat.c:cp_new_stat()), so we do too.\n+ userns := t.UserNamespace()\n+ *stat = linux.Stat{\n+ Dev: uint64(linux.MakeDeviceID(uint16(statx.DevMajor), statx.DevMinor)),\n+ Ino: statx.Ino,\n+ Nlink: uint32(statx.Nlink),\n+ Mode: uint32(statx.Mode),\n+ UID: uint32(auth.KUID(statx.UID).In(userns).OrOverflow()),\n+ GID: uint32(auth.KGID(statx.GID).In(userns).OrOverflow()),\n+ Rdev: uint64(linux.MakeDeviceID(uint16(statx.RdevMajor), statx.RdevMinor)),\n+ Size: int64(statx.Size),\n+ Blksize: int32(statx.Blksize),\n+ Blocks: int64(statx.Blocks),\n+ ATime: timespecFromStatxTimestamp(statx.Atime),\n+ MTime: timespecFromStatxTimestamp(statx.Mtime),\n+ CTime: timespecFromStatxTimestamp(statx.Ctime),\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix construct of linux.Stat for arm64. PiperOrigin-RevId: 297494373
259,858
27.02.2020 10:21:33
28,800
8e2b14fecf204b35fe258816792bdc03a1ca0912
Use automated release notes, if available.
[ { "change_type": "MODIFY", "old_path": "scripts/release.sh", "new_path": "scripts/release.sh", "diff": "@@ -25,6 +25,14 @@ if ! [[ -v KOKORO_RELEASE_TAG ]]; then\necho \"No KOKORO_RELEASE_TAG provided.\" >&2\nexit 1\nfi\n+if ! [[ -v KOKORO_RELNOTES ]]; then\n+ echo \"No KOKORO_RELNOTES provided.\" >&2\n+ exit 1\n+fi\n+if ! [[ -r \"${KOKORO_ARTIFACTS_DIR}/${KOKORO_RELNOTES}\" ]]; then\n+ echo \"The file '${KOKORO_ARTIFACTS_DIR}/${KOKORO_RELNOTES}' is not readable.\" >&2\n+ exit 1\n+fi\n# Unless an explicit releaser is provided, use the bot e-mail.\ndeclare -r KOKORO_RELEASE_AUTHOR=${KOKORO_RELEASE_AUTHOR:-gvisor-bot}\n@@ -46,4 +54,7 @@ EOF\nfi\n# Run the release tool, which pushes to the origin repository.\n-tools/tag_release.sh \"${KOKORO_RELEASE_COMMIT}\" \"${KOKORO_RELEASE_TAG}\"\n+tools/tag_release.sh \\\n+ \"${KOKORO_RELEASE_COMMIT}\" \\\n+ \"${KOKORO_RELEASE_TAG}\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/${KOKORO_RELNOTES}\"\n" }, { "change_type": "MODIFY", "old_path": "tools/tag_release.sh", "new_path": "tools/tag_release.sh", "diff": "set -xeu\n# Check arguments.\n-if [ \"$#\" -ne 2 ]; then\n- echo \"usage: $0 <commit|revid> <release.rc>\"\n+if [ \"$#\" -ne 3 ]; then\n+ echo \"usage: $0 <commit|revid> <release.rc> <message-file>\"\nexit 1\nfi\ndeclare -r target_commit=\"$1\"\ndeclare -r release=\"$2\"\n+declare -r message_file=\"$3\"\n+\n+if ! [[ -r \"${message_file}\" ]]; then\n+ echo \"error: message file '${message_file}' is not readable.\"\n+ exit 1\n+fi\nclosest_commit() {\nwhile read line; do\n@@ -64,6 +70,6 @@ fi\n# Tag the given commit (annotated, to record the committer).\ndeclare -r tag=\"release-${release}\"\n-(git tag -m \"Release ${release}\" -a \"${tag}\" \"${commit}\" && \\\n+(git tag -F \"${message_file}\" -a \"${tag}\" \"${commit}\" && \\\ngit push origin tag \"${tag}\") || \\\n(git tag -d \"${tag}\" && false)\n" } ]
Go
Apache License 2.0
google/gvisor
Use automated release notes, if available. PiperOrigin-RevId: 297628615
259,992
27.02.2020 14:58:16
28,800
88f73699225bd50102bbacb6f78052338f205cdd
Log oom_score_adj value on error Updates
[ { "change_type": "MODIFY", "old_path": "runsc/container/container.go", "new_path": "runsc/container/container.go", "diff": "@@ -17,6 +17,7 @@ package container\nimport (\n\"context\"\n+ \"errors\"\n\"fmt\"\n\"io/ioutil\"\n\"os\"\n@@ -1066,19 +1067,11 @@ func runInCgroup(cg *cgroup.Cgroup, fn func() error) error {\n// adjustGoferOOMScoreAdj sets the oom_store_adj for the container's gofer.\nfunc (c *Container) adjustGoferOOMScoreAdj() error {\n- if c.GoferPid != 0 && c.Spec.Process.OOMScoreAdj != nil {\n- if err := setOOMScoreAdj(c.GoferPid, *c.Spec.Process.OOMScoreAdj); err != nil {\n- // Ignore NotExist error because it can be returned when the sandbox\n- // exited while OOM score was being adjusted.\n- if !os.IsNotExist(err) {\n- return fmt.Errorf(\"setting gofer oom_score_adj for container %q: %v\", c.ID, err)\n- }\n- log.Warningf(\"Gofer process (%d) not found setting oom_score_adj\", c.GoferPid)\n- }\n- }\n-\n+ if c.GoferPid == 0 || c.Spec.Process.OOMScoreAdj == nil {\nreturn nil\n}\n+ return setOOMScoreAdj(c.GoferPid, *c.Spec.Process.OOMScoreAdj)\n+}\n// adjustSandboxOOMScoreAdj sets the oom_score_adj for the sandbox.\n// oom_score_adj is set to the lowest oom_score_adj among the containers\n@@ -1154,29 +1147,29 @@ func adjustSandboxOOMScoreAdj(s *sandbox.Sandbox, rootDir string, destroy bool)\n}\n// Set the lowest of all containers oom_score_adj to the sandbox.\n- if err := setOOMScoreAdj(s.Pid, lowScore); err != nil {\n- // Ignore NotExist error because it can be returned when the sandbox\n- // exited while OOM score was being adjusted.\n- if !os.IsNotExist(err) {\n- return fmt.Errorf(\"setting oom_score_adj for sandbox %q: %v\", s.ID, err)\n- }\n- log.Warningf(\"Sandbox process (%d) not found setting oom_score_adj\", s.Pid)\n- }\n-\n- return nil\n+ return setOOMScoreAdj(s.Pid, lowScore)\n}\n// setOOMScoreAdj sets oom_score_adj to the given value for the given PID.\n// /proc must be available and mounted read-write. scoreAdj should be between\n-// -1000 and 1000.\n+// -1000 and 1000. It's a noop if the process has already exited.\nfunc setOOMScoreAdj(pid int, scoreAdj int) error {\nf, err := os.OpenFile(fmt.Sprintf(\"/proc/%d/oom_score_adj\", pid), os.O_WRONLY, 0644)\nif err != nil {\n+ // Ignore NotExist errors because it can race with process exit.\n+ if os.IsNotExist(err) {\n+ log.Warningf(\"Process (%d) not found setting oom_score_adj\", pid)\n+ return nil\n+ }\nreturn err\n}\ndefer f.Close()\nif _, err := f.WriteString(strconv.Itoa(scoreAdj)); err != nil {\n- return err\n+ if errors.Is(err, syscall.ESRCH) {\n+ log.Warningf(\"Process (%d) exited while setting oom_score_adj\", pid)\n+ return nil\n+ }\n+ return fmt.Errorf(\"setting oom_score_adj to %q: %v\", scoreAdj, err)\n}\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Log oom_score_adj value on error Updates #1873 PiperOrigin-RevId: 297695241
259,896
28.02.2020 10:00:38
28,800
af6fab651406c411ef848c360b017713de385880
Add nat table support for iptables. Fix review comments.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -670,15 +670,21 @@ func parseTarget(filter iptables.IPHeaderFilter, optVal []byte) (iptables.Target\n// TODO(gvisor.dev/issue/170): Check if the flags are valid.\n// Also check if we need to map ports or IP.\n- // For now, redirect target only supports dest port change.\n+ // For now, redirect target only supports destination port change.\n+ // Port range and IP range are not supported yet.\nif nfRange.RangeIPV4.Flags&linux.NF_NAT_RANGE_PROTO_SPECIFIED == 0 {\nreturn nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument.\")\n}\n- target.Flags = nfRange.RangeIPV4.Flags\n+ target.RangeProtoSpecified = true\ntarget.MinIP = tcpip.Address(nfRange.RangeIPV4.MinIP[:])\ntarget.MaxIP = tcpip.Address(nfRange.RangeIPV4.MaxIP[:])\n+ // TODO(gvisor.dev/issue/170): Port range is not supported yet.\n+ if nfRange.RangeIPV4.MinPort != nfRange.RangeIPV4.MaxPort {\n+ return nil, fmt.Errorf(\"netfilter.SetEntries: invalid argument.\")\n+ }\n+\n// Convert port from big endian to little endian.\nport := make([]byte, 2)\nbinary.BigEndian.PutUint16(port, nfRange.RangeIPV4.MinPort)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "@@ -69,8 +69,11 @@ func (ReturnTarget) Action(tcpip.PacketBuffer) (RuleVerdict, int) {\n// Min and Max values for IP and Ports in the struct indicate the range of\n// values which can be used to redirect.\ntype RedirectTarget struct {\n- // Flags to check if the redirect is for address or ports.\n- Flags uint32\n+ // TODO(gvisor.dev/issue/170): Other flags need to be aded after\n+ // we support them.\n+ // RangeProtoSpecified flag indicates single port is specified to\n+ // redirect.\n+ RangeProtoSpecified bool\n// Min address used to redirect.\nMinIP tcpip.Address\n@@ -86,30 +89,56 @@ type RedirectTarget struct {\n}\n// Action implements Target.Action.\n+// TODO(gvisor.dev/issue/170): Parse headers without copying. The current\n+// implementation only works for PREROUTING and calls pkt.Clone(), neither\n+// of which should be the case.\nfunc (rt RedirectTarget) Action(pkt tcpip.PacketBuffer) (RuleVerdict, int) {\n- headerView := pkt.Data.First()\n+ newPkt := pkt.Clone()\n- // Network header should be set.\n+ // Set network header.\n+ headerView := newPkt.Data.First()\nnetHeader := header.IPv4(headerView)\n- if netHeader == nil {\n- return RuleDrop, 0\n- }\n+ newPkt.NetworkHeader = headerView[:netHeader.HeaderLength()]\n- // TODO(gvisor.dev/issue/170): Check Flags in RedirectTarget if\n- // we need to change dest address (for OUTPUT chain) or ports.\nhlen := int(netHeader.HeaderLength())\n+ tlen := int(netHeader.TotalLength())\n+ newPkt.Data.TrimFront(hlen)\n+ newPkt.Data.CapLength(tlen - hlen)\n+ // TODO(gvisor.dev/issue/170): Change destination address to\n+ // loopback or interface address on which the packet was\n+ // received.\n+\n+ // TODO(gvisor.dev/issue/170): Check Flags in RedirectTarget if\n+ // we need to change dest address (for OUTPUT chain) or ports.\nswitch protocol := netHeader.TransportProtocol(); protocol {\ncase header.UDPProtocolNumber:\n- udp := header.UDP(headerView[hlen:])\n- udp.SetDestinationPort(rt.MinPort)\n+ var udpHeader header.UDP\n+ if newPkt.TransportHeader != nil {\n+ udpHeader = header.UDP(newPkt.TransportHeader)\n+ } else {\n+ if len(pkt.Data.First()) < header.UDPMinimumSize {\n+ return RuleDrop, 0\n+ }\n+ udpHeader = header.UDP(newPkt.Data.First())\n+ }\n+ udpHeader.SetDestinationPort(rt.MinPort)\ncase header.TCPProtocolNumber:\n+ var tcpHeader header.TCP\n+ if newPkt.TransportHeader != nil {\n+ tcpHeader = header.TCP(newPkt.TransportHeader)\n+ } else {\n+ if len(pkt.Data.First()) < header.TCPMinimumSize {\n+ return RuleDrop, 0\n+ }\n+ tcpHeader = header.TCP(newPkt.TransportHeader)\n+ }\n// TODO(gvisor.dev/issue/170): Need to recompute checksum\n// and implement nat connection tracking to support TCP.\n- tcp := header.TCP(headerView[hlen:])\n- tcp.SetDestinationPort(rt.MinPort)\n+ tcpHeader.SetDestinationPort(rt.MinPort)\ndefault:\nreturn RuleDrop, 0\n}\n+\nreturn RuleAccept, 0\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -163,6 +163,6 @@ type Matcher interface {\ntype Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n- // Jump, it also returns the name of the chain to jump to.\n+ // Jump, it also returns the index of the rule to jump to.\nAction(packet tcpip.PacketBuffer) (RuleVerdict, int)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add nat table support for iptables. - Fix review comments.
259,992
28.02.2020 10:13:59
28,800
0f8a9e362337ee684042331c5bf24a3cb43d6fc4
Change dup2 call to dup3 We changed syscalls to allow dup3 for ARM64. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/gofer/gofer.go", "new_path": "pkg/sentry/fsimpl/gofer/gofer.go", "diff": "@@ -1045,13 +1045,13 @@ func (d *dentry) ensureSharedHandle(ctx context.Context, read, write, trunc bool\n// using the old file descriptor, preventing us from safely\n// closing it. We could handle this by invalidating existing\n// memmap.Translations, but this is expensive. Instead, use\n- // dup2() to make the old file descriptor refer to the new file\n+ // dup3 to make the old file descriptor refer to the new file\n// description, then close the new file descriptor (which is no\n// longer needed). Racing callers may use the old or new file\n// description, but this doesn't matter since they refer to the\n// same file (unless d.fs.opts.overlayfsStaleRead is true,\n// which we handle separately).\n- if err := syscall.Dup2(int(h.fd), int(d.handle.fd)); err != nil {\n+ if err := syscall.Dup3(int(h.fd), int(d.handle.fd), 0); err != nil {\nd.handleMu.Unlock()\nctx.Warningf(\"gofer.dentry.ensureSharedHandle: failed to dup fd %d to fd %d: %v\", h.fd, d.handle.fd, err)\nh.close(ctx)\n" } ]
Go
Apache License 2.0
google/gvisor
Change dup2 call to dup3 We changed syscalls to allow dup3 for ARM64. Updates #1198 PiperOrigin-RevId: 297870816