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,858 | 23.04.2020 13:00:34 | 25,200 | 2e8c35b506654172243ea46918d27c897fca568c | Add basic GitHub labeler workflow.
This is the first automated GitHub actions workflow, and it simply applies
labels to pull request in a best-effort fashion. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/labeler.yml",
"diff": "+\"arch: arm\":\n+ - \"**/*_arm64.*\"\n+ - \"**/*_aarch64.*\"\n+\"arch: x86_64\":\n+ - \"**/*_amd64.*\"\n+ - \"**/*_x86.*\"\n+\"area: bazel\":\n+ - \"**/BUILD\"\n+ - \"**/*.bzl\"\n+\"area: docs\":\n+ - \"**/g3doc/**\"\n+ - \"**/README.md\"\n+\"area: filesystem\":\n+ - \"pkg/sentry/fs/**\"\n+ - \"pkg/sentry/vfs/**\"\n+ - \"pkg/sentry/fsimpl/**\"\n+\"area: hostinet\":\n+ - \"pkg/sentry/socket/hostinet/**\"\n+\"area: networking\":\n+ - \"pkg/tcpip/**\"\n+ - \"pkg/sentry/socket/**\"\n+\"area: kernel\":\n+ - \"pkg/sentry/arch/**\"\n+ - \"pkg/sentry/kernel/**\"\n+ - \"pkg/sentry/syscalls/**\"\n+\"area: mm\":\n+ - \"pkg/sentry/mm/**\"\n+\"area: tests\":\n+ - \"**/tests/**\"\n+ - \"**/*_test.go\"\n+ - \"**/test/**\"\n+\"area: tooling\":\n+ - \"tools/**\"\n+\"dependencies\":\n+ - \"WORKSPACE\"\n+ - \"go.mod\"\n+ - \"go.sum\"\n+\"platform: kvm\":\n+ - \"pkg/sentry/platform/kvm/**\"\n+ - \"pkg/sentry/platform/ring0/**\"\n+\"platform: ptrace\":\n+ - \"pkg/sentry/platform/ptrace/**\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/labeler.yml",
"diff": "+name: \"Labeler\"\n+on:\n+- pull_request\n+\n+jobs:\n+ label:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/labeler@v2\n+ with:\n+ repo-token: \"${{ secrets.GITHUB_TOKEN }}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add basic GitHub labeler workflow.
This is the first automated GitHub actions workflow, and it simply applies
labels to pull request in a best-effort fashion.
PiperOrigin-RevId: 308112191 |
259,972 | 23.04.2020 13:11:23 | 25,200 | cc5de905e628c5e9aca7e7a333d6dd9638719b6a | Fix test output so that filenames have the correct path.
Tested:
Intentionally introduce an error and then run:
blaze test --test_output=streamed //third_party/gvisor/test/packetimpact/tests:tcp_outside_the_window_linux_test | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/test_runner.sh",
"new_path": "test/packetimpact/tests/test_runner.sh",
"diff": "@@ -262,7 +262,10 @@ sleep 3\n# Start a packetimpact test on the test bench. The packetimpact test sends and\n# receives packets and also sends POSIX socket commands to the posix_server to\n# be executed on the DUT.\n-docker exec -t \"${TESTBENCH}\" \\\n+docker exec \\\n+ -e XML_OUTPUT_FILE=\"/test.xml\" \\\n+ -e TEST_TARGET \\\n+ -t \"${TESTBENCH}\" \\\n/bin/bash -c \"${DOCKER_TESTBENCH_BINARY} \\\n${EXTRA_TEST_ARGS[@]-} \\\n--posix_server_ip=${CTRL_NET_PREFIX}${DUT_NET_SUFFIX} \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix test output so that filenames have the correct path.
Tested:
Intentionally introduce an error and then run:
blaze test --test_output=streamed //third_party/gvisor/test/packetimpact/tests:tcp_outside_the_window_linux_test
PiperOrigin-RevId: 308114194 |
259,985 | 23.04.2020 15:47:59 | 25,200 | 93dd47146185ec7004f514e23bad9f225f55efb1 | Enable automated marshalling for epoll events.
Ensure we use the correct architecture-specific defintion of epoll
event, and use go-marshal for serialization. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/epoll_amd64.go",
"new_path": "pkg/abi/linux/epoll_amd64.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+// +build amd64\n+\npackage linux\n// EpollEvent is equivalent to struct epoll_event from epoll(2).\n//\n-// +marshal\n+// +marshal slice:EpollEventSlice\ntype EpollEvent struct {\nEvents uint32\n// Linux makes struct epoll_event::data a __u64. We represent it as\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/epoll_arm64.go",
"new_path": "pkg/abi/linux/epoll_arm64.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+// +build arm64\n+\npackage linux\n// EpollEvent is equivalent to struct epoll_event from epoll(2).\n//\n-// +marshal\n+// +marshal slice:EpollEventSlice\ntype EpollEvent struct {\nEvents uint32\n// Linux makes struct epoll_event a __u64, necessitating 4 bytes of padding\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/epoll/BUILD",
"new_path": "pkg/sentry/kernel/epoll/BUILD",
"diff": "@@ -24,6 +24,7 @@ go_library(\n],\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/refs\",\n\"//pkg/sentry/fs\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/epoll/epoll.go",
"new_path": "pkg/sentry/kernel/epoll/epoll.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"fmt\"\n\"syscall\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n@@ -30,19 +31,6 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// Event describes the event mask that was observed and the user data to be\n-// returned when one of the events occurs. It has this format to match the linux\n-// format to avoid extra copying/allocation when writing events to userspace.\n-type Event struct {\n- // Events is the event mask containing the set of events that have been\n- // observed on an entry.\n- Events uint32\n-\n- // Data is an opaque 64-bit value provided by the caller when adding the\n- // entry, and returned to the caller when the entry reports an event.\n- Data [2]int32\n-}\n-\n// EntryFlags is a bitmask that holds an entry's flags.\ntype EntryFlags int\n@@ -227,9 +215,9 @@ func (e *EventPoll) Readiness(mask waiter.EventMask) waiter.EventMask {\n}\n// ReadEvents returns up to max available events.\n-func (e *EventPoll) ReadEvents(max int) []Event {\n+func (e *EventPoll) ReadEvents(max int) []linux.EpollEvent {\nvar local pollEntryList\n- var ret []Event\n+ var ret []linux.EpollEvent\ne.listsMu.Lock()\n@@ -251,7 +239,7 @@ func (e *EventPoll) ReadEvents(max int) []Event {\n}\n// Add event to the array that will be returned to caller.\n- ret = append(ret, Event{\n+ ret = append(ret, linux.EpollEvent{\nEvents: uint32(ready),\nData: entry.userData,\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/epoll.go",
"new_path": "pkg/sentry/syscalls/epoll.go",
"diff": "@@ -17,6 +17,7 @@ package syscalls\nimport (\n\"time\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/epoll\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n@@ -118,7 +119,7 @@ func RemoveEpoll(t *kernel.Task, epfd int32, fd int32) error {\n}\n// WaitEpoll implements the epoll_wait(2) linux syscall.\n-func WaitEpoll(t *kernel.Task, fd int32, max int, timeout int) ([]epoll.Event, error) {\n+func WaitEpoll(t *kernel.Task, fd int32, max int, timeout int) ([]linux.EpollEvent, error) {\n// Get epoll from the file descriptor.\nepollfile := t.GetFile(fd)\nif epollfile == nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"new_path": "pkg/sentry/syscalls/linux/sys_epoll.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/epoll\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n- \"gvisor.dev/gvisor/pkg/usermem\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -72,7 +71,7 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nvar data [2]int32\nif op != linux.EPOLL_CTL_DEL {\nvar e linux.EpollEvent\n- if _, err := t.CopyIn(eventAddr, &e); err != nil {\n+ if _, err := e.CopyIn(t, eventAddr); err != nil {\nreturn 0, nil, err\n}\n@@ -105,28 +104,6 @@ func EpollCtl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n}\n-// copyOutEvents copies epoll events from the kernel to user memory.\n-func copyOutEvents(t *kernel.Task, addr usermem.Addr, e []epoll.Event) error {\n- const itemLen = 12\n- buffLen := len(e) * itemLen\n- if _, ok := addr.AddLength(uint64(buffLen)); !ok {\n- return syserror.EFAULT\n- }\n-\n- b := t.CopyScratchBuffer(buffLen)\n- for i := range e {\n- usermem.ByteOrder.PutUint32(b[i*itemLen:], e[i].Events)\n- usermem.ByteOrder.PutUint32(b[i*itemLen+4:], uint32(e[i].Data[0]))\n- usermem.ByteOrder.PutUint32(b[i*itemLen+8:], uint32(e[i].Data[1]))\n- }\n-\n- if _, err := t.CopyOutBytes(addr, b); err != nil {\n- return err\n- }\n-\n- return nil\n-}\n-\n// EpollWait implements the epoll_wait(2) linux syscall.\nfunc EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nepfd := args[0].Int()\n@@ -140,7 +117,7 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\n}\nif len(r) != 0 {\n- if err := copyOutEvents(t, eventsAddr, r); err != nil {\n+ if _, err := linux.CopyEpollEventSliceOut(t, eventsAddr, r); err != nil {\nreturn 0, nil, err\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/BUILD",
"new_path": "pkg/sentry/syscalls/linux/vfs2/BUILD",
"diff": "@@ -6,7 +6,6 @@ go_library(\nname = \"vfs2\",\nsrcs = [\n\"epoll.go\",\n- \"epoll_unsafe.go\",\n\"execve.go\",\n\"fd.go\",\n\"filesystem.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/epoll.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/epoll.go",
"diff": "@@ -28,6 +28,8 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+var sizeofEpollEvent = (*linux.EpollEvent)(nil).SizeBytes()\n+\n// EpollCreate1 implements Linux syscall epoll_create1(2).\nfunc EpollCreate1(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nflags := args[0].Int()\n@@ -124,7 +126,7 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\nmaxEvents := int(args[2].Int())\ntimeout := int(args[3].Int())\n- const _EP_MAX_EVENTS = math.MaxInt32 / sizeofEpollEvent // Linux: fs/eventpoll.c:EP_MAX_EVENTS\n+ var _EP_MAX_EVENTS = math.MaxInt32 / sizeofEpollEvent // Linux: fs/eventpoll.c:EP_MAX_EVENTS\nif maxEvents <= 0 || maxEvents > _EP_MAX_EVENTS {\nreturn 0, nil, syserror.EINVAL\n}\n@@ -157,7 +159,8 @@ func EpollWait(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\nmaxEvents -= n\nif n != 0 {\n// Copy what we read out.\n- copiedEvents, err := copyOutEvents(t, eventsAddr, events[:n])\n+ copiedBytes, err := linux.CopyEpollEventSliceOut(t, eventsAddr, events[:n])\n+ copiedEvents := copiedBytes / sizeofEpollEvent // rounded down\neventsAddr += usermem.Addr(copiedEvents * sizeofEpollEvent)\ntotal += copiedEvents\nif err != nil {\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/syscalls/linux/vfs2/epoll_unsafe.go",
"new_path": null,
"diff": "-// Copyright 2020 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package vfs2\n-\n-import (\n- \"reflect\"\n- \"runtime\"\n- \"unsafe\"\n-\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/gohacks\"\n- \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n- \"gvisor.dev/gvisor/pkg/usermem\"\n-)\n-\n-const sizeofEpollEvent = int(unsafe.Sizeof(linux.EpollEvent{}))\n-\n-func copyOutEvents(t *kernel.Task, addr usermem.Addr, events []linux.EpollEvent) (int, error) {\n- if len(events) == 0 {\n- return 0, nil\n- }\n- // Cast events to a byte slice for copying.\n- var eventBytes []byte\n- eventBytesHdr := (*reflect.SliceHeader)(unsafe.Pointer(&eventBytes))\n- eventBytesHdr.Data = uintptr(gohacks.Noescape(unsafe.Pointer(&events[0])))\n- eventBytesHdr.Len = len(events) * sizeofEpollEvent\n- eventBytesHdr.Cap = len(events) * sizeofEpollEvent\n- copiedBytes, err := t.CopyOutBytes(addr, eventBytes)\n- runtime.KeepAlive(events)\n- copiedEvents := copiedBytes / sizeofEpollEvent // rounded down\n- return copiedEvents, err\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable automated marshalling for epoll events.
Ensure we use the correct architecture-specific defintion of epoll
event, and use go-marshal for serialization.
PiperOrigin-RevId: 308145677 |
259,985 | 23.04.2020 18:18:54 | 25,200 | f01f2132d8d3e551579cba9a1b942b4b70d83f21 | Enable automated marshalling for mempolicy syscalls. | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/mm.go",
"new_path": "pkg/abi/linux/mm.go",
"diff": "@@ -90,14 +90,19 @@ const (\nMS_SYNC = 1 << 2\n)\n+// NumaPolicy is the NUMA memory policy for a memory range. See numa(7).\n+//\n+// +marshal\n+type NumaPolicy int32\n+\n// Policies for get_mempolicy(2)/set_mempolicy(2).\nconst (\n- MPOL_DEFAULT = 0\n- MPOL_PREFERRED = 1\n- MPOL_BIND = 2\n- MPOL_INTERLEAVE = 3\n- MPOL_LOCAL = 4\n- MPOL_MAX = 5\n+ MPOL_DEFAULT NumaPolicy = 0\n+ MPOL_PREFERRED NumaPolicy = 1\n+ MPOL_BIND NumaPolicy = 2\n+ MPOL_INTERLEAVE NumaPolicy = 3\n+ MPOL_LOCAL NumaPolicy = 4\n+ MPOL_MAX NumaPolicy = 5\n)\n// Flags for get_mempolicy(2).\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "@@ -484,7 +484,7 @@ type Task struct {\n// bit.\n//\n// numaPolicy and numaNodeMask are protected by mu.\n- numaPolicy int32\n+ numaPolicy linux.NumaPolicy\nnumaNodeMask uint64\n// netns is the task's network namespace. netns is never nil.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_sched.go",
"new_path": "pkg/sentry/kernel/task_sched.go",
"diff": "@@ -653,14 +653,14 @@ func (t *Task) SetNiceness(n int) {\n}\n// NumaPolicy returns t's current numa policy.\n-func (t *Task) NumaPolicy() (policy int32, nodeMask uint64) {\n+func (t *Task) NumaPolicy() (policy linux.NumaPolicy, nodeMask uint64) {\nt.mu.Lock()\ndefer t.mu.Unlock()\nreturn t.numaPolicy, t.numaNodeMask\n}\n// SetNumaPolicy sets t's numa policy.\n-func (t *Task) SetNumaPolicy(policy int32, nodeMask uint64) {\n+func (t *Task) SetNumaPolicy(policy linux.NumaPolicy, nodeMask uint64) {\nt.mu.Lock()\ndefer t.mu.Unlock()\nt.numaPolicy = policy\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/mm.go",
"new_path": "pkg/sentry/mm/mm.go",
"diff": "package mm\nimport (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fsbridge\"\n@@ -286,7 +287,7 @@ type vma struct {\nmlockMode memmap.MLockMode\n// numaPolicy is the NUMA policy for this vma set by mbind().\n- numaPolicy int32\n+ numaPolicy linux.NumaPolicy\n// numaNodemask is the NUMA nodemask for this vma set by mbind().\nnumaNodemask uint64\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/syscalls.go",
"new_path": "pkg/sentry/mm/syscalls.go",
"diff": "@@ -974,7 +974,7 @@ func (mm *MemoryManager) MLockAll(ctx context.Context, opts MLockAllOpts) error\n}\n// NumaPolicy implements the semantics of Linux's get_mempolicy(MPOL_F_ADDR).\n-func (mm *MemoryManager) NumaPolicy(addr usermem.Addr) (int32, uint64, error) {\n+func (mm *MemoryManager) NumaPolicy(addr usermem.Addr) (linux.NumaPolicy, uint64, error) {\nmm.mappingMu.RLock()\ndefer mm.mappingMu.RUnlock()\nvseg := mm.vmas.FindSegment(addr)\n@@ -986,7 +986,7 @@ func (mm *MemoryManager) NumaPolicy(addr usermem.Addr) (int32, uint64, error) {\n}\n// SetNumaPolicy implements the semantics of Linux's mbind().\n-func (mm *MemoryManager) SetNumaPolicy(addr usermem.Addr, length uint64, policy int32, nodemask uint64) error {\n+func (mm *MemoryManager) SetNumaPolicy(addr usermem.Addr, length uint64, policy linux.NumaPolicy, nodemask uint64) error {\nif !addr.IsPageAligned() {\nreturn syserror.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_mempolicy.go",
"new_path": "pkg/sentry/syscalls/linux/sys_mempolicy.go",
"diff": "@@ -162,10 +162,10 @@ func GetMempolicy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.\nif err != nil {\nreturn 0, nil, err\n}\n- policy = 0 // maxNodes == 1\n+ policy = linux.MPOL_DEFAULT // maxNodes == 1\n}\nif mode != 0 {\n- if _, err := t.CopyOut(mode, policy); err != nil {\n+ if _, err := policy.CopyOut(t, mode); err != nil {\nreturn 0, nil, err\n}\n}\n@@ -199,10 +199,10 @@ func GetMempolicy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.\nif policy&^linux.MPOL_MODE_FLAGS != linux.MPOL_INTERLEAVE {\nreturn 0, nil, syserror.EINVAL\n}\n- policy = 0 // maxNodes == 1\n+ policy = linux.MPOL_DEFAULT // maxNodes == 1\n}\nif mode != 0 {\n- if _, err := t.CopyOut(mode, policy); err != nil {\n+ if _, err := policy.CopyOut(t, mode); err != nil {\nreturn 0, nil, err\n}\n}\n@@ -216,7 +216,7 @@ func GetMempolicy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.\n// SetMempolicy implements the syscall set_mempolicy(2).\nfunc SetMempolicy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- modeWithFlags := args[0].Int()\n+ modeWithFlags := linux.NumaPolicy(args[0].Int())\nnodemask := args[1].Pointer()\nmaxnode := args[2].Uint()\n@@ -233,7 +233,7 @@ func SetMempolicy(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.\nfunc Mbind(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\naddr := args[0].Pointer()\nlength := args[1].Uint64()\n- mode := args[2].Int()\n+ mode := linux.NumaPolicy(args[2].Int())\nnodemask := args[3].Pointer()\nmaxnode := args[4].Uint()\nflags := args[5].Uint()\n@@ -258,9 +258,9 @@ func Mbind(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nreturn 0, nil, err\n}\n-func copyInMempolicyNodemask(t *kernel.Task, modeWithFlags int32, nodemask usermem.Addr, maxnode uint32) (int32, uint64, error) {\n- flags := modeWithFlags & linux.MPOL_MODE_FLAGS\n- mode := modeWithFlags &^ linux.MPOL_MODE_FLAGS\n+func copyInMempolicyNodemask(t *kernel.Task, modeWithFlags linux.NumaPolicy, nodemask usermem.Addr, maxnode uint32) (linux.NumaPolicy, uint64, error) {\n+ flags := linux.NumaPolicy(modeWithFlags & linux.MPOL_MODE_FLAGS)\n+ mode := linux.NumaPolicy(modeWithFlags &^ linux.MPOL_MODE_FLAGS)\nif flags == linux.MPOL_MODE_FLAGS {\n// Can't specify both mode flags simultaneously.\nreturn 0, 0, syserror.EINVAL\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable automated marshalling for mempolicy syscalls.
PiperOrigin-RevId: 308170679 |
259,972 | 23.04.2020 18:20:43 | 25,200 | 79542417fe97a62ee86aa211ac559bcc5cac5e5e | Fix Layer merge and add unit tests
mergo was improperly merging nil and empty strings | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -188,13 +188,6 @@ go_repository(\nversion = \"v0.0.0-20171129191014-dec09d789f3d\",\n)\n-go_repository(\n- name = \"com_github_imdario_mergo\",\n- importpath = \"github.com/imdario/mergo\",\n- sum = \"h1:CGgOkSJeqMRmt0D9XLWExdT4m4F1vd3FV3VPt+0VxkQ=\",\n- version = \"v0.3.8\",\n-)\n-\ngo_repository(\nname = \"com_github_kr_pretty\",\nimportpath = \"github.com/kr/pretty\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/BUILD",
"new_path": "test/packetimpact/testbench/BUILD",
"diff": "@@ -23,7 +23,6 @@ go_library(\n\"//test/packetimpact/proto:posix_server_go_proto\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n\"@com_github_google_go-cmp//cmp/cmpopts:go_default_library\",\n- \"@com_github_imdario_mergo//:go_default_library\",\n\"@com_github_mohae_deepcopy//:go_default_library\",\n\"@org_golang_google_grpc//:go_default_library\",\n\"@org_golang_google_grpc//keepalive:go_default_library\",\n@@ -37,5 +36,8 @@ go_test(\nsize = \"small\",\nsrcs = [\"layers_test.go\"],\nlibrary = \":testbench\",\n- deps = [\"//pkg/tcpip\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"@com_github_mohae_deepcopy//:go_default_library\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -22,7 +22,6 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"github.com/google/go-cmp/cmp/cmpopts\"\n- \"github.com/imdario/mergo\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -111,13 +110,31 @@ func equalLayer(x, y Layer) bool {\nreturn cmp.Equal(x, y, opt, cmpopts.IgnoreTypes(LayerBase{}))\n}\n-// mergeLayer merges other in layer. Any non-nil value in other overrides the\n-// corresponding value in layer. If other is nil, no action is performed.\n-func mergeLayer(layer, other Layer) error {\n- if other == nil {\n+// mergeLayer merges y into x. Any fields for which y has a non-nil value, that\n+// value overwrite the corresponding fields in x.\n+func mergeLayer(x, y Layer) error {\n+ if y == nil {\nreturn nil\n}\n- return mergo.Merge(layer, other, mergo.WithOverride)\n+ if reflect.TypeOf(x) != reflect.TypeOf(y) {\n+ return fmt.Errorf(\"can't merge %T into %T\", y, x)\n+ }\n+ vx := reflect.ValueOf(x).Elem()\n+ vy := reflect.ValueOf(y).Elem()\n+ t := vy.Type()\n+ for i := 0; i < vy.NumField(); i++ {\n+ t := t.Field(i)\n+ if t.Anonymous {\n+ // Ignore the LayerBase in the Layer struct.\n+ continue\n+ }\n+ v := vy.Field(i)\n+ if v.IsNil() {\n+ continue\n+ }\n+ vx.Field(i).Set(v)\n+ }\n+ return nil\n}\nfunc stringLayer(l Layer) string {\n@@ -243,8 +260,7 @@ func (l *Ether) length() int {\nreturn header.EthernetMinimumSize\n}\n-// merge overrides the values in l with the values from other but only in fields\n-// where the value is not nil.\n+// merge implements Layer.merge.\nfunc (l *Ether) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n@@ -399,8 +415,7 @@ func (l *IPv4) length() int {\nreturn int(*l.IHL)\n}\n-// merge overrides the values in l with the values from other but only in fields\n-// where the value is not nil.\n+// merge implements Layer.merge.\nfunc (l *IPv4) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n@@ -544,8 +559,7 @@ func (l *TCP) length() int {\nreturn int(*l.DataOffset)\n}\n-// merge overrides the values in l with the values from other but only in fields\n-// where the value is not nil.\n+// merge implements Layer.merge.\nfunc (l *TCP) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n@@ -622,8 +636,7 @@ func (l *UDP) length() int {\nreturn int(*l.Length)\n}\n-// merge overrides the values in l with the values from other but only in fields\n-// where the value is not nil.\n+// merge implements Layer.merge.\nfunc (l *UDP) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n@@ -659,8 +672,7 @@ func (l *Payload) length() int {\nreturn len(l.Bytes)\n}\n-// merge overrides the values in l with the values from other but only in fields\n-// where the value is not nil.\n+// merge implements Layer.merge.\nfunc (l *Payload) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers_test.go",
"new_path": "test/packetimpact/testbench/layers_test.go",
"diff": "@@ -17,6 +17,7 @@ package testbench\nimport (\n\"testing\"\n+ \"github.com/mohae/deepcopy\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n)\n@@ -52,6 +53,114 @@ func TestLayerMatch(t *testing.T) {\n}\n}\n+func TestLayerMergeMismatch(t *testing.T) {\n+ tcp := &TCP{}\n+ otherTCP := &TCP{}\n+ ipv4 := &IPv4{}\n+ ether := &Ether{}\n+ for _, tt := range []struct {\n+ a, b Layer\n+ success bool\n+ }{\n+ {tcp, tcp, true},\n+ {tcp, otherTCP, true},\n+ {tcp, ipv4, false},\n+ {tcp, ether, false},\n+ {tcp, nil, true},\n+\n+ {otherTCP, otherTCP, true},\n+ {otherTCP, ipv4, false},\n+ {otherTCP, ether, false},\n+ {otherTCP, nil, true},\n+\n+ {ipv4, ipv4, true},\n+ {ipv4, ether, false},\n+ {ipv4, nil, true},\n+\n+ {ether, ether, true},\n+ {ether, nil, true},\n+ } {\n+ if err := tt.a.merge(tt.b); (err == nil) != tt.success {\n+ t.Errorf(\"%s.merge(%s) got %s, wanted the opposite\", tt.a, tt.b, err)\n+ }\n+ if tt.b != nil {\n+ if err := tt.b.merge(tt.a); (err == nil) != tt.success {\n+ t.Errorf(\"%s.merge(%s) got %s, wanted the opposite\", tt.b, tt.a, err)\n+ }\n+ }\n+ }\n+}\n+\n+func TestLayerMerge(t *testing.T) {\n+ zero := Uint32(0)\n+ one := Uint32(1)\n+ two := Uint32(2)\n+ empty := []byte{}\n+ foo := []byte(\"foo\")\n+ bar := []byte(\"bar\")\n+ for _, tt := range []struct {\n+ a, b Layer\n+ want Layer\n+ }{\n+ {&TCP{AckNum: nil}, &TCP{AckNum: nil}, &TCP{AckNum: nil}},\n+ {&TCP{AckNum: nil}, &TCP{AckNum: zero}, &TCP{AckNum: zero}},\n+ {&TCP{AckNum: nil}, &TCP{AckNum: one}, &TCP{AckNum: one}},\n+ {&TCP{AckNum: nil}, &TCP{AckNum: two}, &TCP{AckNum: two}},\n+ {&TCP{AckNum: nil}, nil, &TCP{AckNum: nil}},\n+\n+ {&TCP{AckNum: zero}, &TCP{AckNum: nil}, &TCP{AckNum: zero}},\n+ {&TCP{AckNum: zero}, &TCP{AckNum: zero}, &TCP{AckNum: zero}},\n+ {&TCP{AckNum: zero}, &TCP{AckNum: one}, &TCP{AckNum: one}},\n+ {&TCP{AckNum: zero}, &TCP{AckNum: two}, &TCP{AckNum: two}},\n+ {&TCP{AckNum: zero}, nil, &TCP{AckNum: zero}},\n+\n+ {&TCP{AckNum: one}, &TCP{AckNum: nil}, &TCP{AckNum: one}},\n+ {&TCP{AckNum: one}, &TCP{AckNum: zero}, &TCP{AckNum: zero}},\n+ {&TCP{AckNum: one}, &TCP{AckNum: one}, &TCP{AckNum: one}},\n+ {&TCP{AckNum: one}, &TCP{AckNum: two}, &TCP{AckNum: two}},\n+ {&TCP{AckNum: one}, nil, &TCP{AckNum: one}},\n+\n+ {&TCP{AckNum: two}, &TCP{AckNum: nil}, &TCP{AckNum: two}},\n+ {&TCP{AckNum: two}, &TCP{AckNum: zero}, &TCP{AckNum: zero}},\n+ {&TCP{AckNum: two}, &TCP{AckNum: one}, &TCP{AckNum: one}},\n+ {&TCP{AckNum: two}, &TCP{AckNum: two}, &TCP{AckNum: two}},\n+ {&TCP{AckNum: two}, nil, &TCP{AckNum: two}},\n+\n+ {&Payload{Bytes: nil}, &Payload{Bytes: nil}, &Payload{Bytes: nil}},\n+ {&Payload{Bytes: nil}, &Payload{Bytes: empty}, &Payload{Bytes: empty}},\n+ {&Payload{Bytes: nil}, &Payload{Bytes: foo}, &Payload{Bytes: foo}},\n+ {&Payload{Bytes: nil}, &Payload{Bytes: bar}, &Payload{Bytes: bar}},\n+ {&Payload{Bytes: nil}, nil, &Payload{Bytes: nil}},\n+\n+ {&Payload{Bytes: empty}, &Payload{Bytes: nil}, &Payload{Bytes: empty}},\n+ {&Payload{Bytes: empty}, &Payload{Bytes: empty}, &Payload{Bytes: empty}},\n+ {&Payload{Bytes: empty}, &Payload{Bytes: foo}, &Payload{Bytes: foo}},\n+ {&Payload{Bytes: empty}, &Payload{Bytes: bar}, &Payload{Bytes: bar}},\n+ {&Payload{Bytes: empty}, nil, &Payload{Bytes: empty}},\n+\n+ {&Payload{Bytes: foo}, &Payload{Bytes: nil}, &Payload{Bytes: foo}},\n+ {&Payload{Bytes: foo}, &Payload{Bytes: empty}, &Payload{Bytes: empty}},\n+ {&Payload{Bytes: foo}, &Payload{Bytes: foo}, &Payload{Bytes: foo}},\n+ {&Payload{Bytes: foo}, &Payload{Bytes: bar}, &Payload{Bytes: bar}},\n+ {&Payload{Bytes: foo}, nil, &Payload{Bytes: foo}},\n+\n+ {&Payload{Bytes: bar}, &Payload{Bytes: nil}, &Payload{Bytes: bar}},\n+ {&Payload{Bytes: bar}, &Payload{Bytes: empty}, &Payload{Bytes: empty}},\n+ {&Payload{Bytes: bar}, &Payload{Bytes: foo}, &Payload{Bytes: foo}},\n+ {&Payload{Bytes: bar}, &Payload{Bytes: bar}, &Payload{Bytes: bar}},\n+ {&Payload{Bytes: bar}, nil, &Payload{Bytes: bar}},\n+ } {\n+ a := deepcopy.Copy(tt.a).(Layer)\n+ if err := a.merge(tt.b); err != nil {\n+ t.Errorf(\"%s.merge(%s) = %s, wanted nil\", tt.a, tt.b, err)\n+ continue\n+ }\n+ if a.String() != tt.want.String() {\n+ t.Errorf(\"%s.merge(%s) merge result got %s, want %s\", tt.a, tt.b, a, tt.want)\n+ }\n+ }\n+}\n+\nfunc TestLayerStringFormat(t *testing.T) {\nfor _, tt := range []struct {\nname string\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix Layer merge and add unit tests
mergo was improperly merging nil and empty strings
PiperOrigin-RevId: 308170862 |
259,860 | 24.04.2020 08:19:11 | 25,200 | 40a712c57cd78c51c9875ae04b5e795113c75e62 | Refactor syscall.Fstat calls in hostfs.
Just call syscall.Fstat directly each time mode/file owner are needed. This
feels more natural than using i.getPermissions(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -169,31 +169,22 @@ func fileFlagsFromHostFD(fd int) (int, error) {\n// CheckPermissions implements kernfs.Inode.\nfunc (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\n- mode, uid, gid, err := i.getPermissions()\n- if err != nil {\n+ var s syscall.Stat_t\n+ if err := syscall.Fstat(i.hostFD, &s); err != nil {\nreturn err\n}\n- return vfs.GenericCheckPermissions(creds, ats, mode, uid, gid)\n+ return vfs.GenericCheckPermissions(creds, ats, linux.FileMode(s.Mode), auth.KUID(s.Uid), auth.KGID(s.Gid))\n}\n// Mode implements kernfs.Inode.\nfunc (i *inode) Mode() linux.FileMode {\n- mode, _, _, err := i.getPermissions()\n+ var s syscall.Stat_t\n+ if err := syscall.Fstat(i.hostFD, &s); err != nil {\n// Retrieving the mode from the host fd using fstat(2) should not fail.\n// If the syscall does not succeed, something is fundamentally wrong.\n- if err != nil {\npanic(fmt.Sprintf(\"failed to retrieve mode from host fd %d: %v\", i.hostFD, err))\n}\n- return linux.FileMode(mode)\n-}\n-\n-func (i *inode) getPermissions() (linux.FileMode, auth.KUID, auth.KGID, error) {\n- // Retrieve metadata.\n- var s syscall.Stat_t\n- if err := syscall.Fstat(i.hostFD, &s); err != nil {\n- return 0, 0, 0, err\n- }\n- return linux.FileMode(s.Mode), auth.KUID(s.Uid), auth.KGID(s.Gid), nil\n+ return linux.FileMode(s.Mode)\n}\n// Stat implements kernfs.Inode.\n@@ -326,11 +317,11 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nif m&^(linux.STATX_MODE|linux.STATX_SIZE|linux.STATX_ATIME|linux.STATX_MTIME) != 0 {\nreturn syserror.EPERM\n}\n- mode, uid, gid, err := i.getPermissions()\n- if err != nil {\n+ var hostStat syscall.Stat_t\n+ if err := syscall.Fstat(i.hostFD, &hostStat); err != nil {\nreturn err\n}\n- if err := vfs.CheckSetStat(ctx, creds, &s, mode.Permissions(), uid, gid); err != nil {\n+ if err := vfs.CheckSetStat(ctx, creds, &s, linux.FileMode(hostStat.Mode&linux.PermissionsMask), auth.KUID(hostStat.Uid), auth.KGID(hostStat.Gid)); err != nil {\nreturn err\n}\n@@ -374,11 +365,11 @@ func (i *inode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptio\n}\nfunc (i *inode) open(d *vfs.Dentry, mnt *vfs.Mount) (*vfs.FileDescription, error) {\n- mode, _, _, err := i.getPermissions()\n- if err != nil {\n+ var s syscall.Stat_t\n+ if err := syscall.Fstat(i.hostFD, &s); err != nil {\nreturn nil, err\n}\n- fileType := mode.FileType()\n+ fileType := s.Mode & linux.FileTypeMask\nif fileType == syscall.S_IFSOCK {\nif i.isTTY {\nreturn nil, errors.New(\"cannot use host socket as TTY\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Refactor syscall.Fstat calls in hostfs.
Just call syscall.Fstat directly each time mode/file owner are needed. This
feels more natural than using i.getPermissions().
PiperOrigin-RevId: 308257405 |
259,992 | 24.04.2020 11:43:49 | 25,200 | 2cc0fd42f462f3942230c4b33ca2825e2a28765d | Fixes for procfs
Return ENOENT for /proc/[pid]/task if task is zoombied or terminated
Allow directory to be Seek() to the end
Construct synthetic files for /proc/[pid]/ns/*
Changed GenericDirectoryFD.Init to not register with FileDescription,
otherwise other implementation cannot change behavior.
Updates #1195,1193 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"new_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"diff": "@@ -161,8 +161,10 @@ func (i *rootInode) masterClose(t *Terminal) {\n// Open implements kernfs.Inode.Open.\nfunc (i *rootInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"diff": "package kernfs\nimport (\n+ \"math\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -43,15 +45,27 @@ type GenericDirectoryFD struct {\noff int64\n}\n-// Init initializes a GenericDirectoryFD.\n-func (fd *GenericDirectoryFD) Init(m *vfs.Mount, d *vfs.Dentry, children *OrderedChildren, opts *vfs.OpenOptions) error {\n+// NewGenericDirectoryFD creates a new GenericDirectoryFD and returns its\n+// dentry.\n+func NewGenericDirectoryFD(m *vfs.Mount, d *vfs.Dentry, children *OrderedChildren, opts *vfs.OpenOptions) (*GenericDirectoryFD, error) {\n+ fd := &GenericDirectoryFD{}\n+ if err := fd.Init(children, opts); err != nil {\n+ return nil, err\n+ }\n+ if err := fd.vfsfd.Init(fd, opts.Flags, m, d, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\n+ return fd, nil\n+}\n+\n+// Init initializes a GenericDirectoryFD. Use it when overriding\n+// GenericDirectoryFD. Caller must call fd.VFSFileDescription.Init() with the\n+// correct implementation.\n+func (fd *GenericDirectoryFD) Init(children *OrderedChildren, opts *vfs.OpenOptions) error {\nif vfs.AccessTypesForOpenFlags(opts)&vfs.MayWrite != 0 {\n// Can't open directories for writing.\nreturn syserror.EISDIR\n}\n- if err := fd.vfsfd.Init(fd, opts.Flags, m, d, &vfs.FileDescriptionOptions{}); err != nil {\n- return err\n- }\nfd.children = children\nreturn nil\n}\n@@ -187,6 +201,10 @@ func (fd *GenericDirectoryFD) Seek(ctx context.Context, offset int64, whence int\n// Use offset as given.\ncase linux.SEEK_CUR:\noffset += fd.off\n+ case linux.SEEK_END:\n+ // TODO(gvisor.dev/issue/1193): This can prevent new files from showing up\n+ // if they are added after SEEK_END.\n+ offset = math.MaxInt64\ndefault:\nreturn 0, syserror.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -82,7 +82,7 @@ afterSymlink:\n}\n// Resolve any symlink at current path component.\nif rp.ShouldFollowSymlink() && next.isSymlink() {\n- targetVD, targetPathname, err := next.inode.Getlink(ctx)\n+ targetVD, targetPathname, err := next.inode.Getlink(ctx, rp.Mount())\nif err != nil {\nreturn nil, err\n}\n@@ -477,7 +477,7 @@ afterTrailingSymlink:\n}\nchild := childVFSD.Impl().(*Dentry)\nif rp.ShouldFollowSymlink() && child.isSymlink() {\n- targetVD, targetPathname, err := child.inode.Getlink(ctx)\n+ targetVD, targetPathname, err := child.inode.Getlink(ctx, rp.Mount())\nif err != nil {\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/inode_impl_util.go",
"diff": "@@ -182,7 +182,7 @@ func (InodeNotSymlink) Readlink(context.Context) (string, error) {\n}\n// Getlink implements Inode.Getlink.\n-func (InodeNotSymlink) Getlink(context.Context) (vfs.VirtualDentry, string, error) {\n+func (InodeNotSymlink) Getlink(context.Context, *vfs.Mount) (vfs.VirtualDentry, string, error) {\nreturn vfs.VirtualDentry{}, \"\", syserror.EINVAL\n}\n@@ -568,8 +568,10 @@ func (s *StaticDirectory) Init(creds *auth.Credentials, ino uint64, perm linux.F\n// Open implements kernfs.Inode.\nfunc (s *StaticDirectory) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &s.OrderedChildren, &opts)\n+ fd, err := NewGenericDirectoryFD(rp.Mount(), vfsd, &s.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -439,5 +439,5 @@ type inodeSymlink interface {\n//\n// - If the inode is not a symlink, Getlink returns (zero-value\n// VirtualDentry, \"\", EINVAL).\n- Getlink(ctx context.Context) (vfs.VirtualDentry, string, error)\n+ Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"diff": "@@ -117,8 +117,8 @@ func (fs *filesystem) newReadonlyDir(creds *auth.Credentials, mode linux.FileMod\n}\nfunc (d *readonlyDir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- if err := fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, &opts); err != nil {\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &d.OrderedChildren, &opts)\n+ if err != nil {\nreturn nil, err\n}\nreturn fd.VFSFileDescription(), nil\n@@ -147,8 +147,10 @@ func (fs *filesystem) newDir(creds *auth.Credentials, mode linux.FileMode, conte\n}\nfunc (d *dir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &d.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"new_path": "pkg/sentry/fsimpl/kernfs/symlink.go",
"diff": "@@ -56,7 +56,7 @@ func (s *StaticSymlink) Readlink(_ context.Context) (string, error) {\n}\n// Getlink implements Inode.Getlink.\n-func (s *StaticSymlink) Getlink(_ context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *StaticSymlink) Getlink(context.Context, *vfs.Mount) (vfs.VirtualDentry, string, error) {\nreturn vfs.VirtualDentry{}, s.target, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"new_path": "pkg/sentry/fsimpl/proc/subtasks.go",
"diff": "@@ -88,6 +88,9 @@ func (i *subtasksInode) IterDirents(ctx context.Context, cb vfs.IterDirentsCallb\nif len(tasks) == 0 {\nreturn offset, syserror.ENOENT\n}\n+ if relOffset >= int64(len(tasks)) {\n+ return offset, nil\n+ }\ntids := make([]int, 0, len(tasks))\nfor _, tid := range tasks {\n@@ -110,10 +113,52 @@ func (i *subtasksInode) IterDirents(ctx context.Context, cb vfs.IterDirentsCallb\nreturn offset, nil\n}\n+type subtasksFD struct {\n+ kernfs.GenericDirectoryFD\n+\n+ task *kernel.Task\n+}\n+\n+func (fd *subtasksFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback) error {\n+ if fd.task.ExitState() >= kernel.TaskExitZombie {\n+ return syserror.ENOENT\n+ }\n+ return fd.GenericDirectoryFD.IterDirents(ctx, cb)\n+}\n+\n+// Seek implements vfs.FileDecriptionImpl.Seek.\n+func (fd *subtasksFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n+ if fd.task.ExitState() >= kernel.TaskExitZombie {\n+ return 0, syserror.ENOENT\n+ }\n+ return fd.GenericDirectoryFD.Seek(ctx, offset, whence)\n+}\n+\n+// Stat implements vfs.FileDescriptionImpl.Stat.\n+func (fd *subtasksFD) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n+ if fd.task.ExitState() >= kernel.TaskExitZombie {\n+ return linux.Statx{}, syserror.ENOENT\n+ }\n+ return fd.GenericDirectoryFD.Stat(ctx, opts)\n+}\n+\n+// SetStat implements vfs.FileDescriptionImpl.SetStat.\n+func (fd *subtasksFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+ if fd.task.ExitState() >= kernel.TaskExitZombie {\n+ return syserror.ENOENT\n+ }\n+ return fd.GenericDirectoryFD.SetStat(ctx, opts)\n+}\n+\n// Open implements kernfs.Inode.\nfunc (i *subtasksInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd := &subtasksFD{task: i.task}\n+ if err := fd.Init(&i.OrderedChildren, &opts); err != nil {\n+ return nil, err\n+ }\n+ if err := fd.VFSFileDescription().Init(fd, opts.Flags, rp.Mount(), vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task.go",
"new_path": "pkg/sentry/fsimpl/proc/task.go",
"diff": "@@ -44,6 +44,7 @@ type taskInode struct {\nvar _ kernfs.Inode = (*taskInode)(nil)\nfunc newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNamespace, isThreadGroup bool, cgroupControllers map[string]string) *kernfs.Dentry {\n+ // TODO(gvisor.dev/issue/164): Fail with ESRCH if task exited.\ncontents := map[string]*kernfs.Dentry{\n\"auxv\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &auxvData{task: task}),\n\"cmdline\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &cmdlineData{task: task, arg: cmdlineDataArg}),\n@@ -102,8 +103,10 @@ func (i *taskInode) Valid(ctx context.Context) bool {\n// Open implements kernfs.Inode.\nfunc (i *taskInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_fds.go",
"new_path": "pkg/sentry/fsimpl/proc/task_fds.go",
"diff": "@@ -143,8 +143,10 @@ func (i *fdDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, erro\n// Open implements kernfs.Inode.\nfunc (i *fdDirInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n@@ -207,7 +209,7 @@ func (s *fdSymlink) Readlink(ctx context.Context) (string, error) {\nreturn s.task.Kernel().VFS().PathnameWithDeleted(ctx, root, file.VirtualDentry())\n}\n-func (s *fdSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *fdSymlink) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\nfile, _ := getTaskFD(s.task, s.fd)\nif file == nil {\nreturn vfs.VirtualDentry{}, \"\", syserror.ENOENT\n@@ -268,8 +270,10 @@ func (i *fdInfoDirInode) Lookup(ctx context.Context, name string) (*vfs.Dentry,\n// Open implements kernfs.Inode.\nfunc (i *fdInfoDirInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_files.go",
"new_path": "pkg/sentry/fsimpl/proc/task_files.go",
"diff": "@@ -622,7 +622,7 @@ func (s *exeSymlink) Readlink(ctx context.Context) (string, error) {\n}\n// Getlink implements kernfs.Inode.Getlink.\n-func (s *exeSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *exeSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\nif !kernel.ContextCanTrace(ctx, s.task, false) {\nreturn vfs.VirtualDentry{}, \"\", syserror.EACCES\n}\n@@ -754,9 +754,79 @@ func (s *namespaceSymlink) Readlink(ctx context.Context) (string, error) {\n}\n// Getlink implements Inode.Getlink.\n-func (s *namespaceSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *namespaceSymlink) Getlink(ctx context.Context, mnt *vfs.Mount) (vfs.VirtualDentry, string, error) {\nif err := checkTaskState(s.task); err != nil {\nreturn vfs.VirtualDentry{}, \"\", err\n}\n- return s.StaticSymlink.Getlink(ctx)\n+\n+ // Create a synthetic inode to represent the namespace.\n+ dentry := &kernfs.Dentry{}\n+ dentry.Init(&namespaceInode{})\n+ vd := vfs.MakeVirtualDentry(mnt, dentry.VFSDentry())\n+ vd.IncRef()\n+ dentry.DecRef()\n+ return vd, \"\", nil\n+}\n+\n+// namespaceInode is a synthetic inode created to represent a namespace in\n+// /proc/[pid]/ns/*.\n+type namespaceInode struct {\n+ kernfs.InodeAttrs\n+ kernfs.InodeNoopRefCount\n+ kernfs.InodeNotDirectory\n+ kernfs.InodeNotSymlink\n+}\n+\n+var _ kernfs.Inode = (*namespaceInode)(nil)\n+\n+// Init initializes a namespace inode.\n+func (i *namespaceInode) Init(creds *auth.Credentials, ino uint64, perm linux.FileMode) {\n+ if perm&^linux.PermissionsMask != 0 {\n+ panic(fmt.Sprintf(\"Only permission mask must be set: %x\", perm&linux.PermissionsMask))\n+ }\n+ i.InodeAttrs.Init(creds, ino, linux.ModeRegular|perm)\n+}\n+\n+// Open implements Inode.Open.\n+func (i *namespaceInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ fd := &namespaceFD{inode: i}\n+ i.IncRef()\n+ if err := fd.vfsfd.Init(fd, opts.Flags, rp.Mount(), vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\n+ return &fd.vfsfd, nil\n+}\n+\n+// namespace FD is a synthetic file that represents a namespace in\n+// /proc/[pid]/ns/*.\n+type namespaceFD struct {\n+ vfs.FileDescriptionDefaultImpl\n+\n+ vfsfd vfs.FileDescription\n+ inode *namespaceInode\n+}\n+\n+var _ vfs.FileDescriptionImpl = (*namespaceFD)(nil)\n+\n+// Stat implements FileDescriptionImpl.\n+func (fd *namespaceFD) Stat(ctx context.Context, opts vfs.StatOptions) (linux.Statx, error) {\n+ vfs := fd.vfsfd.VirtualDentry().Mount().Filesystem()\n+ return fd.inode.Stat(vfs, opts)\n+}\n+\n+// SetStat implements FileDescriptionImpl.\n+func (fd *namespaceFD) SetStat(ctx context.Context, opts vfs.SetStatOptions) error {\n+ vfs := fd.vfsfd.VirtualDentry().Mount().Filesystem()\n+ creds := auth.CredentialsFromContext(ctx)\n+ return fd.inode.SetStat(ctx, vfs, creds, opts)\n+}\n+\n+// Release implements FileDescriptionImpl.\n+func (fd *namespaceFD) Release() {\n+ fd.inode.DecRef()\n+}\n+\n+// OnClose implements FileDescriptionImpl.\n+func (*namespaceFD) OnClose(context.Context) error {\n+ return nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks.go",
"diff": "@@ -202,8 +202,10 @@ func (i *tasksInode) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback\n// Open implements kernfs.Inode.\nfunc (i *tasksInode) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &i.OrderedChildren, &opts)\n+ if err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_files.go",
"diff": "@@ -63,7 +63,7 @@ func (s *selfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn strconv.FormatUint(uint64(tgid), 10), nil\n}\n-func (s *selfSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *selfSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\ntarget, err := s.Readlink(ctx)\nreturn vfs.VirtualDentry{}, target, err\n}\n@@ -106,7 +106,7 @@ func (s *threadSelfSymlink) Readlink(ctx context.Context) (string, error) {\nreturn fmt.Sprintf(\"%d/task/%d\", tgid, tid), nil\n}\n-func (s *threadSelfSymlink) Getlink(ctx context.Context) (vfs.VirtualDentry, string, error) {\n+func (s *threadSelfSymlink) Getlink(ctx context.Context, _ *vfs.Mount) (vfs.VirtualDentry, string, error) {\ntarget, err := s.Readlink(ctx)\nreturn vfs.VirtualDentry{}, target, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -106,8 +106,8 @@ func (*dir) SetStat(context.Context, *vfs.Filesystem, *auth.Credentials, vfs.Set\n// Open implements kernfs.Inode.Open.\nfunc (d *dir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- fd := &kernfs.GenericDirectoryFD{}\n- if err := fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, &opts); err != nil {\n+ fd, err := kernfs.NewGenericDirectoryFD(rp.Mount(), vfsd, &d.OrderedChildren, &opts)\n+ if err != nil {\nreturn nil, err\n}\nreturn fd.VFSFileDescription(), nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/vfs.go",
"new_path": "pkg/sentry/vfs/vfs.go",
"diff": "@@ -797,6 +797,14 @@ type VirtualDentry struct {\ndentry *Dentry\n}\n+// MakeVirtualDentry creates a VirtualDentry.\n+func MakeVirtualDentry(mount *Mount, dentry *Dentry) VirtualDentry {\n+ return VirtualDentry{\n+ mount: mount,\n+ dentry: dentry,\n+ }\n+}\n+\n// Ok returns true if vd is not empty. It does not require that a reference is\n// held.\nfunc (vd VirtualDentry) Ok() bool {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fixes for procfs
- Return ENOENT for /proc/[pid]/task if task is zoombied or terminated
- Allow directory to be Seek() to the end
- Construct synthetic files for /proc/[pid]/ns/*
- Changed GenericDirectoryFD.Init to not register with FileDescription,
otherwise other implementation cannot change behavior.
Updates #1195,1193
PiperOrigin-RevId: 308294649 |
260,004 | 24.04.2020 12:45:33 | 25,200 | 1ceee045294a6059093851645968f5a7e00a58f3 | Do not copy tcpip.CancellableTimer
A CancellableTimer's AfterFunc timer instance creates a closure over the
CancellableTimer's address. This closure makes a CancellableTimer unsafe
to copy.
No behaviour change, existing tests pass. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "@@ -412,20 +412,33 @@ type dadState struct {\n// defaultRouterState holds data associated with a default router discovered by\n// a Router Advertisement (RA).\ntype defaultRouterState struct {\n- invalidationTimer tcpip.CancellableTimer\n+ // Timer to invalidate the default router.\n+ //\n+ // May not be nil.\n+ invalidationTimer *tcpip.CancellableTimer\n}\n// onLinkPrefixState holds data associated with an on-link prefix discovered by\n// a Router Advertisement's Prefix Information option (PI) when the NDP\n// configurations was configured to do so.\ntype onLinkPrefixState struct {\n- invalidationTimer tcpip.CancellableTimer\n+ // Timer to invalidate the on-link prefix.\n+ //\n+ // May not be nil.\n+ invalidationTimer *tcpip.CancellableTimer\n}\n// slaacPrefixState holds state associated with a SLAAC prefix.\ntype slaacPrefixState struct {\n- deprecationTimer tcpip.CancellableTimer\n- invalidationTimer tcpip.CancellableTimer\n+ // Timer to deprecate the prefix.\n+ //\n+ // May not be nil.\n+ deprecationTimer *tcpip.CancellableTimer\n+\n+ // Timer to invalidate the prefix.\n+ //\n+ // May not be nil.\n+ invalidationTimer *tcpip.CancellableTimer\n// Nonzero only when the address is not valid forever.\nvalidUntil time.Time\n@@ -775,7 +788,6 @@ func (ndp *ndpState) invalidateDefaultRouter(ip tcpip.Address) {\n}\nrtr.invalidationTimer.StopLocked()\n-\ndelete(ndp.defaultRouters, ip)\n// Let the integrator know a discovered default router is invalidated.\n@@ -804,7 +816,7 @@ func (ndp *ndpState) rememberDefaultRouter(ip tcpip.Address, rl time.Duration) {\n}\nstate := defaultRouterState{\n- invalidationTimer: tcpip.MakeCancellableTimer(&ndp.nic.mu, func() {\n+ invalidationTimer: tcpip.NewCancellableTimer(&ndp.nic.mu, func() {\nndp.invalidateDefaultRouter(ip)\n}),\n}\n@@ -834,7 +846,7 @@ func (ndp *ndpState) rememberOnLinkPrefix(prefix tcpip.Subnet, l time.Duration)\n}\nstate := onLinkPrefixState{\n- invalidationTimer: tcpip.MakeCancellableTimer(&ndp.nic.mu, func() {\n+ invalidationTimer: tcpip.NewCancellableTimer(&ndp.nic.mu, func() {\nndp.invalidateOnLinkPrefix(prefix)\n}),\n}\n@@ -859,7 +871,6 @@ func (ndp *ndpState) invalidateOnLinkPrefix(prefix tcpip.Subnet) {\n}\ns.invalidationTimer.StopLocked()\n-\ndelete(ndp.onLinkPrefixes, prefix)\n// Let the integrator know a discovered on-link prefix is invalidated.\n@@ -979,7 +990,7 @@ func (ndp *ndpState) doSLAAC(prefix tcpip.Subnet, pl, vl time.Duration) {\n}\nstate := slaacPrefixState{\n- deprecationTimer: tcpip.MakeCancellableTimer(&ndp.nic.mu, func() {\n+ deprecationTimer: tcpip.NewCancellableTimer(&ndp.nic.mu, func() {\nstate, ok := ndp.slaacPrefixes[prefix]\nif !ok {\npanic(fmt.Sprintf(\"ndp: must have a slaacPrefixes entry for the deprecated SLAAC prefix %s\", prefix))\n@@ -987,7 +998,7 @@ func (ndp *ndpState) doSLAAC(prefix tcpip.Subnet, pl, vl time.Duration) {\nndp.deprecateSLAACAddress(state.ref)\n}),\n- invalidationTimer: tcpip.MakeCancellableTimer(&ndp.nic.mu, func() {\n+ invalidationTimer: tcpip.NewCancellableTimer(&ndp.nic.mu, func() {\nstate, ok := ndp.slaacPrefixes[prefix]\nif !ok {\npanic(fmt.Sprintf(\"ndp: must have a slaacPrefixes entry for the invalidated SLAAC prefix %s\", prefix))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/timer.go",
"new_path": "pkg/tcpip/timer.go",
"diff": "@@ -88,6 +88,9 @@ func (t *cancellableTimerInstance) stop() {\n//\n// The term \"related work\" is defined as some work that needs to be done while\n// holding some lock that the timer must also hold while doing some work.\n+//\n+// Note, it is not safe to copy a CancellableTimer as its timer instance creates\n+// a closure over the address of the CancellableTimer.\ntype CancellableTimer struct {\n// The active instance of a cancellable timer.\ninstance cancellableTimerInstance\n@@ -154,12 +157,28 @@ func (t *CancellableTimer) Reset(d time.Duration) {\n}\n}\n-// MakeCancellableTimer returns an unscheduled CancellableTimer with the given\n+// Lock is a no-op used by the copylocks checker from go vet.\n+//\n+// See CancellableTimer for details about why it shouldn't be copied.\n+//\n+// See https://github.com/golang/go/issues/8005#issuecomment-190753527 for more\n+// details about the copylocks checker.\n+func (*CancellableTimer) Lock() {}\n+\n+// Unlock is a no-op used by the copylocks checker from go vet.\n+//\n+// See CancellableTimer for details about why it shouldn't be copied.\n+//\n+// See https://github.com/golang/go/issues/8005#issuecomment-190753527 for more\n+// details about the copylocks checker.\n+func (*CancellableTimer) Unlock() {}\n+\n+// NewCancellableTimer returns an unscheduled CancellableTimer with the given\n// locker and fn.\n//\n// fn MUST NOT attempt to lock locker.\n//\n// Callers must call Reset to schedule the timer to fire.\n-func MakeCancellableTimer(locker sync.Locker, fn func()) CancellableTimer {\n- return CancellableTimer{locker: locker, fn: fn}\n+func NewCancellableTimer(locker sync.Locker, fn func()) *CancellableTimer {\n+ return &CancellableTimer{locker: locker, fn: fn}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/timer_test.go",
"new_path": "pkg/tcpip/timer_test.go",
"diff": "@@ -43,7 +43,7 @@ func TestCancellableTimerReassignment(t *testing.T) {\n// that has an active timer (even if it has been stopped as a stopped\n// timer may be blocked on a lock before it can check if it has been\n// stopped while another goroutine holds the same lock).\n- timer = tcpip.MakeCancellableTimer(&lock, func() {\n+ timer = *tcpip.NewCancellableTimer(&lock, func() {\nwg.Done()\n})\ntimer.Reset(shortDuration)\n@@ -59,7 +59,7 @@ func TestCancellableTimerFire(t *testing.T) {\nch := make(chan struct{})\nvar lock sync.Mutex\n- timer := tcpip.MakeCancellableTimer(&lock, func() {\n+ timer := tcpip.NewCancellableTimer(&lock, func() {\nch <- struct{}{}\n})\ntimer.Reset(shortDuration)\n@@ -85,7 +85,7 @@ func TestCancellableTimerResetFromLongDuration(t *testing.T) {\nch := make(chan struct{})\nvar lock sync.Mutex\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(middleDuration)\nlock.Lock()\n@@ -116,7 +116,7 @@ func TestCancellableTimerResetFromShortDuration(t *testing.T) {\nvar lock sync.Mutex\nlock.Lock()\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(shortDuration)\ntimer.StopLocked()\nlock.Unlock()\n@@ -153,7 +153,7 @@ func TestCancellableTimerImmediatelyStop(t *testing.T) {\nfor i := 0; i < 1000; i++ {\nlock.Lock()\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(shortDuration)\ntimer.StopLocked()\nlock.Unlock()\n@@ -174,7 +174,7 @@ func TestCancellableTimerStoppedResetWithoutLock(t *testing.T) {\nvar lock sync.Mutex\nlock.Lock()\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(shortDuration)\ntimer.StopLocked()\nlock.Unlock()\n@@ -205,7 +205,7 @@ func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {\nvar lock sync.Mutex\nlock.Lock()\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(shortDuration)\nfor i := 0; i < 10; i++ {\n// Sleep until the timer fires and gets blocked trying to take the lock.\n@@ -237,7 +237,7 @@ func TestManyCancellableTimerResetUnderLock(t *testing.T) {\nvar lock sync.Mutex\nlock.Lock()\n- timer := tcpip.MakeCancellableTimer(&lock, func() { ch <- struct{}{} })\n+ timer := tcpip.NewCancellableTimer(&lock, func() { ch <- struct{}{} })\ntimer.Reset(shortDuration)\nfor i := 0; i < 10; i++ {\ntimer.StopLocked()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not copy tcpip.CancellableTimer
A CancellableTimer's AfterFunc timer instance creates a closure over the
CancellableTimer's address. This closure makes a CancellableTimer unsafe
to copy.
No behaviour change, existing tests pass.
PiperOrigin-RevId: 308306664 |
259,853 | 24.04.2020 12:51:37 | 25,200 | f87964e829f438175edcc0264adc7ce7b3d83842 | kokoro: save all files from test.outputs/
If a test fails by timeout, bazel doesn't generate outputs.zip. | [
{
"change_type": "MODIFY",
"old_path": "scripts/common_build.sh",
"new_path": "scripts/common_build.sh",
"diff": "@@ -70,8 +70,8 @@ function collect_logs() {\nfor d in `find -L \"bazel-testlogs\" -name 'shard_*_of_*' | xargs dirname | sort | uniq`; do\njunitparser merge `find $d -name test.xml` $d/test.xml\ncat $d/shard_*_of_*/test.log > $d/test.log\n- if ls -l $d/shard_*_of_*/test.outputs/outputs.zip 2>/dev/null; then\n- zip -r -1 \"$d/outputs.zip\" $d/shard_*_of_*/test.outputs/outputs.zip\n+ if ls -ld $d/shard_*_of_*/test.outputs 2>/dev/null; then\n+ zip -r -1 \"$d/outputs.zip\" $d/shard_*_of_*/test.outputs\nfi\ndone\nfind -L \"bazel-testlogs\" -name 'shard_*_of_*' | xargs rm -rf\n"
}
] | Go | Apache License 2.0 | google/gvisor | kokoro: save all files from test.outputs/
If a test fails by timeout, bazel doesn't generate outputs.zip.
PiperOrigin-RevId: 308307815 |
259,860 | 24.04.2020 13:45:31 | 25,200 | f13f26d17da56d585fd9857a81175bbd0be8ce60 | Port SCM Rights to VFS2.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/control.go",
"new_path": "pkg/sentry/fs/host/control.go",
"diff": "@@ -23,6 +23,8 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n)\n+// LINT.IfChange\n+\ntype scmRights struct {\nfds []int\n}\n@@ -32,8 +34,6 @@ func newSCMRights(fds []int) control.SCMRights {\n}\n// Files implements control.SCMRights.Files.\n-//\n-// TODO(gvisor.dev/issue/2017): Port to VFS2.\nfunc (c *scmRights) Files(ctx context.Context, max int) (control.RightsFiles, bool) {\nn := max\nvar trunc bool\n@@ -93,3 +93,5 @@ func fdsToFiles(ctx context.Context, fds []int) []*fs.File {\n}\nreturn files\n}\n+\n+// LINT.ThenChange(../../fsimpl/host/control.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -5,6 +5,7 @@ licenses([\"notice\"])\ngo_library(\nname = \"host\",\nsrcs = [\n+ \"control.go\",\n\"host.go\",\n\"ioctl_unsafe.go\",\n\"tty.go\",\n@@ -23,6 +24,8 @@ go_library(\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/socket/control\",\n+ \"//pkg/sentry/socket/unix/transport\",\n\"//pkg/sentry/unimpl\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/host/control.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 host\n+\n+import (\n+ \"syscall\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/control\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+type scmRights struct {\n+ fds []int\n+}\n+\n+func newSCMRights(fds []int) control.SCMRightsVFS2 {\n+ return &scmRights{fds}\n+}\n+\n+// Files implements control.SCMRights.Files.\n+func (c *scmRights) Files(ctx context.Context, max int) (control.RightsFilesVFS2, bool) {\n+ n := max\n+ var trunc bool\n+ if l := len(c.fds); n > l {\n+ n = l\n+ } else if n < l {\n+ trunc = true\n+ }\n+\n+ rf := control.RightsFilesVFS2(fdsToFiles(ctx, c.fds[:n]))\n+\n+ // Only consume converted FDs (fdsToFiles may convert fewer than n FDs).\n+ c.fds = c.fds[len(rf):]\n+ return rf, trunc\n+}\n+\n+// Clone implements transport.RightsControlMessage.Clone.\n+func (c *scmRights) Clone() transport.RightsControlMessage {\n+ // Host rights never need to be cloned.\n+ return nil\n+}\n+\n+// Release implements transport.RightsControlMessage.Release.\n+func (c *scmRights) Release() {\n+ for _, fd := range c.fds {\n+ syscall.Close(fd)\n+ }\n+ c.fds = nil\n+}\n+\n+// If an error is encountered, only files created before the error will be\n+// returned. This is what Linux does.\n+func fdsToFiles(ctx context.Context, fds []int) []*vfs.FileDescription {\n+ files := make([]*vfs.FileDescription, 0, len(fds))\n+ for _, fd := range fds {\n+ // Get flags. We do it here because they may be modified\n+ // by subsequent functions.\n+ fileFlags, _, errno := syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_GETFL, 0)\n+ if errno != 0 {\n+ ctx.Warningf(\"Error retrieving host FD flags: %v\", error(errno))\n+ break\n+ }\n+\n+ // Create the file backed by hostFD.\n+ file, err := ImportFD(ctx, kernel.KernelFromContext(ctx).HostMount(), fd, false /* isTTY */)\n+ if err != nil {\n+ ctx.Warningf(\"Error creating file from host FD: %v\", err)\n+ break\n+ }\n+\n+ if err := file.SetStatusFlags(ctx, auth.CredentialsFromContext(ctx), uint32(fileFlags&linux.O_NONBLOCK)); err != nil {\n+ ctx.Warningf(\"Error setting flags on host FD file: %v\", err)\n+ break\n+ }\n+\n+ files = append(files, file)\n+ }\n+ return files\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/BUILD",
"new_path": "pkg/sentry/socket/control/BUILD",
"diff": "@@ -4,7 +4,10 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"control\",\n- srcs = [\"control.go\"],\n+ srcs = [\n+ \"control.go\",\n+ \"control_vfs2.go\",\n+ ],\nimports = [\n\"gvisor.dev/gvisor/pkg/sentry/fs\",\n],\n@@ -18,6 +21,7 @@ go_library(\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/socket\",\n\"//pkg/sentry/socket/unix/transport\",\n+ \"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n\"//pkg/tcpip\",\n\"//pkg/usermem\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -41,6 +41,8 @@ type SCMCredentials interface {\nCredentials(t *kernel.Task) (kernel.ThreadID, auth.UID, auth.GID)\n}\n+// LINT.IfChange\n+\n// SCMRights represents a SCM_RIGHTS socket control message.\ntype SCMRights interface {\ntransport.RightsControlMessage\n@@ -142,6 +144,8 @@ func PackRights(t *kernel.Task, rights SCMRights, cloexec bool, buf []byte, flag\nreturn putCmsg(buf, flags, linux.SCM_RIGHTS, align, fds)\n}\n+// LINT.ThenChange(./control_vfs2.go)\n+\n// scmCredentials represents an SCM_CREDENTIALS socket control message.\n//\n// +stateify savable\n@@ -537,12 +541,20 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (socket.Con\n}\nif len(fds) > 0 {\n+ if kernel.VFS2Enabled {\n+ rights, err := NewSCMRightsVFS2(t, fds)\n+ if err != nil {\n+ return socket.ControlMessages{}, err\n+ }\n+ cmsgs.Unix.Rights = rights\n+ } else {\nrights, err := NewSCMRights(t, fds)\nif err != nil {\nreturn socket.ControlMessages{}, err\n}\ncmsgs.Unix.Rights = rights\n}\n+ }\nreturn cmsgs, nil\n}\n@@ -566,6 +578,8 @@ func MakeCreds(t *kernel.Task) SCMCredentials {\nreturn &scmCredentials{t, tcred.EffectiveKUID, tcred.EffectiveKGID}\n}\n+// LINT.IfChange\n+\n// New creates default control messages if needed.\nfunc New(t *kernel.Task, socketOrEndpoint interface{}, rights SCMRights) transport.ControlMessages {\nreturn transport.ControlMessages{\n@@ -573,3 +587,5 @@ func New(t *kernel.Task, socketOrEndpoint interface{}, rights SCMRights) transpo\nRights: rights,\n}\n}\n+\n+// LINT.ThenChange(./control_vfs2.go)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/socket/control/control_vfs2.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 control\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// SCMRightsVFS2 represents a SCM_RIGHTS socket control message.\n+type SCMRightsVFS2 interface {\n+ transport.RightsControlMessage\n+\n+ // Files returns up to max RightsFiles.\n+ //\n+ // Returned files are consumed and ownership is transferred to the caller.\n+ // Subsequent calls to Files will return the next files.\n+ Files(ctx context.Context, max int) (rf RightsFilesVFS2, truncated bool)\n+}\n+\n+// RightsFiles represents a SCM_RIGHTS socket control message. A reference is\n+// maintained for each vfs.FileDescription and is release either when an FD is created or\n+// when the Release method is called.\n+type RightsFilesVFS2 []*vfs.FileDescription\n+\n+// NewSCMRightsVFS2 creates a new SCM_RIGHTS socket control message\n+// representation using local sentry FDs.\n+func NewSCMRightsVFS2(t *kernel.Task, fds []int32) (SCMRightsVFS2, error) {\n+ files := make(RightsFilesVFS2, 0, len(fds))\n+ for _, fd := range fds {\n+ file := t.GetFileVFS2(fd)\n+ if file == nil {\n+ files.Release()\n+ return nil, syserror.EBADF\n+ }\n+ files = append(files, file)\n+ }\n+ return &files, nil\n+}\n+\n+// Files implements SCMRights.Files.\n+func (fs *RightsFilesVFS2) Files(ctx context.Context, max int) (RightsFilesVFS2, bool) {\n+ n := max\n+ var trunc bool\n+ if l := len(*fs); n > l {\n+ n = l\n+ } else if n < l {\n+ trunc = true\n+ }\n+ rf := (*fs)[:n]\n+ *fs = (*fs)[n:]\n+ return rf, trunc\n+}\n+\n+// Clone implements transport.RightsControlMessage.Clone.\n+func (fs *RightsFilesVFS2) Clone() transport.RightsControlMessage {\n+ nfs := append(RightsFilesVFS2(nil), *fs...)\n+ for _, nf := range nfs {\n+ nf.IncRef()\n+ }\n+ return &nfs\n+}\n+\n+// Release implements transport.RightsControlMessage.Release.\n+func (fs *RightsFilesVFS2) Release() {\n+ for _, f := range *fs {\n+ f.DecRef()\n+ }\n+ *fs = nil\n+}\n+\n+// rightsFDsVFS2 gets up to the specified maximum number of FDs.\n+func rightsFDsVFS2(t *kernel.Task, rights SCMRightsVFS2, cloexec bool, max int) ([]int32, bool) {\n+ files, trunc := rights.Files(t, max)\n+ fds := make([]int32, 0, len(files))\n+ for i := 0; i < max && len(files) > 0; i++ {\n+ fd, err := t.NewFDFromVFS2(0, files[0], kernel.FDFlags{\n+ CloseOnExec: cloexec,\n+ })\n+ files[0].DecRef()\n+ files = files[1:]\n+ if err != nil {\n+ t.Warningf(\"Error inserting FD: %v\", err)\n+ // This is what Linux does.\n+ break\n+ }\n+\n+ fds = append(fds, int32(fd))\n+ }\n+ return fds, trunc\n+}\n+\n+// PackRightsVFS2 packs as many FDs as will fit into the unused capacity of buf.\n+func PackRightsVFS2(t *kernel.Task, rights SCMRightsVFS2, cloexec bool, buf []byte, flags int) ([]byte, int) {\n+ maxFDs := (cap(buf) - len(buf) - linux.SizeOfControlMessageHeader) / 4\n+ // Linux does not return any FDs if none fit.\n+ if maxFDs <= 0 {\n+ flags |= linux.MSG_CTRUNC\n+ return buf, flags\n+ }\n+ fds, trunc := rightsFDsVFS2(t, rights, cloexec, maxFDs)\n+ if trunc {\n+ flags |= linux.MSG_CTRUNC\n+ }\n+ align := t.Arch().Width()\n+ return putCmsg(buf, flags, linux.SCM_RIGHTS, align, fds)\n+}\n+\n+// NewVFS2 creates default control messages if needed.\n+func NewVFS2(t *kernel.Task, socketOrEndpoint interface{}, rights SCMRightsVFS2) transport.ControlMessages {\n+ return transport.ControlMessages{\n+ Credentials: makeCreds(t, socketOrEndpoint),\n+ Rights: rights,\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/socket.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/socket.go",
"diff": "@@ -804,7 +804,7 @@ func recvSingleMsg(t *kernel.Task, s socket.SocketVFS2, msgPtr usermem.Addr, fla\n}\nif cms.Unix.Rights != nil {\n- controlData, mflags = control.PackRights(t, cms.Unix.Rights.(control.SCMRights), flags&linux.MSG_CMSG_CLOEXEC != 0, controlData, mflags)\n+ controlData, mflags = control.PackRightsVFS2(t, cms.Unix.Rights.(control.SCMRightsVFS2), flags&linux.MSG_CMSG_CLOEXEC != 0, controlData, mflags)\n}\n// Copy the address to the caller.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Port SCM Rights to VFS2.
Fixes #1477.
PiperOrigin-RevId: 308317511 |
259,972 | 24.04.2020 14:41:33 | 25,200 | d5776be3fbcc9e71c449b7b41786929734ce47e2 | Improve and update packetimpact README.md | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/README.md",
"new_path": "test/packetimpact/README.md",
"diff": "@@ -30,8 +30,8 @@ There are a few ways to write networking tests for gVisor currently:\nThe right choice depends on the needs of the test.\nFeature | Go unit test | syscall test | packetdrill | packetimpact\n-------------- | ------------ | ------------ | ----------- | ------------\n-Multiplatform | no | **YES** | **YES** | **YES**\n+-------------- | ------------ | ------------ | ----------- | ------------\n+Multi-platform | no | **YES** | **YES** | **YES**\nConcise | no | somewhat | somewhat | **VERY**\nControl-flow | **YES** | **YES** | no | **YES**\nFlexible | **VERY** | no | somewhat | **VERY**\n@@ -41,12 +41,12 @@ Flexible | **VERY** | no | somewhat | **VERY**\nIf the test depends on the internals of gVisor and doesn't need to run on Linux\nor other platforms for comparison purposes, a Go unit test can be appropriate.\nThey can observe internals of gVisor networking. The downside is that they are\n-**not concise** and **not multiplatform**. If you require insight on gVisor\n+**not concise** and **not multi-platform**. If you require insight on gVisor\ninternals, this is the right choice.\n### Syscall tests\n-Syscall tests are **multiplatform** but cannot examine the internals of gVisor\n+Syscall tests are **multi-platform** but cannot examine the internals of gVisor\nnetworking. They are **concise**. They can use **control-flow** structures like\nconditionals, for loops, and variables. However, they are limited to only what\nthe POSIX interface provides so they are **not flexible**. For example, you\n@@ -57,7 +57,7 @@ protocols, wrong sequence numbers, etc.\n### Packetdrill tests\n-Packetdrill tests are **multiplatform** and can run against both Linux and\n+Packetdrill tests are **multi-platform** and can run against both Linux and\ngVisor. They are **concise** and use a special packetdrill scripting language.\nThey are **more flexible** than a syscall test in that they can send packets\nthat a syscall test would have difficulty sending, like a packet with a\n@@ -73,7 +73,7 @@ other side supports window scaling, for example.\nPacketimpact tests are similar to Packetdrill tests except that they are written\nin Go instead of the packetdrill scripting language. That gives them all the\n**control-flow** abilities of Go (loops, functions, variables, etc). They are\n-**multiplatform** in the same way as packetdrill tests but even more\n+**multi-platform** in the same way as packetdrill tests but even more\n**flexible** because Go is more expressive than the scripting language of\npacketdrill. However, Go is **not as concise** as the packetdrill language. Many\ndesign decisions below are made to mitigate that.\n@@ -81,21 +81,27 @@ design decisions below are made to mitigate that.\n## How it works\n```\n- +--------------+ +--------------+\n+ Testbench Device-Under-Test (DUT)\n+ +-------------------+ +------------------------+\n| | TEST NET | |\n- | | <===========> | Device |\n- | Test | | Under |\n- | Bench | | Test |\n- | | <===========> | (DUT) |\n+ | rawsockets.go <-->| <===========> | <---+ |\n+ | ^ | | | |\n+ | | | | | |\n+ | v | | | |\n+ | unittest | | | |\n+ | ^ | | | |\n+ | | | | | |\n+ | v | | v |\n+ | dut.go <========gRPC========> posix server |\n| | CONTROL NET | |\n- +--------------+ +--------------+\n+ +-------------------+ +------------------------+\n```\n-Two docker containers are created by a script, one for the test bench and the\n-other for the device under test (DUT). The script connects the two containers\n-with a control network and test network. It also does some other tasks like\n-waiting until the DUT is ready before starting the test and disabling Linux\n-networking that would interfere with the test bench.\n+Two docker containers are created by a \"runner\" script, one for the testbench\n+and the other for the device under test (DUT). The script connects the two\n+containers with a control network and test network. It also does some other\n+tasks like waiting until the DUT is ready before starting the test and disabling\n+Linux networking that would interfere with the test bench.\n### DUT\n@@ -220,7 +226,8 @@ func (i *Injector) Send(b []byte) {...}\ncontainer and in practice, the container doesn't recognize binaries built on\nthe host if they use cgo.\n* Both gVisor and gopacket have the ability to read and write pcap files\n- without cgo but that is insufficient here.\n+ without cgo but that is insufficient here because we can't just replay pcap\n+ files, we need a more dynamic solution.\n* The sniffer and injector can't share a socket because they need to be bound\ndifferently.\n* Sniffing could have been done asynchronously with channels, obviating the\n@@ -270,11 +277,10 @@ but with a pointer for each field that may be `nil`.\n* Many functions, one per field, like: `filterByFlag(myBytes, SYN)`,\n`filterByLength(myBytes, 20)`, `filterByNextProto(myBytes, 0x8000)`,\netc.\n- * Using pointers allows us to combine `Layer`s with a one-line call to\n- `mergo.Merge(...)`. So the default `Layers` can be overridden by a\n- `Layers` with just the TCP conection's src/dst which can be overridden\n- by one with just a test specific TCP window size. Each override is\n- specified as just one call to `mergo.Merge`.\n+ * Using pointers allows us to combine `Layer`s with reflection. So the\n+ default `Layers` can be overridden by a `Layers` with just the TCP\n+ conection's src/dst which can be overridden by one with just a test\n+ specific TCP window size.\n* It's a proven way to separate the details of a packet from the byte\nformat as shown by scapy's success.\n* Use packetgo. It's more general than parsing packets with gVisor. However:\n@@ -334,6 +340,14 @@ type Layer interface {\n}\n```\n+The `next` and `prev` make up a link listed so that each layer can get at the\n+information in the layer around it. This is necessary for some protocols, like\n+TCP that needs the layer before and payload after to compute the checksum. Any\n+sequence of `Layer` structs is valid so long as the parser and `toBytes`\n+functions can map from type to protool number and vice-versa. When the mapping\n+fails, an error is emitted explaining what functionality is missing. The\n+solution is either to fix the ordering or implement the missing protocol.\n+\nFor each `Layer` there is also a parsing function. For example, this one is for\nEthernet:\n@@ -392,81 +406,217 @@ for {\n##### Alternatives considered\n* Don't use previous and next pointers.\n- * Each layer may need to be able to interrogate the layers aroung it, like\n+ * Each layer may need to be able to interrogate the layers around it, like\nfor computing the next protocol number or total length. So *some*\nmechanism is needed for a `Layer` to see neighboring layers.\n* We could pass the entire array `Layers` to the `toBytes()` function.\nPassing an array to a method that includes in the array the function\nreceiver itself seems wrong.\n-#### Connections\n+#### `layerState`\n-Using `Layers` above, we can create connection structures to maintain state\n-about connections. For example, here is the `TCPIPv4` struct:\n+`Layers` represents the different headers of a packet but a connection includes\n+more state. For example, a TCP connection needs to keep track of the next\n+expected sequence number and also the next sequence number to send. This is\n+stored in a `layerState` struct. This is the `layerState` for TCP:\n+```go\n+// tcpState maintains state about a TCP connection.\n+type tcpState struct {\n+ out, in TCP\n+ localSeqNum, remoteSeqNum *seqnum.Value\n+ synAck *TCP\n+ portPickerFD int\n+ finSent bool\n+}\n```\n-type TCPIPv4 struct {\n- outgoing Layers\n- incoming Layers\n- localSeqNum uint32\n- remoteSeqNum uint32\n- sniffer Sniffer\n+\n+The next sequence numbers for each side of the connection are stored. `out` and\n+`in` have defaults for the TCP header, such as the expected source and\n+destination ports for outgoing packets and incoming packets.\n+\n+##### `layerState` interface\n+\n+```go\n+// layerState stores the state of a layer of a connection.\n+type layerState interface {\n+ // outgoing returns an outgoing layer to be sent in a frame.\n+ outgoing() Layer\n+\n+ // incoming creates an expected Layer for comparing against a received Layer.\n+ // Because the expectation can depend on values in the received Layer, it is\n+ // an input to incoming. For example, the ACK number needs to be checked in a\n+ // TCP packet but only if the ACK flag is set in the received packet.\n+ incoming(received Layer) Layer\n+\n+ // sent updates the layerState based on the Layer that was sent. The input is\n+ // a Layer with all prev and next pointers populated so that the entire frame\n+ // as it was sent is available.\n+ sent(sent Layer) error\n+\n+ // received updates the layerState based on a Layer that is receieved. The\n+ // input is a Layer with all prev and next pointers populated so that the\n+ // entire frame as it was receieved is available.\n+ received(received Layer) error\n+\n+ // close frees associated resources held by the LayerState.\n+ close() error\n+}\n+```\n+\n+`outgoing` generates the default Layer for an outgoing packet. For TCP, this\n+would be a `TCP` with the source and destination ports populated. Because they\n+are static, they are stored inside the `out` member of `tcpState`. However, the\n+sequence numbers change frequently so the outgoing sequence number is stored in\n+the `localSeqNum` and put into the output of outgoing for each call.\n+\n+`incoming` does the same functions for packets that arrive but instead of\n+generating a packet to send, it generates an expect packet for filtering packets\n+that arrive. For example, if a `TCP` header arrives with the wrong ports, it can\n+be ignored as belonging to a different connection. `incoming` needs the received\n+header itself as an input because the filter may depend on the input. For\n+example, the expected sequence number depends on the flags in the TCP header.\n+\n+`sent` and `received` are run for each header that is actually sent or received\n+and used to update the internal state. `incoming` and `outgoing` should *not* be\n+used for these purpose. For example, `incoming` is called on every packet that\n+arrives but only packets that match ought to actually update the state.\n+`outgoing` is called to created outgoing packets and those packets are always\n+sent, so unlike `incoming`/`received`, there is one `outgoing` call for each\n+`sent` call.\n+\n+`close` cleans up after the layerState. For example, TCP and UDP need to keep a\n+port reserved and then release it.\n+\n+#### Connections\n+\n+Using `layerState` above, we can create connections.\n+\n+```go\n+// Connection holds a collection of layer states for maintaining a connection\n+// along with sockets for sniffer and injecting packets.\n+type Connection struct {\n+ layerStates []layerState\ninjector Injector\n+ sniffer Sniffer\nt *testing.T\n}\n```\n-`TCPIPv4` contains an `outgoing Layers` which holds the defaults for the\n-connection, such as the source and destination MACs, IPs, and ports. When\n-`outgoing.toBytes()` is called a valid packet for this TCPIPv4 flow is built.\n+The connection stores an array of `layerState` in the order that the headers\n+should be present in the frame to send. For example, Ether then IPv4 then TCP.\n+The injector and sniffer are for writing and reading frames. A `*testing.T` is\n+stored so that internal errors can be reported directly without code in the unit\n+test.\n-It also contains `incoming Layers` which holds filter for incoming packets that\n-belong to this flow. `incoming.match(Layers)` is used on received bytes to check\n-if they are part of the flow.\n+The `Connection` has some useful functions:\n-The `sniffer` and `injector` are for receiving and sending raw packet bytes. The\n-`localSeqNum` and `remoteSeqNum` are updated by `Send` and `Recv` so that\n-outgoing packets will have, by default, the correct sequence number and ack\n-number.\n+```go\n+// Close frees associated resources held by the Connection.\n+func (conn *Connection) Close() {...}\n+// CreateFrame builds a frame for the connection with layer overriding defaults\n+// of the innermost layer and additionalLayers added after it.\n+func (conn *Connection) CreateFrame(layer Layer, additionalLayers ...Layer) Layers {...}\n+// SendFrame sends a frame on the wire and updates the state of all layers.\n+func (conn *Connection) SendFrame(frame Layers) {...}\n+// Send a packet with reasonable defaults. Potentially override the final layer\n+// in the connection with the provided layer and add additionLayers.\n+func (conn *Connection) Send(layer Layer, additionalLayers ...Layer) {...}\n+// Expect a frame with the final layerStates layer matching the provided Layer\n+// within the timeout specified. If it doesn't arrive in time, it returns nil.\n+func (conn *Connection) Expect(layer Layer, timeout time.Duration) (Layer, error) {...}\n+// ExpectFrame expects a frame that matches the provided Layers within the\n+// timeout specified. If it doesn't arrive in time, it returns nil.\n+func (conn *Connection) ExpectFrame(layers Layers, timeout time.Duration) (Layers, error) {...}\n+// Drain drains the sniffer's receive buffer by receiving packets until there's\n+// nothing else to receive.\n+func (conn *Connection) Drain() {...}\n+```\n-TCPIPv4 provides some functions:\n+`CreateFrame` uses the `[]layerState` to create a frame to send. The first\n+argument is for overriding defaults in the last header of the frame, because\n+this is the most common need. For a TCPIPv4 connection, this would be the TCP\n+header. Optional additionalLayers can be specified to add to the frame being\n+created, such as a `Payload` for `TCP`.\n+\n+`SendFrame` sends the frame to the DUT. It is combined with `CreateFrame` to\n+make `Send`. For unittests with basic sending needs, `Send` can be used. If more\n+control is needed over the frame, it can be made with `CreateFrame`, modified in\n+the unit test, and then sent with `SendFrame`.\n+\n+On the receiving side, there is `Expect` and `ExpectFrame`. Like with the\n+sending side, there are two forms of each function, one for just the last header\n+and one for the whole frame. The expect functions use the `[]layerState` to\n+create a template for the expected incoming frame. That frame is then overridden\n+by the values in the first argument. Finally, a loop starts sniffing packets on\n+the wire for frames. If a matching frame is found before the timeout, it is\n+returned without error. If not, nil is returned and the error contains text of\n+all the received frames that didn't match. Exactly one of the outputs will be\n+non-nil, even if no frames are received at all.\n+\n+`Drain` sniffs and discards all the frames that have yet to be received. A\n+common way to write a test is:\n-```\n-func (conn *TCPIPv4) Send(tcp TCP) {...}\n-func (conn *TCPIPv4) Recv(timeout time.Duration) *TCP {...}\n+```go\n+conn.Drain() // Discard all outstanding frames.\n+conn.Send(...) // Send a frame with overrides.\n+// Now expect a frame with a certain header and fail if it doesn't arrive.\n+if _, err := conn.Expect(...); err != nil { t.Fatal(...) }\n```\n-`Send(tcp TCP)` uses [mergo](https://github.com/imdario/mergo) to merge the\n-provided `TCP` (a `Layer`) into `outgoing`. This way the user can specify\n-concisely just which fields of `outgoing` to modify. The packet is sent using\n-the `injector`.\n+Or for a test where we want to check that no frame arrives:\n-`Recv(timeout time.Duration)` reads packets from the sniffer until either the\n-timeout has elapsed or a packet that matches `incoming` arrives.\n+```go\n+if gotOne, _ := conn.Expect(...); gotOne != nil { t.Fatal(...) }\n+```\n+\n+#### Specializing `Connection`\n-Using those, we can perform a TCP 3-way handshake without too much code:\n+Because there are some common combinations of `layerState` into `Connection`,\n+they are defined:\n```go\n-func (conn *TCPIPv4) Handshake() {\n- syn := uint8(header.TCPFlagSyn)\n- synack := uint8(header.TCPFlagSyn)\n- ack := uint8(header.TCPFlagAck)\n- conn.Send(TCP{Flags: &syn}) // Send a packet with all defaults but set TCP-SYN.\n+// TCPIPv4 maintains the state for all the layers in a TCP/IPv4 connection.\n+type TCPIPv4 Connection\n+// UDPIPv4 maintains the state for all the layers in a UDP/IPv4 connection.\n+type UDPIPv4 Connection\n+```\n- // Wait for the SYN-ACK response.\n- for {\n- newTCP := conn.Recv(time.Second) // This already filters by MAC, IP, and ports.\n- if TCP{Flags: &synack}.match(newTCP) {\n- break // Only if it's a SYN-ACK proceed.\n+Each has a `NewXxx` function to create a new connection with reasonable\n+defaults. They also have functions that call the underlying `Connection`\n+functions but with specialization and tighter type-checking. For example:\n+\n+```go\n+func (conn *TCPIPv4) Send(tcp TCP, additionalLayers ...Layer) {\n+ (*Connection)(conn).Send(&tcp, additionalLayers...)\n}\n+func (conn *TCPIPv4) Drain() {\n+ conn.sniffer.Drain()\n}\n+```\n+\n+They may also have some accessors to get or set the internal state of the\n+connection:\n- conn.Send(TCP{Flags: &ack}) // Send an ACK. The seq and ack numbers are set correctly.\n+```go\n+func (conn *TCPIPv4) state() *tcpState {\n+ state, ok := conn.layerStates[len(conn.layerStates)-1].(*tcpState)\n+ if !ok {\n+ conn.t.Fatalf(\"expected final state of %v to be tcpState\", conn.layerStates)\n+ }\n+ return state\n+}\n+func (conn *TCPIPv4) RemoteSeqNum() *seqnum.Value {\n+ return conn.state().remoteSeqNum\n+}\n+func (conn *TCPIPv4) LocalSeqNum() *seqnum.Value {\n+ return conn.state().localSeqNum\n}\n```\n-The handshake code is part of the testbench utilities so tests can share this\n-common sequence, making tests even more concise.\n+Unittests will in practice use these functions and not the functions on\n+`Connection`. For example, `NewTCPIPv4()` and then call `Send` on that rather\n+than cast is to a `Connection` and call `Send` on that cast result.\n##### Alternatives considered\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve and update packetimpact README.md
PiperOrigin-RevId: 308328860 |
259,972 | 24.04.2020 15:02:33 | 25,200 | 3d860530a904004aea5bc95e6331b3b11cec1877 | Better error message from ExpectFrame
Display the errors as diffs between the expected and wanted frame. | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/connections.go",
"new_path": "test/packetimpact/testbench/connections.go",
"diff": "@@ -21,7 +21,6 @@ import (\n\"fmt\"\n\"math/rand\"\n\"net\"\n- \"strings\"\n\"testing\"\n\"time\"\n@@ -66,14 +65,16 @@ func pickPort() (int, uint16, error) {\n// layerState stores the state of a layer of a connection.\ntype layerState interface {\n- // outgoing returns an outgoing layer to be sent in a frame.\n+ // outgoing returns an outgoing layer to be sent in a frame. It should not\n+ // update layerState, that is done in layerState.sent.\noutgoing() Layer\n// incoming creates an expected Layer for comparing against a received Layer.\n// Because the expectation can depend on values in the received Layer, it is\n// an input to incoming. For example, the ACK number needs to be checked in a\n- // TCP packet but only if the ACK flag is set in the received packet. The\n- // calles takes ownership of the returned Layer.\n+ // TCP packet but only if the ACK flag is set in the received packet. It\n+ // should not update layerState, that is done in layerState.received. The\n+ // caller takes ownership of the returned Layer.\nincoming(received Layer) Layer\n// sent updates the layerState based on the Layer that was sent. The input is\n@@ -363,44 +364,33 @@ type Connection struct {\nt *testing.T\n}\n-// match tries to match each Layer in received against the incoming filter. If\n-// received is longer than layerStates then that may still count as a match. The\n-// reverse is never a match. override overrides the default matchers for each\n-// Layer.\n-func (conn *Connection) match(override, received Layers) bool {\n- var layersToMatch int\n- if len(override) < len(conn.layerStates) {\n- layersToMatch = len(conn.layerStates)\n- } else {\n- layersToMatch = len(override)\n- }\n- if len(received) < layersToMatch {\n- return false\n- }\n- for i := 0; i < layersToMatch; i++ {\n- var toMatch Layer\n- if i < len(conn.layerStates) {\n- s := conn.layerStates[i]\n- toMatch = s.incoming(received[i])\n+// Returns the default incoming frame against which to match. If received is\n+// longer than layerStates then that may still count as a match. The reverse is\n+// never a match and nil is returned.\n+func (conn *Connection) incoming(received Layers) Layers {\n+ if len(received) < len(conn.layerStates) {\n+ return nil\n+ }\n+ in := Layers{}\n+ for i, s := range conn.layerStates {\n+ toMatch := s.incoming(received[i])\nif toMatch == nil {\n- return false\n+ return nil\n}\n- if i < len(override) {\n- if err := toMatch.merge(override[i]); err != nil {\n- conn.t.Fatalf(\"failed to merge: %s\", err)\n+ in = append(in, toMatch)\n}\n+ return in\n}\n- } else {\n- toMatch = override[i]\n+\n+func (conn *Connection) match(override, received Layers) bool {\n+ toMatch := conn.incoming(received)\nif toMatch == nil {\n- conn.t.Fatalf(\"expect the overriding layers to be non-nil\")\n- }\n+ return false // Not enough layers in gotLayers for matching.\n}\n- if !toMatch.match(received[i]) {\n- return false\n+ if err := toMatch.merge(override); err != nil {\n+ return false // Failing to merge is not matching.\n}\n- }\n- return true\n+ return toMatch.match(received)\n}\n// Close frees associated resources held by the Connection.\n@@ -470,6 +460,16 @@ func (conn *Connection) recvFrame(timeout time.Duration) Layers {\nreturn parse(parseEther, b)\n}\n+// layersError stores the Layers that we got and the Layers that we wanted to\n+// match.\n+type layersError struct {\n+ got, want Layers\n+}\n+\n+func (e *layersError) Error() string {\n+ return e.got.diff(e.want)\n+}\n+\n// Expect a frame with the final layerStates layer matching the provided Layer\n// within the timeout specified. If it doesn't arrive in time, it returns nil.\nfunc (conn *Connection) Expect(layer Layer, timeout time.Duration) (Layer, error) {\n@@ -485,21 +485,25 @@ func (conn *Connection) Expect(layer Layer, timeout time.Duration) (Layer, error\nreturn gotFrame[len(conn.layerStates)-1], nil\n}\nconn.t.Fatal(\"the received frame should be at least as long as the expected layers\")\n- return nil, fmt.Errorf(\"the received frame should be at least as long as the expected layers\")\n+ panic(\"unreachable\")\n}\n// ExpectFrame expects a frame that matches the provided Layers within the\n-// timeout specified. If it doesn't arrive in time, it returns nil.\n+// timeout specified. If one arrives in time, the Layers is returned without an\n+// error. If it doesn't arrive in time, it returns nil and error is non-nil.\nfunc (conn *Connection) ExpectFrame(layers Layers, timeout time.Duration) (Layers, error) {\ndeadline := time.Now().Add(timeout)\n- var allLayers []string\n+ var errs error\nfor {\nvar gotLayers Layers\nif timeout = time.Until(deadline); timeout > 0 {\ngotLayers = conn.recvFrame(timeout)\n}\nif gotLayers == nil {\n- return nil, fmt.Errorf(\"got %d packets:\\n%s\", len(allLayers), strings.Join(allLayers, \"\\n\"))\n+ if errs == nil {\n+ return nil, fmt.Errorf(\"got no frames matching %v during %s\", layers, timeout)\n+ }\n+ return nil, fmt.Errorf(\"got no frames matching %v during %s: got %w\", layers, timeout, errs)\n}\nif conn.match(layers, gotLayers) {\nfor i, s := range conn.layerStates {\n@@ -509,7 +513,7 @@ func (conn *Connection) ExpectFrame(layers Layers, timeout time.Duration) (Layer\n}\nreturn gotLayers, nil\n}\n- allLayers = append(allLayers, fmt.Sprintf(\"%s\", gotLayers))\n+ errs = multierr.Combine(errs, &layersError{got: gotLayers, want: conn.incoming(gotLayers)})\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"github.com/google/go-cmp/cmp\"\n\"github.com/google/go-cmp/cmp/cmpopts\"\n+ \"go.uber.org/multierr\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -720,3 +721,247 @@ func (ls *Layers) match(other Layers) bool {\n}\nreturn true\n}\n+\n+// layerDiff stores the diffs for each field along with the label for the Layer.\n+// If rows is nil, that means that there was no diff.\n+type layerDiff struct {\n+ label string\n+ rows []layerDiffRow\n+}\n+\n+// layerDiffRow stores the fields and corresponding values for two got and want\n+// layers. If the value was nil then the string stored is the empty string.\n+type layerDiffRow struct {\n+ field, got, want string\n+}\n+\n+// diffLayer extracts all differing fields between two layers.\n+func diffLayer(got, want Layer) []layerDiffRow {\n+ vGot := reflect.ValueOf(got).Elem()\n+ vWant := reflect.ValueOf(want).Elem()\n+ if vGot.Type() != vWant.Type() {\n+ return nil\n+ }\n+ t := vGot.Type()\n+ var result []layerDiffRow\n+ for i := 0; i < t.NumField(); i++ {\n+ t := t.Field(i)\n+ if t.Anonymous {\n+ // Ignore the LayerBase in the Layer struct.\n+ continue\n+ }\n+ vGot := vGot.Field(i)\n+ vWant := vWant.Field(i)\n+ gotString := \"\"\n+ if !vGot.IsNil() {\n+ gotString = fmt.Sprint(reflect.Indirect(vGot))\n+ }\n+ wantString := \"\"\n+ if !vWant.IsNil() {\n+ wantString = fmt.Sprint(reflect.Indirect(vWant))\n+ }\n+ result = append(result, layerDiffRow{t.Name, gotString, wantString})\n+ }\n+ return result\n+}\n+\n+// layerType returns a concise string describing the type of the Layer, like\n+// \"TCP\", or \"IPv6\".\n+func layerType(l Layer) string {\n+ return reflect.TypeOf(l).Elem().Name()\n+}\n+\n+// diff compares Layers and returns a representation of the difference. Each\n+// Layer in the Layers is pairwise compared. If an element in either is nil, it\n+// is considered a match with the other Layer. If two Layers have differing\n+// types, they don't match regardless of the contents. If two Layers have the\n+// same type then the fields in the Layer are pairwise compared. Fields that are\n+// nil always match. Two non-nil fields only match if they point to equal\n+// values. diff returns an empty string if and only if *ls and other match.\n+func (ls *Layers) diff(other Layers) string {\n+ var allDiffs []layerDiff\n+ // Check the cases where one list is longer than the other, where one or both\n+ // elements are nil, where the sides have different types, and where the sides\n+ // have the same type.\n+ for i := 0; i < len(*ls) || i < len(other); i++ {\n+ if i >= len(*ls) {\n+ // Matching ls against other where other is longer than ls. missing\n+ // matches everything so we just include a label without any rows. Having\n+ // no rows is a sign that there was no diff.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: \"missing matches \" + layerType(other[i]),\n+ })\n+ continue\n+ }\n+\n+ if i >= len(other) {\n+ // Matching ls against other where ls is longer than other. missing\n+ // matches everything so we just include a label without any rows. Having\n+ // no rows is a sign that there was no diff.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]) + \" matches missing\",\n+ })\n+ continue\n+ }\n+\n+ if (*ls)[i] == nil && other[i] == nil {\n+ // Matching ls against other where both elements are nil. nil matches\n+ // everything so we just include a label without any rows. Having no rows\n+ // is a sign that there was no diff.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: \"nil matches nil\",\n+ })\n+ continue\n+ }\n+\n+ if (*ls)[i] == nil {\n+ // Matching ls against other where the element in ls is nil. nil matches\n+ // everything so we just include a label without any rows. Having no rows\n+ // is a sign that there was no diff.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: \"nil matches \" + layerType(other[i]),\n+ })\n+ continue\n+ }\n+\n+ if other[i] == nil {\n+ // Matching ls against other where the element in other is nil. nil\n+ // matches everything so we just include a label without any rows. Having\n+ // no rows is a sign that there was no diff.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]) + \" matches nil\",\n+ })\n+ continue\n+ }\n+\n+ if reflect.TypeOf((*ls)[i]) == reflect.TypeOf(other[i]) {\n+ // Matching ls against other where both elements have the same type. Match\n+ // each field pairwise and only report a diff if there is a mismatch,\n+ // which is only when both sides are non-nil and have differring values.\n+ diff := diffLayer((*ls)[i], other[i])\n+ var layerDiffRows []layerDiffRow\n+ for _, d := range diff {\n+ if d.got == \"\" || d.want == \"\" || d.got == d.want {\n+ continue\n+ }\n+ layerDiffRows = append(layerDiffRows, layerDiffRow{\n+ d.field,\n+ d.got,\n+ d.want,\n+ })\n+ }\n+ if len(layerDiffRows) > 0 {\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]),\n+ rows: layerDiffRows,\n+ })\n+ } else {\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]) + \" matches \" + layerType(other[i]),\n+ // Having no rows is a sign that there was no diff.\n+ })\n+ }\n+ continue\n+ }\n+ // Neither side is nil and the types are different, so we'll display one\n+ // side then the other.\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]) + \" doesn't match \" + layerType(other[i]),\n+ })\n+ diff := diffLayer((*ls)[i], (*ls)[i])\n+ layerDiffRows := []layerDiffRow{}\n+ for _, d := range diff {\n+ if len(d.got) == 0 {\n+ continue\n+ }\n+ layerDiffRows = append(layerDiffRows, layerDiffRow{\n+ d.field,\n+ d.got,\n+ \"\",\n+ })\n+ }\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType((*ls)[i]),\n+ rows: layerDiffRows,\n+ })\n+\n+ layerDiffRows = []layerDiffRow{}\n+ diff = diffLayer(other[i], other[i])\n+ for _, d := range diff {\n+ if len(d.want) == 0 {\n+ continue\n+ }\n+ layerDiffRows = append(layerDiffRows, layerDiffRow{\n+ d.field,\n+ \"\",\n+ d.want,\n+ })\n+ }\n+ allDiffs = append(allDiffs, layerDiff{\n+ label: layerType(other[i]),\n+ rows: layerDiffRows,\n+ })\n+ }\n+\n+ output := \"\"\n+ // These are for output formatting.\n+ maxLabelLen, maxFieldLen, maxGotLen, maxWantLen := 0, 0, 0, 0\n+ foundOne := false\n+ for _, l := range allDiffs {\n+ if len(l.label) > maxLabelLen && len(l.rows) > 0 {\n+ maxLabelLen = len(l.label)\n+ }\n+ if l.rows != nil {\n+ foundOne = true\n+ }\n+ for _, r := range l.rows {\n+ if len(r.field) > maxFieldLen {\n+ maxFieldLen = len(r.field)\n+ }\n+ if l := len(fmt.Sprint(r.got)); l > maxGotLen {\n+ maxGotLen = l\n+ }\n+ if l := len(fmt.Sprint(r.want)); l > maxWantLen {\n+ maxWantLen = l\n+ }\n+ }\n+ }\n+ if !foundOne {\n+ return \"\"\n+ }\n+ for _, l := range allDiffs {\n+ if len(l.rows) == 0 {\n+ output += \"(\" + l.label + \")\\n\"\n+ continue\n+ }\n+ for i, r := range l.rows {\n+ var label string\n+ if i == 0 {\n+ label = l.label + \":\"\n+ }\n+ output += fmt.Sprintf(\n+ \"%*s %*s %*v %*v\\n\",\n+ maxLabelLen+1, label,\n+ maxFieldLen+1, r.field+\":\",\n+ maxGotLen, r.got,\n+ maxWantLen, r.want,\n+ )\n+ }\n+ }\n+ return output\n+}\n+\n+// merge merges the other Layers into ls. If the other Layers is longer, those\n+// additional Layer structs are added to ls. The errors from merging are\n+// collected and returned.\n+func (ls *Layers) merge(other Layers) error {\n+ var errs error\n+ for i, o := range other {\n+ if i < len(*ls) {\n+ errs = multierr.Combine(errs, (*ls)[i].merge(o))\n+ } else {\n+ *ls = append(*ls, o)\n+ }\n+ }\n+ return errs\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers_test.go",
"new_path": "test/packetimpact/testbench/layers_test.go",
"diff": "@@ -313,3 +313,83 @@ func TestConnectionMatch(t *testing.T) {\n})\n}\n}\n+\n+func TestLayersDiff(t *testing.T) {\n+ for _, tt := range []struct {\n+ x, y Layers\n+ want string\n+ }{\n+ {\n+ Layers{&Ether{Type: NetworkProtocolNumber(12)}, &TCP{DataOffset: Uint8(5), SeqNum: Uint32(5)}},\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ \"Ether: Type: 12 13\\n\" +\n+ \" TCP: SeqNum: 5 6\\n\" +\n+ \" DataOffset: 5 7\\n\",\n+ },\n+ {\n+ Layers{&Ether{Type: NetworkProtocolNumber(12)}, &UDP{SrcPort: Uint16(123)}},\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ \"Ether: Type: 12 13\\n\" +\n+ \"(UDP doesn't match TCP)\\n\" +\n+ \" UDP: SrcPort: 123 \\n\" +\n+ \" TCP: SeqNum: 6\\n\" +\n+ \" DataOffset: 7\\n\",\n+ },\n+ {\n+ Layers{&UDP{SrcPort: Uint16(123)}},\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ \"(UDP doesn't match Ether)\\n\" +\n+ \" UDP: SrcPort: 123 \\n\" +\n+ \"Ether: Type: 13\\n\" +\n+ \"(missing matches TCP)\\n\",\n+ },\n+ {\n+ Layers{nil, &UDP{SrcPort: Uint16(123)}},\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ \"(nil matches Ether)\\n\" +\n+ \"(UDP doesn't match TCP)\\n\" +\n+ \"UDP: SrcPort: 123 \\n\" +\n+ \"TCP: SeqNum: 6\\n\" +\n+ \" DataOffset: 7\\n\",\n+ },\n+ {\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &IPv4{IHL: Uint8(4)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ Layers{&Ether{Type: NetworkProtocolNumber(13)}, &IPv4{IHL: Uint8(6)}, &TCP{DataOffset: Uint8(7), SeqNum: Uint32(6)}},\n+ \"(Ether matches Ether)\\n\" +\n+ \"IPv4: IHL: 4 6\\n\" +\n+ \"(TCP matches TCP)\\n\",\n+ },\n+ {\n+ Layers{&Payload{Bytes: []byte(\"foo\")}},\n+ Layers{&Payload{Bytes: []byte(\"bar\")}},\n+ \"Payload: Bytes: [102 111 111] [98 97 114]\\n\",\n+ },\n+ {\n+ Layers{&Payload{Bytes: []byte(\"\")}},\n+ Layers{&Payload{}},\n+ \"\",\n+ },\n+ {\n+ Layers{&Payload{Bytes: []byte(\"\")}},\n+ Layers{&Payload{Bytes: []byte(\"\")}},\n+ \"\",\n+ },\n+ {\n+ Layers{&UDP{}},\n+ Layers{&TCP{}},\n+ \"(UDP doesn't match TCP)\\n\" +\n+ \"(UDP)\\n\" +\n+ \"(TCP)\\n\",\n+ },\n+ } {\n+ if got := tt.x.diff(tt.y); got != tt.want {\n+ t.Errorf(\"%s.diff(%s) = %q, want %q\", tt.x, tt.y, got, tt.want)\n+ }\n+ if tt.x.match(tt.y) != (tt.x.diff(tt.y) == \"\") {\n+ t.Errorf(\"match and diff of %s and %s disagree\", tt.x, tt.y)\n+ }\n+ if tt.y.match(tt.x) != (tt.y.diff(tt.x) == \"\") {\n+ t.Errorf(\"match and diff of %s and %s disagree\", tt.y, tt.x)\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/fin_wait2_timeout_test.go",
"new_path": "test/packetimpact/tests/fin_wait2_timeout_test.go",
"diff": "@@ -61,8 +61,8 @@ func TestFinWait2Timeout(t *testing.T) {\nt.Fatalf(\"expected a RST packet within a second but got none: %s\", err)\n}\n} else {\n- if _, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, 10*time.Second); err == nil {\n- t.Fatalf(\"expected no RST packets within ten seconds but got one: %s\", err)\n+ if got, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagRst)}, 10*time.Second); got != nil || err == nil {\n+ t.Fatalf(\"expected no RST packets within ten seconds but got one: %s\", got)\n}\n}\n})\n"
}
] | Go | Apache License 2.0 | google/gvisor | Better error message from ExpectFrame
Display the errors as diffs between the expected and wanted frame.
PiperOrigin-RevId: 308333271 |
259,972 | 24.04.2020 15:55:11 | 25,200 | dfff265fe422499af3bbe7d58e8db35ba32304f5 | Add ICMP6 param problem test
Tested:
When run on Linux, a correct ICMPv6 response is received. On netstack, no
ICMPv6 response is received. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/ipv6.go",
"new_path": "pkg/tcpip/header/ipv6.go",
"diff": "@@ -27,7 +27,9 @@ const (\n// IPv6PayloadLenOffset is the offset of the PayloadLength field in\n// IPv6 header.\nIPv6PayloadLenOffset = 4\n- nextHdr = 6\n+ // IPv6NextHeaderOffset is the offset of the NextHeader field in\n+ // IPv6 header.\n+ IPv6NextHeaderOffset = 6\nhopLimit = 7\nv6SrcAddr = 8\nv6DstAddr = v6SrcAddr + IPv6AddressSize\n@@ -163,7 +165,7 @@ func (b IPv6) HopLimit() uint8 {\n// NextHeader returns the value of the \"next header\" field of the ipv6 header.\nfunc (b IPv6) NextHeader() uint8 {\n- return b[nextHdr]\n+ return b[IPv6NextHeaderOffset]\n}\n// TransportProtocol implements Network.TransportProtocol.\n@@ -223,7 +225,7 @@ func (b IPv6) SetDestinationAddress(addr tcpip.Address) {\n// SetNextHeader sets the value of the \"next header\" field of the ipv6 header.\nfunc (b IPv6) SetNextHeader(v uint8) {\n- b[nextHdr] = v\n+ b[IPv6NextHeaderOffset] = v\n}\n// SetChecksum implements Network.SetChecksum. Given that IPv6 doesn't have a\n@@ -235,7 +237,7 @@ func (IPv6) SetChecksum(uint16) {\nfunc (b IPv6) Encode(i *IPv6Fields) {\nb.SetTOS(i.TrafficClass, i.FlowLabel)\nb.SetPayloadLength(i.PayloadLength)\n- b[nextHdr] = i.NextHeader\n+ b[IPv6NextHeaderOffset] = i.NextHeader\nb[hopLimit] = i.HopLimit\nb.SetSourceAddress(i.SrcAddr)\nb.SetDestinationAddress(i.DstAddr)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/connections.go",
"new_path": "test/packetimpact/testbench/connections.go",
"diff": "@@ -34,33 +34,60 @@ import (\nvar localIPv4 = flag.String(\"local_ipv4\", \"\", \"local IPv4 address for test packets\")\nvar remoteIPv4 = flag.String(\"remote_ipv4\", \"\", \"remote IPv4 address for test packets\")\n+var localIPv6 = flag.String(\"local_ipv6\", \"\", \"local IPv6 address for test packets\")\n+var remoteIPv6 = flag.String(\"remote_ipv6\", \"\", \"remote IPv6 address for test packets\")\nvar localMAC = flag.String(\"local_mac\", \"\", \"local mac address for test packets\")\nvar remoteMAC = flag.String(\"remote_mac\", \"\", \"remote mac address for test packets\")\n-// pickPort makes a new socket and returns the socket FD and port. The caller\n-// must close the FD when done with the port if there is no error.\n-func pickPort() (int, uint16, error) {\n- fd, err := unix.Socket(unix.AF_INET, unix.SOCK_STREAM, 0)\n+// pickPort makes a new socket and returns the socket FD and port. The domain\n+// should be AF_INET or AF_INET6. The caller must close the FD when done with\n+// the port if there is no error.\n+func pickPort(domain, typ int) (fd int, port uint16, err error) {\n+ fd, err = unix.Socket(domain, typ, 0)\nif err != nil {\nreturn -1, 0, err\n}\n- var sa unix.SockaddrInet4\n- copy(sa.Addr[0:4], net.ParseIP(*localIPv4).To4())\n- if err := unix.Bind(fd, &sa); err != nil {\n- unix.Close(fd)\n+ defer func() {\n+ if err != nil {\n+ err = multierr.Append(err, unix.Close(fd))\n+ }\n+ }()\n+ var sa unix.Sockaddr\n+ switch domain {\n+ case unix.AF_INET:\n+ var sa4 unix.SockaddrInet4\n+ copy(sa4.Addr[:], net.ParseIP(*localIPv4).To4())\n+ sa = &sa4\n+ case unix.AF_INET6:\n+ var sa6 unix.SockaddrInet6\n+ copy(sa6.Addr[:], net.ParseIP(*localIPv6).To16())\n+ sa = &sa6\n+ default:\n+ return -1, 0, fmt.Errorf(\"invalid domain %d, it should be one of unix.AF_INET or unix.AF_INET6\", domain)\n+ }\n+ if err = unix.Bind(fd, sa); err != nil {\nreturn -1, 0, err\n}\nnewSockAddr, err := unix.Getsockname(fd)\nif err != nil {\n- unix.Close(fd)\nreturn -1, 0, err\n}\n+ switch domain {\n+ case unix.AF_INET:\nnewSockAddrInet4, ok := newSockAddr.(*unix.SockaddrInet4)\nif !ok {\n- unix.Close(fd)\n- return -1, 0, fmt.Errorf(\"can't cast Getsockname result to SockaddrInet4\")\n+ return -1, 0, fmt.Errorf(\"can't cast Getsockname result %T to SockaddrInet4\", newSockAddr)\n}\nreturn fd, uint16(newSockAddrInet4.Port), nil\n+ case unix.AF_INET6:\n+ newSockAddrInet6, ok := newSockAddr.(*unix.SockaddrInet6)\n+ if !ok {\n+ return -1, 0, fmt.Errorf(\"can't cast Getsockname result %T to SockaddrInet6\", newSockAddr)\n+ }\n+ return fd, uint16(newSockAddrInet6.Port), nil\n+ default:\n+ return -1, 0, fmt.Errorf(\"invalid domain %d, it should be one of unix.AF_INET or unix.AF_INET6\", domain)\n+ }\n}\n// layerState stores the state of a layer of a connection.\n@@ -123,7 +150,7 @@ func newEtherState(out, in Ether) (*etherState, error) {\n}\nfunc (s *etherState) outgoing() Layer {\n- return &s.out\n+ return deepcopy.Copy(&s.out).(Layer)\n}\n// incoming implements layerState.incoming.\n@@ -168,7 +195,7 @@ func newIPv4State(out, in IPv4) (*ipv4State, error) {\n}\nfunc (s *ipv4State) outgoing() Layer {\n- return &s.out\n+ return deepcopy.Copy(&s.out).(Layer)\n}\n// incoming implements layerState.incoming.\n@@ -188,6 +215,54 @@ func (*ipv4State) close() error {\nreturn nil\n}\n+// ipv6State maintains state about an IPv6 connection.\n+type ipv6State struct {\n+ out, in IPv6\n+}\n+\n+var _ layerState = (*ipv6State)(nil)\n+\n+// newIPv6State creates a new ipv6State.\n+func newIPv6State(out, in IPv6) (*ipv6State, error) {\n+ lIP := tcpip.Address(net.ParseIP(*localIPv6).To16())\n+ rIP := tcpip.Address(net.ParseIP(*remoteIPv6).To16())\n+ s := ipv6State{\n+ out: IPv6{SrcAddr: &lIP, DstAddr: &rIP},\n+ in: IPv6{SrcAddr: &rIP, DstAddr: &lIP},\n+ }\n+ if err := s.out.merge(&out); err != nil {\n+ return nil, err\n+ }\n+ if err := s.in.merge(&in); err != nil {\n+ return nil, err\n+ }\n+ return &s, nil\n+}\n+\n+// outgoing returns an outgoing layer to be sent in a frame.\n+func (s *ipv6State) outgoing() Layer {\n+ return deepcopy.Copy(&s.out).(Layer)\n+}\n+\n+func (s *ipv6State) incoming(Layer) Layer {\n+ return deepcopy.Copy(&s.in).(Layer)\n+}\n+\n+func (s *ipv6State) sent(Layer) error {\n+ // Nothing to do.\n+ return nil\n+}\n+\n+func (s *ipv6State) received(Layer) error {\n+ // Nothing to do.\n+ return nil\n+}\n+\n+// close cleans up any resources held.\n+func (s *ipv6State) close() error {\n+ return nil\n+}\n+\n// tcpState maintains state about a TCP connection.\ntype tcpState struct {\nout, in TCP\n@@ -206,8 +281,8 @@ func SeqNumValue(v seqnum.Value) *seqnum.Value {\n}\n// newTCPState creates a new TCPState.\n-func newTCPState(out, in TCP) (*tcpState, error) {\n- portPickerFD, localPort, err := pickPort()\n+func newTCPState(domain int, out, in TCP) (*tcpState, error) {\n+ portPickerFD, localPort, err := pickPort(domain, unix.SOCK_STREAM)\nif err != nil {\nreturn nil, err\n}\n@@ -310,8 +385,8 @@ type udpState struct {\nvar _ layerState = (*udpState)(nil)\n// newUDPState creates a new udpState.\n-func newUDPState(out, in UDP) (*udpState, error) {\n- portPickerFD, localPort, err := pickPort()\n+func newUDPState(domain int, out, in UDP) (*udpState, error) {\n+ portPickerFD, localPort, err := pickPort(domain, unix.SOCK_DGRAM)\nif err != nil {\nreturn nil, err\n}\n@@ -330,7 +405,7 @@ func newUDPState(out, in UDP) (*udpState, error) {\n}\nfunc (s *udpState) outgoing() Layer {\n- return &s.out\n+ return deepcopy.Copy(&s.out).(Layer)\n}\n// incoming implements layerState.incoming.\n@@ -422,7 +497,7 @@ func (conn *Connection) CreateFrame(layer Layer, additionalLayers ...Layer) Laye\n// SendFrame sends a frame on the wire and updates the state of all layers.\nfunc (conn *Connection) SendFrame(frame Layers) {\n- outBytes, err := frame.toBytes()\n+ outBytes, err := frame.ToBytes()\nif err != nil {\nconn.t.Fatalf(\"can't build outgoing TCP packet: %s\", err)\n}\n@@ -536,7 +611,7 @@ func NewTCPIPv4(t *testing.T, outgoingTCP, incomingTCP TCP) TCPIPv4 {\nif err != nil {\nt.Fatalf(\"can't make ipv4State: %s\", err)\n}\n- tcpState, err := newTCPState(outgoingTCP, incomingTCP)\n+ tcpState, err := newTCPState(unix.AF_INET, outgoingTCP, incomingTCP)\nif err != nil {\nt.Fatalf(\"can't make tcpState: %s\", err)\n}\n@@ -633,6 +708,59 @@ func (conn *TCPIPv4) SynAck() *TCP {\nreturn conn.state().synAck\n}\n+// IPv6Conn maintains the state for all the layers in a IPv6 connection.\n+type IPv6Conn Connection\n+\n+// NewIPv6Conn creates a new IPv6Conn connection with reasonable defaults.\n+func NewIPv6Conn(t *testing.T, outgoingIPv6, incomingIPv6 IPv6) IPv6Conn {\n+ etherState, err := newEtherState(Ether{}, Ether{})\n+ if err != nil {\n+ t.Fatalf(\"can't make EtherState: %s\", err)\n+ }\n+ ipv6State, err := newIPv6State(outgoingIPv6, incomingIPv6)\n+ if err != nil {\n+ t.Fatalf(\"can't make IPv6State: %s\", err)\n+ }\n+\n+ injector, err := NewInjector(t)\n+ if err != nil {\n+ t.Fatalf(\"can't make injector: %s\", err)\n+ }\n+ sniffer, err := NewSniffer(t)\n+ if err != nil {\n+ t.Fatalf(\"can't make sniffer: %s\", err)\n+ }\n+\n+ return IPv6Conn{\n+ layerStates: []layerState{etherState, ipv6State},\n+ injector: injector,\n+ sniffer: sniffer,\n+ t: t,\n+ }\n+}\n+\n+// SendFrame sends a frame on the wire and updates the state of all layers.\n+func (conn *IPv6Conn) SendFrame(frame Layers) {\n+ (*Connection)(conn).SendFrame(frame)\n+}\n+\n+// CreateFrame builds a frame for the connection with ipv6 overriding the ipv6\n+// layer defaults and additionalLayers added after it.\n+func (conn *IPv6Conn) CreateFrame(ipv6 IPv6, additionalLayers ...Layer) Layers {\n+ return (*Connection)(conn).CreateFrame(&ipv6, additionalLayers...)\n+}\n+\n+// Close to clean up any resources held.\n+func (conn *IPv6Conn) Close() {\n+ (*Connection)(conn).Close()\n+}\n+\n+// ExpectFrame expects a frame that matches the provided Layers within the\n+// timeout specified. If it doesn't arrive in time, it returns nil.\n+func (conn *IPv6Conn) ExpectFrame(frame Layers, timeout time.Duration) (Layers, error) {\n+ return (*Connection)(conn).ExpectFrame(frame, timeout)\n+}\n+\n// Drain drains the sniffer's receive buffer by receiving packets until there's\n// nothing else to receive.\nfunc (conn *TCPIPv4) Drain() {\n@@ -652,7 +780,7 @@ func NewUDPIPv4(t *testing.T, outgoingUDP, incomingUDP UDP) UDPIPv4 {\nif err != nil {\nt.Fatalf(\"can't make ipv4State: %s\", err)\n}\n- tcpState, err := newUDPState(outgoingUDP, incomingUDP)\n+ tcpState, err := newUDPState(unix.AF_INET, outgoingUDP, incomingUDP)\nif err != nil {\nt.Fatalf(\"can't make udpState: %s\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -36,14 +36,14 @@ import (\ntype Layer interface {\nfmt.Stringer\n- // toBytes converts the Layer into bytes. In places where the Layer's field\n+ // ToBytes converts the Layer into bytes. In places where the Layer's field\n// isn't nil, the value that is pointed to is used. When the field is nil, a\n// reasonable default for the Layer is used. For example, \"64\" for IPv4 TTL\n// and a calculated checksum for TCP or IP. Some layers require information\n// from the previous or next layers in order to compute a default, such as\n// TCP's checksum or Ethernet's type, so each Layer has a doubly-linked list\n// to the layer's neighbors.\n- toBytes() ([]byte, error)\n+ ToBytes() ([]byte, error)\n// match checks if the current Layer matches the provided Layer. If either\n// Layer has a nil in a given field, that field is considered matching.\n@@ -174,7 +174,8 @@ func (l *Ether) String() string {\nreturn stringLayer(l)\n}\n-func (l *Ether) toBytes() ([]byte, error) {\n+// ToBytes implements Layer.ToBytes.\n+func (l *Ether) ToBytes() ([]byte, error) {\nb := make([]byte, header.EthernetMinimumSize)\nh := header.Ethernet(b)\nfields := &header.EthernetFields{}\n@@ -190,8 +191,9 @@ func (l *Ether) toBytes() ([]byte, error) {\nswitch n := l.next().(type) {\ncase *IPv4:\nfields.Type = header.IPv4ProtocolNumber\n+ case *IPv6:\n+ fields.Type = header.IPv6ProtocolNumber\ndefault:\n- // TODO(b/150301488): Support more protocols, like IPv6.\nreturn nil, fmt.Errorf(\"ethernet header's next layer is unrecognized: %#v\", n)\n}\n}\n@@ -246,6 +248,8 @@ func parseEther(b []byte) (Layer, layerParser) {\nswitch h.Type() {\ncase header.IPv4ProtocolNumber:\nnextParser = parseIPv4\n+ case header.IPv6ProtocolNumber:\n+ nextParser = parseIPv6\ndefault:\n// Assume that the rest is a payload.\nnextParser = parsePayload\n@@ -286,7 +290,8 @@ func (l *IPv4) String() string {\nreturn stringLayer(l)\n}\n-func (l *IPv4) toBytes() ([]byte, error) {\n+// ToBytes implements Layer.ToBytes.\n+func (l *IPv4) ToBytes() ([]byte, error) {\nb := make([]byte, header.IPv4MinimumSize)\nh := header.IPv4(b)\nfields := &header.IPv4Fields{\n@@ -421,6 +426,186 @@ func (l *IPv4) merge(other Layer) error {\nreturn mergeLayer(l, other)\n}\n+// IPv6 can construct and match an IPv6 encapsulation.\n+type IPv6 struct {\n+ LayerBase\n+ TrafficClass *uint8\n+ FlowLabel *uint32\n+ PayloadLength *uint16\n+ NextHeader *uint8\n+ HopLimit *uint8\n+ SrcAddr *tcpip.Address\n+ DstAddr *tcpip.Address\n+}\n+\n+func (l *IPv6) String() string {\n+ return stringLayer(l)\n+}\n+\n+// ToBytes implements Layer.ToBytes.\n+func (l *IPv6) ToBytes() ([]byte, error) {\n+ b := make([]byte, header.IPv6MinimumSize)\n+ h := header.IPv6(b)\n+ fields := &header.IPv6Fields{\n+ HopLimit: 64,\n+ }\n+ if l.TrafficClass != nil {\n+ fields.TrafficClass = *l.TrafficClass\n+ }\n+ if l.FlowLabel != nil {\n+ fields.FlowLabel = *l.FlowLabel\n+ }\n+ if l.PayloadLength != nil {\n+ fields.PayloadLength = *l.PayloadLength\n+ } else {\n+ for current := l.next(); current != nil; current = current.next() {\n+ fields.PayloadLength += uint16(current.length())\n+ }\n+ }\n+ if l.NextHeader != nil {\n+ fields.NextHeader = *l.NextHeader\n+ } else {\n+ switch n := l.next().(type) {\n+ case *TCP:\n+ fields.NextHeader = uint8(header.TCPProtocolNumber)\n+ case *UDP:\n+ fields.NextHeader = uint8(header.UDPProtocolNumber)\n+ case *ICMPv6:\n+ fields.NextHeader = uint8(header.ICMPv6ProtocolNumber)\n+ default:\n+ // TODO(b/150301488): Support more protocols as needed.\n+ return nil, fmt.Errorf(\"ToBytes can't deduce the IPv6 header's next protocol: %#v\", n)\n+ }\n+ }\n+ if l.HopLimit != nil {\n+ fields.HopLimit = *l.HopLimit\n+ }\n+ if l.SrcAddr != nil {\n+ fields.SrcAddr = *l.SrcAddr\n+ }\n+ if l.DstAddr != nil {\n+ fields.DstAddr = *l.DstAddr\n+ }\n+ h.Encode(fields)\n+ return h, nil\n+}\n+\n+// parseIPv6 parses the bytes assuming that they start with an ipv6 header and\n+// continues parsing further encapsulations.\n+func parseIPv6(b []byte) (Layer, layerParser) {\n+ h := header.IPv6(b)\n+ tos, flowLabel := h.TOS()\n+ ipv6 := IPv6{\n+ TrafficClass: &tos,\n+ FlowLabel: &flowLabel,\n+ PayloadLength: Uint16(h.PayloadLength()),\n+ NextHeader: Uint8(h.NextHeader()),\n+ HopLimit: Uint8(h.HopLimit()),\n+ SrcAddr: Address(h.SourceAddress()),\n+ DstAddr: Address(h.DestinationAddress()),\n+ }\n+ var nextParser layerParser\n+ switch h.TransportProtocol() {\n+ case header.TCPProtocolNumber:\n+ nextParser = parseTCP\n+ case header.UDPProtocolNumber:\n+ nextParser = parseUDP\n+ case header.ICMPv6ProtocolNumber:\n+ nextParser = parseICMPv6\n+ default:\n+ // Assume that the rest is a payload.\n+ nextParser = parsePayload\n+ }\n+ return &ipv6, nextParser\n+}\n+\n+func (l *IPv6) match(other Layer) bool {\n+ return equalLayer(l, other)\n+}\n+\n+func (l *IPv6) length() int {\n+ return header.IPv6MinimumSize\n+}\n+\n+// merge overrides the values in l with the values from other but only in fields\n+// where the value is not nil.\n+func (l *IPv6) merge(other Layer) error {\n+ return mergeLayer(l, other)\n+}\n+\n+// ICMPv6 can construct and match an ICMPv6 encapsulation.\n+type ICMPv6 struct {\n+ LayerBase\n+ Type *header.ICMPv6Type\n+ Code *byte\n+ Checksum *uint16\n+ NDPPayload []byte\n+}\n+\n+func (l *ICMPv6) String() string {\n+ // TODO(eyalsoha): Do something smarter here when *l.Type is ParameterProblem?\n+ // We could parse the contents of the Payload as if it were an IPv6 packet.\n+ return stringLayer(l)\n+}\n+\n+// ToBytes implements Layer.ToBytes.\n+func (l *ICMPv6) ToBytes() ([]byte, error) {\n+ b := make([]byte, header.ICMPv6HeaderSize+len(l.NDPPayload))\n+ h := header.ICMPv6(b)\n+ if l.Type != nil {\n+ h.SetType(*l.Type)\n+ }\n+ if l.Code != nil {\n+ h.SetCode(*l.Code)\n+ }\n+ copy(h.NDPPayload(), l.NDPPayload)\n+ if l.Checksum != nil {\n+ h.SetChecksum(*l.Checksum)\n+ } else {\n+ ipv6 := l.prev().(*IPv6)\n+ h.SetChecksum(header.ICMPv6Checksum(h, *ipv6.SrcAddr, *ipv6.DstAddr, buffer.VectorisedView{}))\n+ }\n+ return h, nil\n+}\n+\n+// ICMPv6Type is a helper routine that allocates a new ICMPv6Type value to store\n+// v and returns a pointer to it.\n+func ICMPv6Type(v header.ICMPv6Type) *header.ICMPv6Type {\n+ return &v\n+}\n+\n+// Byte is a helper routine that allocates a new byte value to store\n+// v and returns a pointer to it.\n+func Byte(v byte) *byte {\n+ return &v\n+}\n+\n+// parseICMPv6 parses the bytes assuming that they start with an ICMPv6 header.\n+func parseICMPv6(b []byte) (Layer, layerParser) {\n+ h := header.ICMPv6(b)\n+ icmpv6 := ICMPv6{\n+ Type: ICMPv6Type(h.Type()),\n+ Code: Byte(h.Code()),\n+ Checksum: Uint16(h.Checksum()),\n+ NDPPayload: h.NDPPayload(),\n+ }\n+ return &icmpv6, nil\n+}\n+\n+func (l *ICMPv6) match(other Layer) bool {\n+ return equalLayer(l, other)\n+}\n+\n+func (l *ICMPv6) length() int {\n+ return header.ICMPv6HeaderSize + len(l.NDPPayload)\n+}\n+\n+// merge overrides the values in l with the values from other but only in fields\n+// where the value is not nil.\n+func (l *ICMPv6) merge(other Layer) error {\n+ return mergeLayer(l, other)\n+}\n+\n// TCP can construct and match a TCP encapsulation.\ntype TCP struct {\nLayerBase\n@@ -439,7 +624,8 @@ func (l *TCP) String() string {\nreturn stringLayer(l)\n}\n-func (l *TCP) toBytes() ([]byte, error) {\n+// ToBytes implements Layer.ToBytes.\n+func (l *TCP) ToBytes() ([]byte, error) {\nb := make([]byte, header.TCPMinimumSize)\nh := header.TCP(b)\nif l.SrcPort != nil {\n@@ -504,7 +690,7 @@ func layerChecksum(l Layer, protoNumber tcpip.TransportProtocolNumber) (uint16,\n}\nvar payloadBytes buffer.VectorisedView\nfor current := l.next(); current != nil; current = current.next() {\n- payload, err := current.toBytes()\n+ payload, err := current.ToBytes()\nif err != nil {\nreturn 0, fmt.Errorf(\"can't get bytes for next header: %s\", payload)\n}\n@@ -578,7 +764,8 @@ func (l *UDP) String() string {\nreturn stringLayer(l)\n}\n-func (l *UDP) toBytes() ([]byte, error) {\n+// ToBytes implements Layer.ToBytes.\n+func (l *UDP) ToBytes() ([]byte, error) {\nb := make([]byte, header.UDPMinimumSize)\nh := header.UDP(b)\nif l.SrcPort != nil {\n@@ -661,7 +848,8 @@ func parsePayload(b []byte) (Layer, layerParser) {\nreturn &payload, nil\n}\n-func (l *Payload) toBytes() ([]byte, error) {\n+// ToBytes implements Layer.ToBytes.\n+func (l *Payload) ToBytes() ([]byte, error) {\nreturn l.Bytes, nil\n}\n@@ -697,11 +885,13 @@ func (ls *Layers) linkLayers() {\n}\n}\n-func (ls *Layers) toBytes() ([]byte, error) {\n+// ToBytes converts the Layers into bytes. It creates a linked list of the Layer\n+// structs and then concatentates the output of ToBytes on each Layer.\n+func (ls *Layers) ToBytes() ([]byte, error) {\nls.linkLayers()\noutBytes := []byte{}\nfor _, l := range *ls {\n- layerBytes, err := l.toBytes()\n+ layerBytes, err := l.ToBytes()\nif err != nil {\nreturn nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -96,6 +96,19 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"icmpv6_param_problem\",\n+ srcs = [\"icmpv6_param_problem_test.go\"],\n+ # TODO(b/153485026): Fix netstack then remove the line below.\n+ netstack = False,\n+ deps = [\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/header\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\nsh_binary(\nname = \"test_runner\",\nsrcs = [\"test_runner.sh\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetimpact/tests/icmpv6_param_problem_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 icmpv6_param_problem_test\n+\n+import (\n+ \"encoding/binary\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+// TestICMPv6ParamProblemTest sends a packet with a bad next header. The DUT\n+// should respond with an ICMPv6 Parameter Problem message.\n+func TestICMPv6ParamProblemTest(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ conn := tb.NewIPv6Conn(t, tb.IPv6{}, tb.IPv6{})\n+ defer conn.Close()\n+ ipv6 := tb.IPv6{\n+ // 254 is reserved and used for experimentation and testing. This should\n+ // cause an error.\n+ NextHeader: tb.Uint8(254),\n+ }\n+ icmpv6 := tb.ICMPv6{\n+ Type: tb.ICMPv6Type(header.ICMPv6EchoRequest),\n+ NDPPayload: []byte(\"hello world\"),\n+ }\n+\n+ toSend := conn.CreateFrame(ipv6, &icmpv6)\n+ conn.SendFrame(toSend)\n+\n+ // Build the expected ICMPv6 payload, which includes an index to the\n+ // problematic byte and also the problematic packet as described in\n+ // https://tools.ietf.org/html/rfc4443#page-12 .\n+ ipv6Sent := toSend[1:]\n+ expectedPayload, err := ipv6Sent.ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"can't convert %s to bytes: %s\", ipv6Sent, err)\n+ }\n+\n+ // The problematic field is the NextHeader.\n+ b := make([]byte, 4)\n+ binary.BigEndian.PutUint32(b, header.IPv6NextHeaderOffset)\n+ expectedPayload = append(b, expectedPayload...)\n+ expectedICMPv6 := tb.ICMPv6{\n+ Type: tb.ICMPv6Type(header.ICMPv6ParamProblem),\n+ NDPPayload: expectedPayload,\n+ }\n+\n+ paramProblem := tb.Layers{\n+ &tb.Ether{},\n+ &tb.IPv6{},\n+ &expectedICMPv6,\n+ }\n+ timeout := time.Second\n+ if _, err := conn.ExpectFrame(paramProblem, timeout); err != nil {\n+ t.Errorf(\"expected %s within %s but got none: %s\", paramProblem, timeout, err)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/test_runner.sh",
"new_path": "test/packetimpact/tests/test_runner.sh",
"diff": "@@ -192,6 +192,8 @@ docker pull \"${IMAGE_TAG}\"\n# Create the DUT container and connect to network.\nDUT=$(docker create ${RUNTIME_ARG} --privileged --rm \\\n+ --cap-add NET_ADMIN \\\n+ --sysctl net.ipv6.conf.all.disable_ipv6=0 \\\n--stop-timeout ${TIMEOUT} -it ${IMAGE_TAG})\ndocker network connect \"${CTRL_NET}\" \\\n--ip \"${CTRL_NET_PREFIX}${DUT_NET_SUFFIX}\" \"${DUT}\" \\\n@@ -203,6 +205,8 @@ docker start \"${DUT}\"\n# Create the test bench container and connect to network.\nTESTBENCH=$(docker create --privileged --rm \\\n+ --cap-add NET_ADMIN \\\n+ --sysctl net.ipv6.conf.all.disable_ipv6=0 \\\n--stop-timeout ${TIMEOUT} -it ${IMAGE_TAG})\ndocker network connect \"${CTRL_NET}\" \\\n--ip \"${CTRL_NET_PREFIX}${TESTBENCH_NET_SUFFIX}\" \"${TESTBENCH}\" \\\n@@ -237,6 +241,32 @@ declare -r REMOTE_MAC=$(docker exec -t \"${DUT}\" ip link show \\\n\"${TEST_DEVICE}\" | tail -1 | cut -d' ' -f6)\ndeclare -r LOCAL_MAC=$(docker exec -t \"${TESTBENCH}\" ip link show \\\n\"${TEST_DEVICE}\" | tail -1 | cut -d' ' -f6)\n+declare REMOTE_IPV6=$(docker exec -t \"${DUT}\" ip addr show scope link \\\n+ \"${TEST_DEVICE}\" | grep inet6 | cut -d' ' -f6 | cut -d'/' -f1)\n+declare -r LOCAL_IPV6=$(docker exec -t \"${TESTBENCH}\" ip addr show scope link \\\n+ \"${TEST_DEVICE}\" | grep inet6 | cut -d' ' -f6 | cut -d'/' -f1)\n+\n+# Netstack as DUT doesn't assign IPv6 addresses automatically so do it if\n+# needed. Convert the MAC address to an IPv6 link local address as described in\n+# RFC 4291 page 20: https://tools.ietf.org/html/rfc4291#page-20\n+if [[ -z \"${REMOTE_IPV6}\" ]]; then\n+ # Split the octets of the MAC into an array of strings.\n+ IFS=\":\" read -a REMOTE_OCTETS <<< \"${REMOTE_MAC}\"\n+ # Flip the global bit.\n+ REMOTE_OCTETS[0]=$(printf '%x' \"$((0x${REMOTE_OCTETS[0]} ^ 2))\")\n+ # Add the IPv6 address.\n+ docker exec \"${DUT}\" \\\n+ ip addr add $(printf 'fe80::%02x%02x:%02xff:fe%02x:%02x%02x/64' \\\n+ \"0x${REMOTE_OCTETS[0]}\" \"0x${REMOTE_OCTETS[1]}\" \"0x${REMOTE_OCTETS[2]}\" \\\n+ \"0x${REMOTE_OCTETS[3]}\" \"0x${REMOTE_OCTETS[4]}\" \"0x${REMOTE_OCTETS[5]}\") \\\n+ scope link \\\n+ dev \"${TEST_DEVICE}\"\n+ # Re-extract the IPv6 address.\n+ # TODO(eyalsoha): Add \"scope link\" below when netstack supports correctly\n+ # creating link-local IPv6 addresses.\n+ REMOTE_IPV6=$(docker exec -t \"${DUT}\" ip addr show \\\n+ \"${TEST_DEVICE}\" | grep inet6 | cut -d' ' -f6 | cut -d'/' -f1)\n+fi\ndeclare -r DOCKER_TESTBENCH_BINARY=\"/$(basename ${TESTBENCH_BINARY})\"\ndocker cp -L \"${TESTBENCH_BINARY}\" \"${TESTBENCH}:${DOCKER_TESTBENCH_BINARY}\"\n@@ -245,7 +275,10 @@ if [[ -z \"${TSHARK-}\" ]]; then\n# Run tcpdump in the test bench unbuffered, without dns resolution, just on\n# the interface with the test packets.\ndocker exec -t \"${TESTBENCH}\" \\\n- tcpdump -S -vvv -U -n -i \"${TEST_DEVICE}\" net \"${TEST_NET_PREFIX}/24\" &\n+ tcpdump -S -vvv -U -n -i \"${TEST_DEVICE}\" \\\n+ net \"${TEST_NET_PREFIX}/24\" or \\\n+ host \"${REMOTE_IPV6}\" or \\\n+ host \"${LOCAL_IPV6}\" &\nelse\n# Run tshark in the test bench unbuffered, without dns resolution, just on the\n# interface with the test packets.\n@@ -253,7 +286,9 @@ else\ntshark -V -l -n -i \"${TEST_DEVICE}\" \\\n-o tcp.check_checksum:TRUE \\\n-o udp.check_checksum:TRUE \\\n- host \"${TEST_NET_PREFIX}${TESTBENCH_NET_SUFFIX}\" &\n+ net \"${TEST_NET_PREFIX}/24\" or \\\n+ host \"${REMOTE_IPV6}\" or \\\n+ host \"${LOCAL_IPV6}\" &\nfi\n# tcpdump and tshark take time to startup\n@@ -272,6 +307,8 @@ docker exec \\\n--posix_server_port=${CTRL_PORT} \\\n--remote_ipv4=${TEST_NET_PREFIX}${DUT_NET_SUFFIX} \\\n--local_ipv4=${TEST_NET_PREFIX}${TESTBENCH_NET_SUFFIX} \\\n+ --remote_ipv6=${REMOTE_IPV6} \\\n+ --local_ipv6=${LOCAL_IPV6} \\\n--remote_mac=${REMOTE_MAC} \\\n--local_mac=${LOCAL_MAC} \\\n--device=${TEST_DEVICE}\" && true\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add ICMP6 param problem test
Tested:
When run on Linux, a correct ICMPv6 response is received. On netstack, no
ICMPv6 response is received.
PiperOrigin-RevId: 308343113 |
259,992 | 24.04.2020 18:15:26 | 25,200 | 4af39dd1c522f7852312ecbfd3678892fc656322 | Propagate PID limit from OCI to sandbox cgroup
Closes | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -45,13 +45,13 @@ var controllers = map[string]controller{\n\"memory\": &memory{},\n\"net_cls\": &networkClass{},\n\"net_prio\": &networkPrio{},\n+ \"pids\": &pids{},\n// These controllers either don't have anything in the OCI spec or is\n- // irrevalant for a sandbox, e.g. pids.\n+ // irrelevant for a sandbox.\n\"devices\": &noop{},\n\"freezer\": &noop{},\n\"perf_event\": &noop{},\n- \"pids\": &noop{},\n\"systemd\": &noop{},\n}\n@@ -525,3 +525,13 @@ func (*networkPrio) set(spec *specs.LinuxResources, path string) error {\n}\nreturn nil\n}\n+\n+type pids struct{}\n+\n+func (*pids) set(spec *specs.LinuxResources, path string) error {\n+ if spec.Pids == nil {\n+ return nil\n+ }\n+ val := strconv.FormatInt(spec.Pids.Limit, 10)\n+ return setValue(path, \"pids.max\", val)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/root/cgroup_test.go",
"new_path": "test/root/cgroup_test.go",
"diff": "@@ -199,6 +199,12 @@ func TestCgroup(t *testing.T) {\nwant: \"750\",\nskipIfNotFound: true, // blkio groups may not be available.\n},\n+ {\n+ arg: \"--pids-limit=1000\",\n+ ctrl: \"pids\",\n+ file: \"pids.max\",\n+ want: \"1000\",\n+ },\n}\nargs := make([]string, 0, len(attrs))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Propagate PID limit from OCI to sandbox cgroup
Closes #2489
PiperOrigin-RevId: 308362434 |
259,972 | 24.04.2020 19:59:05 | 25,200 | c9199bab927e901947c1647de248433aa3d439fb | More descriptive error message for missing docker image.
Tested:
Ran a packetimpact test after `docker image rm` and examined the message. | [
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/dockerutil.go",
"new_path": "pkg/test/dockerutil/dockerutil.go",
"diff": "@@ -353,7 +353,10 @@ func (d *Docker) run(r RunOpts, command string, p ...string) (string, error) {\n// Create calls 'docker create' with the arguments provided.\nfunc (d *Docker) Create(r RunOpts, args ...string) error {\n- _, err := d.run(r, \"create\", args...)\n+ out, err := d.run(r, \"create\", args...)\n+ if strings.Contains(out, \"Unable to find image\") {\n+ return fmt.Errorf(\"unable to find image, did you remember to `make load-%s`: %w\", r.Image, err)\n+ }\nreturn err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | More descriptive error message for missing docker image.
Tested:
Ran a packetimpact test after `docker image rm` and examined the message.
PiperOrigin-RevId: 308370603 |
259,845 | 20.04.2020 16:46:22 | -32,400 | 93e510e26fca90a90e10a550ce6ca8d7dfa0b55c | fix behavior of `getMountNameAndOptions` when options include either bind or rbind | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -756,6 +756,15 @@ func (c *containerMounter) createRootMount(ctx context.Context, conf *Config) (*\nreturn rootInode, nil\n}\n+func (c *containerMounter) getBindMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool) {\n+ fd := c.fds.remove()\n+ fsName = \"9p\"\n+ opts = p9MountOptions(fd, c.getMountAccessType(m))\n+ // If configured, add overlay to all writable mounts.\n+ useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+ return fsName, opts, useOverlay\n+}\n+\n// getMountNameAndOptions retrieves the fsName, opts, and useOverlay values\n// used for mounts.\nfunc (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool, error) {\n@@ -769,6 +778,13 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\ncase devpts, devtmpfs, proc, sysfs:\nfsName = m.Type\ncase nonefs:\n+ for _, opt := range m.Options {\n+ if opt == \"bind\" || opt == \"rbind\" {\n+ fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\n+ return fsName, opts, useOverlay, nil\n+ }\n+ }\n+\nfsName = sysfs\ncase tmpfs:\nfsName = m.Type\n@@ -778,15 +794,16 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nif err != nil {\nreturn \"\", nil, false, err\n}\n-\ncase bind:\n- fd := c.fds.remove()\n- fsName = \"9p\"\n- opts = p9MountOptions(fd, c.getMountAccessType(m))\n- // If configured, add overlay to all writable mounts.\n- useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n-\n+ fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\ndefault:\n+ for _, opt := range m.Options {\n+ if opt == \"bind\" || opt == \"rbind\" {\n+ fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\n+ return fsName, opts, useOverlay, nil\n+ }\n+ }\n+\nlog.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n}\nreturn fsName, opts, useOverlay, nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | fix behavior of `getMountNameAndOptions` when options include either bind or rbind
Signed-off-by: moricho <[email protected]> |
259,845 | 20.04.2020 17:03:00 | -32,400 | 0b3166f6243472fbb72cc749c57d3a59aa481979 | add bind/rbind options for mount | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/filesystems.go",
"new_path": "pkg/sentry/fs/filesystems.go",
"diff": "@@ -144,6 +144,10 @@ type MountSourceFlags struct {\n// NoExec corresponds to mount(2)'s \"MS_NOEXEC\" and indicates that\n// binaries from this file system can't be executed.\nNoExec bool\n+\n+ // Bind corresponds to mount(2)'s MS_BIND and indicates that\n+ // the filesystem should be bind mounted.\n+ Bind bool\n}\n// GenericMountSourceOptions splits a string containing comma separated tokens of the\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -63,8 +63,13 @@ const (\nnonefs = \"none\"\n)\n+var (\n// tmpfs has some extra supported options that we must pass through.\n-var tmpfsAllowedOptions = []string{\"mode\", \"uid\", \"gid\"}\n+ tmpfsAllowedOptions = []string{\"mode\", \"uid\", \"gid\"}\n+\n+ // filesystems supported on gVisor.\n+ supportedFilesystems = []string{bind, devpts, devtmpfs, proc, sysfs, tmpfs}\n+)\nfunc addOverlay(ctx context.Context, conf *Config, lower *fs.Inode, name string, lowerFlags fs.MountSourceFlags) (*fs.Inode, error) {\n// Upper layer uses the same flags as lower, but it must be read-write.\n@@ -219,6 +224,8 @@ func mountFlags(opts []string) fs.MountSourceFlags {\nmf.NoAtime = true\ncase \"noexec\":\nmf.NoExec = true\n+ case \"bind\", \"rbind\":\n+ mf.Bind = true\ndefault:\nlog.Warningf(\"ignoring unknown mount option %q\", o)\n}\n@@ -230,6 +237,10 @@ func isSupportedMountFlag(fstype, opt string) bool {\nswitch opt {\ncase \"rw\", \"ro\", \"noatime\", \"noexec\":\nreturn true\n+ case \"bind\", \"rbind\":\n+ if fstype == nonefs || !specutils.ContainsStr(supportedFilesystems, fstype) {\n+ return true\n+ }\n}\nif fstype == tmpfs {\nok, err := parseMountOption(opt, tmpfsAllowedOptions...)\n@@ -756,12 +767,14 @@ func (c *containerMounter) createRootMount(ctx context.Context, conf *Config) (*\nreturn rootInode, nil\n}\n+// getBindMountNameAndOptions retrieves the fsName, opts, and useOverlay values\n+// used for bind mounts.\nfunc (c *containerMounter) getBindMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool) {\nfd := c.fds.remove()\n- fsName = \"9p\"\n- opts = p9MountOptions(fd, c.getMountAccessType(m))\n+ fsName := \"9p\"\n+ opts := p9MountOptions(fd, c.getMountAccessType(m))\n// If configured, add overlay to all writable mounts.\n- useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+ useOverlay := conf.Overlay && !mountFlags(m.Options).ReadOnly\nreturn fsName, opts, useOverlay\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | add bind/rbind options for mount
Signed-off-by: moricho <[email protected]> |
259,845 | 22.04.2020 15:04:18 | -32,400 | fc53d6436776d5de052075e98f44417f04ced7e7 | refactor and add test for bindmount | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/filesystems.go",
"new_path": "pkg/sentry/fs/filesystems.go",
"diff": "@@ -144,10 +144,6 @@ type MountSourceFlags struct {\n// NoExec corresponds to mount(2)'s \"MS_NOEXEC\" and indicates that\n// binaries from this file system can't be executed.\nNoExec bool\n-\n- // Bind corresponds to mount(2)'s MS_BIND and indicates that\n- // the filesystem should be bind mounted.\n- Bind bool\n}\n// GenericMountSourceOptions splits a string containing comma separated tokens of the\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -63,13 +63,8 @@ const (\nnonefs = \"none\"\n)\n-var (\n// tmpfs has some extra supported options that we must pass through.\n- tmpfsAllowedOptions = []string{\"mode\", \"uid\", \"gid\"}\n-\n- // filesystems supported on gVisor.\n- supportedFilesystems = []string{bind, devpts, devtmpfs, proc, sysfs, tmpfs}\n-)\n+var tmpfsAllowedOptions = []string{\"mode\", \"uid\", \"gid\"}\nfunc addOverlay(ctx context.Context, conf *Config, lower *fs.Inode, name string, lowerFlags fs.MountSourceFlags) (*fs.Inode, error) {\n// Upper layer uses the same flags as lower, but it must be read-write.\n@@ -225,7 +220,8 @@ func mountFlags(opts []string) fs.MountSourceFlags {\ncase \"noexec\":\nmf.NoExec = true\ncase \"bind\", \"rbind\":\n- mf.Bind = true\n+ // When options include either \"bind\" or \"rbind\",\n+ // it's converted to a 9P mount.\ndefault:\nlog.Warningf(\"ignoring unknown mount option %q\", o)\n}\n@@ -237,10 +233,6 @@ func isSupportedMountFlag(fstype, opt string) bool {\nswitch opt {\ncase \"rw\", \"ro\", \"noatime\", \"noexec\":\nreturn true\n- case \"bind\", \"rbind\":\n- if fstype == nonefs || !specutils.ContainsStr(supportedFilesystems, fstype) {\n- return true\n- }\n}\nif fstype == tmpfs {\nok, err := parseMountOption(opt, tmpfsAllowedOptions...)\n@@ -767,17 +759,6 @@ func (c *containerMounter) createRootMount(ctx context.Context, conf *Config) (*\nreturn rootInode, nil\n}\n-// getBindMountNameAndOptions retrieves the fsName, opts, and useOverlay values\n-// used for bind mounts.\n-func (c *containerMounter) getBindMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool) {\n- fd := c.fds.remove()\n- fsName := \"9p\"\n- opts := p9MountOptions(fd, c.getMountAccessType(m))\n- // If configured, add overlay to all writable mounts.\n- useOverlay := conf.Overlay && !mountFlags(m.Options).ReadOnly\n- return fsName, opts, useOverlay\n-}\n-\n// getMountNameAndOptions retrieves the fsName, opts, and useOverlay values\n// used for mounts.\nfunc (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (string, []string, bool, error) {\n@@ -787,17 +768,20 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nuseOverlay bool\n)\n- switch m.Type {\n- case devpts, devtmpfs, proc, sysfs:\n- fsName = m.Type\n- case nonefs:\nfor _, opt := range m.Options {\n+ // When options include either \"bind\" or \"rbind\", this behaves as\n+ // bind mount even if the mount type is equal to a filesystem supported\n+ // on runsc.\nif opt == \"bind\" || opt == \"rbind\" {\n- fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\n- return fsName, opts, useOverlay, nil\n+ m.Type = bind\n+ break\n}\n}\n+ switch m.Type {\n+ case devpts, devtmpfs, proc, sysfs:\n+ fsName = m.Type\n+ case nonefs:\nfsName = sysfs\ncase tmpfs:\nfsName = m.Type\n@@ -807,16 +791,15 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nif err != nil {\nreturn \"\", nil, false, err\n}\n+\ncase bind:\n- fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\n- default:\n- for _, opt := range m.Options {\n- if opt == \"bind\" || opt == \"rbind\" {\n- fsName, opts, useOverlay = c.getBindMountNameAndOptions(conf, m)\n- return fsName, opts, useOverlay, nil\n- }\n- }\n+ fd := c.fds.remove()\n+ fsName = \"9p\"\n+ opts = p9MountOptions(fd, c.getMountAccessType(m))\n+ // If configured, add overlay to all writable mounts.\n+ useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+ default:\nlog.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n}\nreturn fsName, opts, useOverlay, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1523,6 +1523,28 @@ func TestReadonlyMount(t *testing.T) {\n}\n}\n+func TestBindMountByOption(t *testing.T) {\n+ for _, conf := range configs(t, overlay) {\n+ t.Logf(\"Running test with conf: %+v\", conf)\n+\n+ dir, err := ioutil.TempDir(testutil.TmpDir(), \"bind-mount\")\n+ spec := testutil.NewSpecWithArgs(\"/bin/touch\", path.Join(dir, \"file\"))\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed: %v\", err)\n+ }\n+ spec.Mounts = append(spec.Mounts, specs.Mount{\n+ Destination: dir,\n+ Source: dir,\n+ Type: \"none\",\n+ Options: []string{\"rw\", \"bind\"},\n+ })\n+\n+ if err := run(spec, conf); err != nil {\n+ t.Fatalf(\"error running sandbox: %v\", err)\n+ }\n+ }\n+}\n+\n// TestAbbreviatedIDs checks that runsc supports using abbreviated container\n// IDs in place of full IDs.\nfunc TestAbbreviatedIDs(t *testing.T) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -1394,7 +1394,7 @@ func TestMultiContainerSharedMountUnsupportedOptions(t *testing.T) {\nDestination: \"/mydir/test\",\nSource: \"/some/dir\",\nType: \"tmpfs\",\n- Options: []string{\"rw\", \"rbind\", \"relatime\"},\n+ Options: []string{\"rw\", \"relatime\"},\n}\npodSpec[0].Mounts = append(podSpec[0].Mounts, mnt0)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -311,7 +311,19 @@ func capsFromNames(names []string, skipSet map[linux.Capability]struct{}) (auth.\n// Is9PMount returns true if the given mount can be mounted as an external gofer.\nfunc Is9PMount(m specs.Mount) bool {\n- return m.Type == \"bind\" && m.Source != \"\" && IsSupportedDevMount(m)\n+ var isBind bool\n+ switch m.Type {\n+ case \"bind\":\n+ isBind = true\n+ default:\n+ for _, opt := range m.Options {\n+ if opt == \"bind\" || opt == \"rbind\" {\n+ isBind = true\n+ break\n+ }\n+ }\n+ }\n+ return isBind && m.Source != \"\" && IsSupportedDevMount(m)\n}\n// IsSupportedDevMount returns true if the mount is a supported /dev mount.\n"
}
] | Go | Apache License 2.0 | google/gvisor | refactor and add test for bindmount
Signed-off-by: moricho <[email protected]> |
259,885 | 27.04.2020 07:37:45 | 25,200 | 292f3f99b73fb901ffdd3ad8ac682718e1e8960a | Don't leak vfs.MountNamespace reference if kernel.TaskSet.NewTask fails. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_start.go",
"new_path": "pkg/sentry/kernel/task_start.go",
"diff": "@@ -104,6 +104,9 @@ func (ts *TaskSet) NewTask(cfg *TaskConfig) (*Task, error) {\ncfg.TaskContext.release()\ncfg.FSContext.DecRef()\ncfg.FDTable.DecRef()\n+ if cfg.MountNamespaceVFS2 != nil {\n+ cfg.MountNamespaceVFS2.DecRef()\n+ }\nreturn nil, err\n}\nreturn t, nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't leak vfs.MountNamespace reference if kernel.TaskSet.NewTask fails.
PiperOrigin-RevId: 308617610 |
259,881 | 27.04.2020 11:51:48 | 14,400 | b15d49a1378e1ccdb821570a111f228532b85ced | container: use sighandling package
Use the sighandling package for Container.ForwardSignals, for
consistency with other signal forwarding.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -15,8 +15,10 @@ go_library(\n\"//test:__subpackages__\",\n],\ndeps = [\n+ \"//pkg/abi/linux\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n+ \"//pkg/sentry/sighandling\",\n\"//pkg/sync\",\n\"//runsc/boot\",\n\"//runsc/cgroup\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -22,7 +22,6 @@ import (\n\"io/ioutil\"\n\"os\"\n\"os/exec\"\n- \"os/signal\"\n\"regexp\"\n\"strconv\"\n\"strings\"\n@@ -31,8 +30,10 @@ import (\n\"github.com/cenkalti/backoff\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n+ \"gvisor.dev/gvisor/pkg/sentry/sighandling\"\n\"gvisor.dev/gvisor/runsc/boot\"\n\"gvisor.dev/gvisor/runsc/cgroup\"\n\"gvisor.dev/gvisor/runsc/sandbox\"\n@@ -621,21 +622,15 @@ func (c *Container) SignalProcess(sig syscall.Signal, pid int32) error {\n// forwarding signals.\nfunc (c *Container) ForwardSignals(pid int32, fgProcess bool) func() {\nlog.Debugf(\"Forwarding all signals to container %q PID %d fgProcess=%t\", c.ID, pid, fgProcess)\n- sigCh := make(chan os.Signal, 1)\n- signal.Notify(sigCh)\n- go func() {\n- for s := range sigCh {\n- log.Debugf(\"Forwarding signal %d to container %q PID %d fgProcess=%t\", s, c.ID, pid, fgProcess)\n- if err := c.Sandbox.SignalProcess(c.ID, pid, s.(syscall.Signal), fgProcess); err != nil {\n- log.Warningf(\"error forwarding signal %d to container %q: %v\", s, c.ID, err)\n+ stop := sighandling.StartSignalForwarding(func(sig linux.Signal) {\n+ log.Debugf(\"Forwarding signal %d to container %q PID %d fgProcess=%t\", sig, c.ID, pid, fgProcess)\n+ if err := c.Sandbox.SignalProcess(c.ID, pid, syscall.Signal(sig), fgProcess); err != nil {\n+ log.Warningf(\"error forwarding signal %d to container %q: %v\", sig, c.ID, err)\n}\n- }\n- log.Debugf(\"Done forwarding signals to container %q PID %d fgProcess=%t\", c.ID, pid, fgProcess)\n- }()\n-\n+ })\nreturn func() {\n- signal.Stop(sigCh)\n- close(sigCh)\n+ log.Debugf(\"Done forwarding signals to container %q PID %d fgProcess=%t\", c.ID, pid, fgProcess)\n+ stop()\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | container: use sighandling package
Use the sighandling package for Container.ForwardSignals, for
consistency with other signal forwarding.
Fixes #2546 |
259,992 | 27.04.2020 12:25:57 | 25,200 | 003e79a6d11b17caed480c1ba556de5cb713abb3 | Dump stack for stuck start and stuck watchdog
The meaning for skipDump was reversed, but not all callers
were updated. Change the meaning once again to forceDump, so
that the period between stack dump is respected from all
callers. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/watchdog/watchdog.go",
"new_path": "pkg/sentry/watchdog/watchdog.go",
"diff": "@@ -255,7 +255,7 @@ func (w *Watchdog) runTurn() {\ncase <-done:\ncase <-time.After(w.TaskTimeout):\n// Report if the watchdog is not making progress.\n- // No one is wathching the watchdog watcher though.\n+ // No one is watching the watchdog watcher though.\nw.reportStuckWatchdog()\n<-done\n}\n@@ -317,10 +317,8 @@ func (w *Watchdog) report(offenders map[*kernel.Task]*offender, newTaskFound boo\nbuf.WriteString(\"Search for '(*Task).run(0x..., 0x<tid>)' in the stack dump to find the offending goroutine\")\n- // Dump stack only if a new task is detected or if it sometime has\n- // passed since the last time a stack dump was generated.\n- showStack := newTaskFound || time.Since(w.lastStackDump) >= stackDumpSameTaskPeriod\n- w.doAction(w.TaskTimeoutAction, showStack, &buf)\n+ // Force stack dump only if a new task is detected.\n+ w.doAction(w.TaskTimeoutAction, newTaskFound, &buf)\n}\nfunc (w *Watchdog) reportStuckWatchdog() {\n@@ -329,12 +327,15 @@ func (w *Watchdog) reportStuckWatchdog() {\nw.doAction(w.TaskTimeoutAction, false, &buf)\n}\n-// doAction will take the given action. If the action is LogWarning and\n-// showStack is false, then the stack printing will be skipped.\n-func (w *Watchdog) doAction(action Action, showStack bool, msg *bytes.Buffer) {\n+// doAction will take the given action. If the action is LogWarning, the stack\n+// is not always dumpped to the log to prevent log flooding. \"forceStack\"\n+// guarantees that the stack will be dumped regarless.\n+func (w *Watchdog) doAction(action Action, forceStack bool, msg *bytes.Buffer) {\nswitch action {\ncase LogWarning:\n- if !showStack {\n+ // Dump stack only if forced or sometime has passed since the last time a\n+ // stack dump was generated.\n+ if !forceStack && time.Since(w.lastStackDump) < stackDumpSameTaskPeriod {\nmsg.WriteString(\"\\n...[stack dump skipped]...\")\nlog.Warningf(msg.String())\nreturn\n@@ -359,6 +360,7 @@ func (w *Watchdog) doAction(action Action, showStack bool, msg *bytes.Buffer) {\ncase <-time.After(1 * time.Second):\n}\npanic(fmt.Sprintf(\"%s\\nStack for running G's are skipped while panicking.\", msg.String()))\n+\ndefault:\npanic(fmt.Sprintf(\"Unknown watchdog action %v\", action))\n"
}
] | Go | Apache License 2.0 | google/gvisor | Dump stack for stuck start and stuck watchdog
The meaning for skipDump was reversed, but not all callers
were updated. Change the meaning once again to forceDump, so
that the period between stack dump is respected from all
callers.
PiperOrigin-RevId: 308674373 |
259,884 | 28.04.2020 07:03:12 | -32,400 | a9b3046791e7044fb519ce611c74961d29f9fd23 | Capture and publish OOM events
* Capture and publish OOM events
We use oom notifiers on the cgroup to publish oom events to containerd.
This is passed back via CRI to Kubernetes etc. for more helpful error
reporting.
Fixes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/v2/epoll.go",
"diff": "+// +build linux\n+\n+/*\n+ Copyright The containerd 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+\n+package v2\n+\n+import (\n+ \"context\"\n+ \"sync\"\n+\n+ \"github.com/containerd/cgroups\"\n+ eventstypes \"github.com/containerd/containerd/api/events\"\n+ \"github.com/containerd/containerd/events\"\n+ \"github.com/containerd/containerd/runtime\"\n+ \"github.com/sirupsen/logrus\"\n+ \"golang.org/x/sys/unix\"\n+)\n+\n+func newOOMEpoller(publisher events.Publisher) (*epoller, error) {\n+ fd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)\n+ if err != nil {\n+ return nil, err\n+ }\n+ return &epoller{\n+ fd: fd,\n+ publisher: publisher,\n+ set: make(map[uintptr]*item),\n+ }, nil\n+}\n+\n+type epoller struct {\n+ mu sync.Mutex\n+\n+ fd int\n+ publisher events.Publisher\n+ set map[uintptr]*item\n+}\n+\n+type item struct {\n+ id string\n+ cg cgroups.Cgroup\n+}\n+\n+func (e *epoller) Close() error {\n+ return unix.Close(e.fd)\n+}\n+\n+func (e *epoller) run(ctx context.Context) {\n+ var events [128]unix.EpollEvent\n+ for {\n+ select {\n+ case <-ctx.Done():\n+ e.Close()\n+ return\n+ default:\n+ n, err := unix.EpollWait(e.fd, events[:], -1)\n+ if err != nil {\n+ if err == unix.EINTR {\n+ continue\n+ }\n+ logrus.WithError(err).Error(\"cgroups: epoll wait\")\n+ }\n+ for i := 0; i < n; i++ {\n+ e.process(ctx, uintptr(events[i].Fd))\n+ }\n+ }\n+ }\n+}\n+\n+func (e *epoller) add(id string, cg cgroups.Cgroup) error {\n+ e.mu.Lock()\n+ defer e.mu.Unlock()\n+ fd, err := cg.OOMEventFD()\n+ if err != nil {\n+ return err\n+ }\n+ e.set[fd] = &item{\n+ id: id,\n+ cg: cg,\n+ }\n+ event := unix.EpollEvent{\n+ Fd: int32(fd),\n+ Events: unix.EPOLLHUP | unix.EPOLLIN | unix.EPOLLERR,\n+ }\n+ return unix.EpollCtl(e.fd, unix.EPOLL_CTL_ADD, int(fd), &event)\n+}\n+\n+func (e *epoller) process(ctx context.Context, fd uintptr) {\n+ flush(fd)\n+ e.mu.Lock()\n+ i, ok := e.set[fd]\n+ if !ok {\n+ e.mu.Unlock()\n+ return\n+ }\n+ e.mu.Unlock()\n+ if i.cg.State() == cgroups.Deleted {\n+ e.mu.Lock()\n+ delete(e.set, fd)\n+ e.mu.Unlock()\n+ unix.Close(int(fd))\n+ return\n+ }\n+ if err := e.publisher.Publish(ctx, runtime.TaskOOMEventTopic, &eventstypes.TaskOOM{\n+ ContainerID: i.id,\n+ }); err != nil {\n+ logrus.WithError(err).Error(\"publish OOM event\")\n+ }\n+}\n+\n+func flush(fd uintptr) error {\n+ var buf [8]byte\n+ _, err := unix.Read(int(fd), buf[:])\n+ return err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/v2/service.go",
"new_path": "pkg/v2/service.go",
"diff": "@@ -75,13 +75,19 @@ const configFile = \"config.toml\"\n// New returns a new shim service that can be used via GRPC\nfunc New(ctx context.Context, id string, publisher events.Publisher) (shim.Shim, error) {\n+ ep, err := newOOMEpoller(publisher)\n+ if err != nil {\n+ return nil, err\n+ }\nctx, cancel := context.WithCancel(ctx)\n+ go ep.run(ctx)\ns := &service{\nid: id,\ncontext: ctx,\nprocesses: make(map[string]rproc.Process),\nevents: make(chan interface{}, 128),\nec: proc.ExitCh,\n+ oomPoller: ep,\ncancel: cancel,\n}\ngo s.processExits()\n@@ -104,6 +110,7 @@ type service struct {\nevents chan interface{}\nplatform rproc.Platform\nec chan proc.Exit\n+ oomPoller *epoller\nid string\nbundle string\n@@ -343,6 +350,19 @@ func (s *service) Create(ctx context.Context, r *taskAPI.CreateTaskRequest) (_ *\n// save the main task id and bundle to the shim for additional requests\ns.id = r.ID\ns.bundle = r.Bundle\n+\n+ // Set up OOM notification on the sandbox's cgroup. This is done on sandbox\n+ // create since the sandbox process will be created here.\n+ pid := process.Pid()\n+ if pid > 0 {\n+ cg, err := cgroups.Load(cgroups.V1, cgroups.PidPath(pid))\n+ if err != nil {\n+ return nil, errors.Wrapf(err, \"loading cgroup for %d\", pid)\n+ }\n+ if err := s.oomPoller.add(s.id, cg); err != nil {\n+ return nil, errors.Wrapf(err, \"add cg to OOM monitor\")\n+ }\n+ }\ns.task = process\nreturn &taskAPI.CreateTaskResponse{\nPid: uint32(process.Pid()),\n@@ -359,6 +379,8 @@ func (s *service) Start(ctx context.Context, r *taskAPI.StartRequest) (*taskAPI.\nif err := p.Start(ctx); err != nil {\nreturn nil, err\n}\n+ // TODO: Set the cgroup and oom notifications on restore.\n+ // https://github.com/google/gvisor-containerd-shim/issues/58\nreturn &taskAPI.StartResponse{\nPid: uint32(p.Pid()),\n}, nil\n"
}
] | Go | Apache License 2.0 | google/gvisor | Capture and publish OOM events (#57)
* Capture and publish OOM events
We use oom notifiers on the cgroup to publish oom events to containerd.
This is passed back via CRI to Kubernetes etc. for more helpful error
reporting.
Fixes #56 |
259,962 | 27.04.2020 15:40:00 | 25,200 | 8f42cbfd0815ea34fdfe76c07f76966952d09bb7 | Reduce flakiness in tcp_test.
Poll for metric updates as immediately trying to read them can sometimes be
flaky if due to goroutine scheduling the check happens before the sender has got
a chance to update the corresponding sent metric. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_sack_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_sack_test.go",
"diff": "@@ -28,6 +28,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/testing/context\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n)\n// createConnectedWithSACKPermittedOption creates and connects c.ep with the\n@@ -439,6 +440,7 @@ func TestSACKRecovery(t *testing.T) {\n// Receive the retransmitted packet.\nc.ReceiveAndCheckPacketWithOptions(data, rtxOffset, maxPayload, tsOptionSize)\n+ metricPollFn := func() error {\ntcpStats := c.Stack().Stats().TCP\nstats := []struct {\nstat *tcpip.StatCounter\n@@ -452,9 +454,15 @@ func TestSACKRecovery(t *testing.T) {\n}\nfor _, s := range stats {\nif got, want := s.stat.Value(), s.want; got != want {\n- t.Errorf(\"got %s.Value() = %v, want = %v\", s.name, got, want)\n+ return fmt.Errorf(\"got %s.Value() = %v, want = %v\", s.name, got, want)\n}\n}\n+ return nil\n+ }\n+\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n+ }\n// Now send 7 mode duplicate ACKs. In SACK TCP dupAcks do not cause\n// window inflation and sending of packets is completely handled by the\n@@ -517,22 +525,28 @@ func TestSACKRecovery(t *testing.T) {\nbytesRead += maxPayload\n}\n+ metricPollFn = func() error {\n// In SACK recovery only the first segment is fast retransmitted when\n// entering recovery.\nif got, want := c.Stack().Stats().TCP.FastRetransmit.Value(), uint64(1); got != want {\n- t.Errorf(\"got stats.TCP.FastRetransmit.Value = %v, want = %v\", got, want)\n+ return fmt.Errorf(\"got stats.TCP.FastRetransmit.Value = %v, want = %v\", got, want)\n}\nif got, want := c.EP.Stats().(*tcp.Stats).SendErrors.FastRetransmit.Value(), uint64(1); got != want {\n- t.Errorf(\"got EP stats SendErrors.FastRetransmit = %v, want = %v\", got, want)\n+ return fmt.Errorf(\"got EP stats SendErrors.FastRetransmit = %v, want = %v\", got, want)\n}\nif got, want := c.Stack().Stats().TCP.Retransmits.Value(), uint64(4); got != want {\n- t.Errorf(\"got stats.TCP.Retransmits.Value = %v, want = %v\", got, want)\n+ return fmt.Errorf(\"got stats.TCP.Retransmits.Value = %v, want = %v\", got, want)\n}\nif got, want := c.EP.Stats().(*tcp.Stats).SendErrors.Retransmits.Value(), uint64(4); got != want {\n- t.Errorf(\"got EP stats Stats.SendErrors.Retransmits = %v, want = %v\", got, want)\n+ return fmt.Errorf(\"got EP stats Stats.SendErrors.Retransmits = %v, want = %v\", got, want)\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n}\nc.CheckNoPacketTimeout(\"More packets received than expected during recovery after partial ack for this cwnd.\", 50*time.Millisecond)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -35,6 +35,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp/testing/context\"\n+ \"gvisor.dev/gvisor/pkg/test/testutil\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -209,8 +210,15 @@ func TestTCPResetsSentIncrement(t *testing.T) {\nc.SendPacket(nil, ackHeaders)\nc.GetPacket()\n+\n+ metricPollFn := func() error {\nif got := stats.TCP.ResetsSent.Value(); got != want {\n- t.Errorf(\"got stats.TCP.ResetsSent.Value() = %v, want = %v\", got, want)\n+ return fmt.Errorf(\"got stats.TCP.ResetsSent.Value() = %v, want = %v\", got, want)\n+ }\n+ return nil\n+ }\n+ if err := testutil.Poll(metricPollFn, 1*time.Second); err != nil {\n+ t.Error(err)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Reduce flakiness in tcp_test.
Poll for metric updates as immediately trying to read them can sometimes be
flaky if due to goroutine scheduling the check happens before the sender has got
a chance to update the corresponding sent metric.
PiperOrigin-RevId: 308712817 |
259,858 | 28.04.2020 14:45:06 | 25,200 | 64723470a6f0b62ec6223ff66e9c9ca70d248b61 | Use existing bazeldefs with top-level BUILD file. | [
{
"change_type": "MODIFY",
"old_path": ".bazelrc",
"new_path": ".bazelrc",
"diff": "@@ -30,10 +30,10 @@ build:remote --auth_scope=\"https://www.googleapis.com/auth/cloud-source-tools\"\n# Add a custom platform and toolchain that builds in a privileged docker\n# container, which is required by our syscall tests.\n-build:remote --host_platform=//:rbe_ubuntu1604\n-build:remote --extra_toolchains=//:cc-toolchain-clang-x86_64-default\n-build:remote --extra_execution_platforms=//:rbe_ubuntu1604\n-build:remote --platforms=//:rbe_ubuntu1604\n+build:remote --host_platform=//tools/bazeldefs:rbe_ubuntu1604\n+build:remote --extra_toolchains=//tools/bazeldefs:cc-toolchain-clang-x86_64-default\n+build:remote --extra_execution_platforms=//tools/bazeldefs:rbe_ubuntu1604\n+build:remote --platforms=//tools/bazeldefs:rbe_ubuntu1604\nbuild:remote --crosstool_top=@rbe_default//cc:toolchain\nbuild:remote --jobs=50\nbuild:remote --remote_timeout=3600\n"
},
{
"change_type": "MODIFY",
"old_path": "BUILD",
"new_path": "BUILD",
"diff": "-load(\"@io_bazel_rules_go//go:def.bzl\", \"go_path\", \"nogo\")\n-load(\"@bazel_gazelle//:def.bzl\", \"gazelle\")\n+load(\"//tools:defs.bzl\", \"build_test\", \"gazelle\", \"go_path\")\npackage(licenses = [\"notice\"])\n+exports_files([\"LICENSE\"])\n+\n# The sandbox filegroup is used for sandbox-internal dependencies.\npackage_group(\nname = \"sandbox\",\n- packages = [\n- \"//...\",\n+ packages = [\"//...\"],\n+)\n+\n+# For targets that will not normally build internally, we ensure that they are\n+# least build by a static BUILD test.\n+build_test(\n+ name = \"build_test\",\n+ targets = [\n+ \"//test/e2e:integration_test\",\n+ \"//test/image:image_test\",\n+ \"//test/root:root_test\",\n],\n)\n@@ -43,46 +53,3 @@ go_path(\n# To update the WORKSPACE from go.mod, use:\n# bazel run //:gazelle -- update-repos -from_file=go.mod\ngazelle(name = \"gazelle\")\n-\n-# We need to define a bazel platform and toolchain to specify dockerPrivileged\n-# and dockerRunAsRoot options, they are required to run tests on the RBE\n-# cluster in Kokoro.\n-alias(\n- name = \"rbe_ubuntu1604\",\n- actual = \":rbe_ubuntu1604_r346485\",\n-)\n-\n-platform(\n- name = \"rbe_ubuntu1604_r346485\",\n- constraint_values = [\n- \"@bazel_tools//platforms:x86_64\",\n- \"@bazel_tools//platforms:linux\",\n- \"@bazel_tools//tools/cpp:clang\",\n- \"@bazel_toolchains//constraints:xenial\",\n- \"@bazel_toolchains//constraints/sanitizers:support_msan\",\n- ],\n- remote_execution_properties = \"\"\"\n- properties: {\n- name: \"container-image\"\n- value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:93f7e127196b9b653d39830c50f8b05d49ef6fd8739a9b5b8ab16e1df5399e50\"\n- }\n- properties: {\n- name: \"dockerAddCapabilities\"\n- value: \"SYS_ADMIN\"\n- }\n- properties: {\n- name: \"dockerPrivileged\"\n- value: \"true\"\n- }\n- \"\"\",\n-)\n-\n-toolchain(\n- name = \"cc-toolchain-clang-x86_64-default\",\n- exec_compatible_with = [\n- ],\n- target_compatible_with = [\n- ],\n- toolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/10.0.0/bazel_2.0.0/cc:cc-compiler-k8\",\n- toolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n-)\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"git_repository\")\n+# Bazel/starlark utilities.\n+http_archive(\n+ name = \"bazel_skylib\",\n+ urls = [\n+ \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz\",\n+ \"https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz\",\n+ ],\n+ sha256 = \"97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44\",\n+)\n+\n+load(\"@bazel_skylib//:workspace.bzl\", \"bazel_skylib_workspace\")\n+\n+bazel_skylib_workspace()\n+\n# Load go bazel rules and gazelle.\n#\n# Note that this repository actually patches some other Go repositories as it\n"
},
{
"change_type": "MODIFY",
"old_path": "benchmarks/BUILD",
"new_path": "benchmarks/BUILD",
"diff": "@@ -9,6 +9,7 @@ config_setting(\npy_binary(\nname = \"benchmarks\",\n+ testonly = 1,\nsrcs = [\"run.py\"],\ndata = select({\n\":gcloud_rule\": [],\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/BUILD",
"new_path": "tools/bazeldefs/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"rbe_platform\", \"rbe_toolchain\")\n+\npackage(licenses = [\"notice\"])\n# In bazel, no special support is required for loopback networking. This is\n@@ -8,3 +10,42 @@ genrule(\ncmd = \"touch $@\",\nvisibility = [\"//:sandbox\"],\n)\n+\n+# We need to define a bazel platform and toolchain to specify dockerPrivileged\n+# and dockerRunAsRoot options, they are required to run tests on the RBE\n+# cluster in Kokoro.\n+rbe_platform(\n+ name = \"rbe_ubuntu1604\",\n+ constraint_values = [\n+ \"@bazel_tools//platforms:x86_64\",\n+ \"@bazel_tools//platforms:linux\",\n+ \"@bazel_tools//tools/cpp:clang\",\n+ \"@bazel_toolchains//constraints:xenial\",\n+ \"@bazel_toolchains//constraints/sanitizers:support_msan\",\n+ ],\n+ remote_execution_properties = \"\"\"\n+ properties: {\n+ name: \"container-image\"\n+ value:\"docker://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:93f7e127196b9b653d39830c50f8b05d49ef6fd8739a9b5b8ab16e1df5399e50\"\n+ }\n+ properties: {\n+ name: \"dockerAddCapabilities\"\n+ value: \"SYS_ADMIN\"\n+ }\n+ properties: {\n+ name: \"dockerPrivileged\"\n+ value: \"true\"\n+ }\n+ \"\"\",\n+)\n+\n+rbe_toolchain(\n+ name = \"cc-toolchain-clang-x86_64-default\",\n+ exec_compatible_with = [],\n+ tags = [\n+ \"manual\",\n+ ],\n+ target_compatible_with = [],\n+ toolchain = \"@bazel_toolchains//configs/ubuntu16_04_clang/10.0.0/bazel_2.0.0/cc:cc-compiler-k8\",\n+ toolchain_type = \"@bazel_tools//tools/cpp:toolchain_type\",\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/defs.bzl",
"new_path": "tools/bazeldefs/defs.bzl",
"diff": "\"\"\"Bazel implementations of standard rules.\"\"\"\n+load(\"@bazel_gazelle//:def.bzl\", _gazelle = \"gazelle\")\n+load(\"@bazel_skylib//rules:build_test.bzl\", _build_test = \"build_test\")\nload(\"@bazel_tools//tools/cpp:cc_flags_supplier.bzl\", _cc_flags_supplier = \"cc_flags_supplier\")\n-load(\"@io_bazel_rules_go//go:def.bzl\", \"GoLibrary\", _go_binary = \"go_binary\", _go_context = \"go_context\", _go_embed_data = \"go_embed_data\", _go_library = \"go_library\", _go_test = \"go_test\")\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"GoLibrary\", _go_binary = \"go_binary\", _go_context = \"go_context\", _go_embed_data = \"go_embed_data\", _go_library = \"go_library\", _go_path = \"go_path\", _go_test = \"go_test\")\nload(\"@io_bazel_rules_go//proto:def.bzl\", _go_grpc_library = \"go_grpc_library\", _go_proto_library = \"go_proto_library\")\nload(\"@rules_cc//cc:defs.bzl\", _cc_binary = \"cc_binary\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\")\nload(\"@rules_pkg//:pkg.bzl\", _pkg_deb = \"pkg_deb\", _pkg_tar = \"pkg_tar\")\nload(\"@pydeps//:requirements.bzl\", _py_requirement = \"requirement\")\nload(\"@com_github_grpc_grpc//bazel:cc_grpc_library.bzl\", _cc_grpc_library = \"cc_grpc_library\")\n+build_test = _build_test\ncc_library = _cc_library\ncc_flags_supplier = _cc_flags_supplier\ncc_proto_library = _cc_proto_library\ncc_test = _cc_test\ncc_toolchain = \"@bazel_tools//tools/cpp:current_cc_toolchain\"\n+gazelle = _gazelle\ngo_embed_data = _go_embed_data\n+go_path = _go_path\ngtest = \"@com_google_googletest//:gtest\"\ngrpcpp = \"@com_github_grpc_grpc//:grpc++\"\ngbenchmark = \"@com_google_benchmark//:benchmark\"\n@@ -23,6 +28,8 @@ pkg_tar = _pkg_tar\npy_library = native.py_library\npy_binary = native.py_binary\npy_test = native.py_test\n+rbe_platform = native.platform\n+rbe_toolchain = native.toolchain\ndef proto_library(name, has_services = None, **kwargs):\nnative.proto_library(\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/defs.bzl",
"new_path": "tools/defs.bzl",
"diff": "@@ -7,12 +7,13 @@ 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\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _gbenchmark = \"gbenchmark\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _grpcpp = \"grpcpp\", _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\", _build_test = \"build_test\", _cc_binary = \"cc_binary\", _cc_flags_supplier = \"cc_flags_supplier\", _cc_grpc_library = \"cc_grpc_library\", _cc_library = \"cc_library\", _cc_proto_library = \"cc_proto_library\", _cc_test = \"cc_test\", _cc_toolchain = \"cc_toolchain\", _default_installer = \"default_installer\", _default_net_util = \"default_net_util\", _gazelle = \"gazelle\", _gbenchmark = \"gbenchmark\", _go_binary = \"go_binary\", _go_embed_data = \"go_embed_data\", _go_grpc_and_proto_libraries = \"go_grpc_and_proto_libraries\", _go_library = \"go_library\", _go_path = \"go_path\", _go_proto_library = \"go_proto_library\", _go_test = \"go_test\", _grpcpp = \"grpcpp\", _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\", _rbe_platform = \"rbe_platform\", _rbe_toolchain = \"rbe_toolchain\", _select_arch = \"select_arch\", _select_system = \"select_system\")\nload(\"//tools/bazeldefs:platforms.bzl\", _default_platform = \"default_platform\", _platforms = \"platforms\")\nload(\"//tools/bazeldefs:tags.bzl\", \"go_suffixes\")\nload(\"//tools/nogo:defs.bzl\", \"nogo_test\")\n# Delegate directly.\n+build_test = _build_test\ncc_binary = _cc_binary\ncc_flags_supplier = _cc_flags_supplier\ncc_grpc_library = _cc_grpc_library\n@@ -22,7 +23,9 @@ cc_toolchain = _cc_toolchain\ndefault_installer = _default_installer\ndefault_net_util = _default_net_util\ngbenchmark = _gbenchmark\n+gazelle = _gazelle\ngo_embed_data = _go_embed_data\n+go_path = _go_path\ngo_test = _go_test\ngtest = _gtest\ngrpcpp = _grpcpp\n@@ -35,6 +38,8 @@ py_requirement = _py_requirement\npy_test = _py_test\nselect_arch = _select_arch\nselect_system = _select_system\n+rbe_platform = _rbe_platform\n+rbe_toolchain = _rbe_toolchain\n# Platform options.\ndefault_platform = _default_platform\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use existing bazeldefs with top-level BUILD file.
PiperOrigin-RevId: 308901116 |
259,860 | 28.04.2020 17:42:11 | 25,200 | f93f2fda74f31246e8866783f6c4be2318bdedd6 | Deduplicate unix socket Release() method. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -103,7 +103,7 @@ func (s *socketOpsCommon) DecRef() {\n}\n// Release implemements fs.FileOperations.Release.\n-func (s *SocketOperations) Release() {\n+func (s *socketOpsCommon) Release() {\n// Release only decrements a reference on s because s may be referenced in\n// the abstract socket namespace.\ns.DecRef()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"new_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"diff": "@@ -273,13 +273,6 @@ func (s *SocketVFS2) Write(ctx context.Context, src usermem.IOSequence, opts vfs\n})\n}\n-// Release implements vfs.FileDescriptionImpl.\n-func (s *SocketVFS2) Release() {\n- // Release only decrements a reference on s because s may be referenced in\n- // the abstract socket namespace.\n- s.DecRef()\n-}\n-\n// Readiness implements waiter.Waitable.Readiness.\nfunc (s *SocketVFS2) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn s.socketOpsCommon.Readiness(mask)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deduplicate unix socket Release() method.
PiperOrigin-RevId: 308932254 |
259,860 | 28.04.2020 20:11:43 | 25,200 | ce19497c1c0829af6ba56f0cc68e3a4cb33cf1c8 | Fix Unix socket permissions.
Enforce write permission checks in BoundEndpointAt, which corresponds to the
permission checks in Linux (net/unix/af_unix.c:unix_find_other).
Also, create bound socket files with the correct permissions in VFS2.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"new_path": "pkg/sentry/fsimpl/ext/filesystem.go",
"diff": "@@ -486,10 +486,13 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\n// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\nfunc (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.BoundEndpointOptions) (transport.BoundEndpoint, error) {\n- _, _, err := fs.walk(rp, false)\n+ _, inode, err := fs.walk(rp, false)\nif err != nil {\nreturn nil, err\n}\n+ if err := inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\n+ return nil, err\n+ }\n// TODO(b/134676337): Support sockets.\nreturn nil, syserror.ECONNREFUSED\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go",
"diff": "@@ -768,12 +768,15 @@ func (fs *Filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\n// BoundEndpointAt implements FilesystemImpl.BoundEndpointAt.\nfunc (fs *Filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.BoundEndpointOptions) (transport.BoundEndpoint, error) {\nfs.mu.RLock()\n- _, _, err := fs.walkExistingLocked(ctx, rp)\n+ _, inode, err := fs.walkExistingLocked(ctx, rp)\nfs.mu.RUnlock()\nfs.processDeferredDecRefs()\nif err != nil {\nreturn nil, err\n}\n+ if err := inode.CheckPermissions(ctx, rp.Credentials(), vfs.MayWrite); err != nil {\n+ return nil, err\n+ }\nreturn nil, syserror.ECONNREFUSED\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go",
"diff": "@@ -704,6 +704,9 @@ func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath\nif err != nil {\nreturn nil, err\n}\n+ if err := d.inode.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {\n+ return nil, err\n+ }\nswitch impl := d.inode.impl.(type) {\ncase *socketFile:\nreturn impl.ep, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -323,7 +323,10 @@ func (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n// Create the socket.\n//\n- // TODO(gvisor.dev/issue/2324): Correctly set file permissions.\n+ // Note that the file permissions here are not set correctly (see\n+ // gvisor.dev/issue/2324). There is no convenient way to get permissions\n+ // on the socket referred to by s, so we will leave this discrepancy\n+ // unresolved until VFS2 replaces this code.\nchildDir, err := d.Bind(t, t.FSContext().RootDirectory(), name, bep, fs.FilePermissions{User: fs.PermMask{Read: true}})\nif err != nil {\nreturn syserr.ErrPortInUse\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"new_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"diff": "@@ -197,11 +197,13 @@ func (s *SocketVFS2) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nStart: start,\nPath: path,\n}\n- err := t.Kernel().VFS().MknodAt(t, t.Credentials(), &pop, &vfs.MknodOptions{\n- // TODO(gvisor.dev/issue/2324): The file permissions should be taken\n- // from s and t.FSContext().Umask() (see net/unix/af_unix.c:unix_bind),\n- // but VFS1 just always uses 0400. Resolve this inconsistency.\n- Mode: linux.S_IFSOCK | 0400,\n+ stat, err := s.vfsfd.Stat(t, vfs.StatOptions{Mask: linux.STATX_MODE})\n+ if err != nil {\n+ return syserr.FromError(err)\n+ }\n+ err = t.Kernel().VFS().MknodAt(t, t.Credentials(), &pop, &vfs.MknodOptions{\n+ // File permissions correspond to net/unix/af_unix.c:unix_bind.\n+ Mode: linux.FileMode(linux.S_IFSOCK | uint(stat.Mode)&^t.FSContext().Umask()),\nEndpoint: bep,\n})\nif err == syserror.EEXIST {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/anonfs.go",
"new_path": "pkg/sentry/vfs/anonfs.go",
"diff": "@@ -241,6 +241,9 @@ func (fs *anonFilesystem) BoundEndpointAt(ctx context.Context, rp *ResolvingPath\nif !rp.Final() {\nreturn nil, syserror.ENOTDIR\n}\n+ if err := GenericCheckPermissions(rp.Credentials(), MayWrite, anonFileMode, anonFileUID, anonFileGID); err != nil {\n+ return nil, err\n+ }\nreturn nil, syserror.ECONNREFUSED\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/filesystem.go",
"new_path": "pkg/sentry/vfs/filesystem.go",
"diff": "@@ -494,7 +494,13 @@ type FilesystemImpl interface {\n// BoundEndpointAt returns the Unix socket endpoint bound at the path rp.\n//\n- // - If a non-socket file exists at rp, then BoundEndpointAt returns ECONNREFUSED.\n+ // Errors:\n+ //\n+ // - If the file does not have write permissions, then BoundEndpointAt\n+ // returns EACCES.\n+ //\n+ // - If a non-socket file exists at rp, then BoundEndpointAt returns\n+ // ECONNREFUSED.\nBoundEndpointAt(ctx context.Context, rp *ResolvingPath, opts BoundEndpointOptions) (transport.BoundEndpoint, error)\n// PrependPath prepends a path from vd to vd.Mount().Root() to b.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -365,6 +365,7 @@ cc_binary(\n\":socket_test_util\",\n\"//test/util:file_descriptor\",\ngtest,\n+ \"//test/util:temp_umask\",\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket.cc",
"new_path": "test/syscalls/linux/socket.cc",
"diff": "// limitations under the License.\n#include <sys/socket.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n#include <unistd.h>\n#include \"gtest/gtest.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/file_descriptor.h\"\n+#include \"test/util/temp_umask.h\"\n#include \"test/util/test_util.h\"\nnamespace gvisor {\n@@ -58,11 +61,69 @@ TEST(SocketTest, ProtocolInet) {\n}\n}\n+TEST(SocketTest, UnixSocketFileMode) {\n+ // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n+ // should pass in VFS2.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ FileDescriptor bound =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n+\n+ // The permissions of the file created with bind(2) should be defined by the\n+ // permissions of the bound socket and the umask.\n+ mode_t sock_perm = 0765, mask = 0123;\n+ ASSERT_THAT(fchmod(bound.get(), sock_perm), SyscallSucceeds());\n+ TempUmask m(mask);\n+\n+ struct sockaddr_un addr =\n+ ASSERT_NO_ERRNO_AND_VALUE(UniqueUnixAddr(/*abstract=*/false, AF_UNIX));\n+ ASSERT_THAT(bind(bound.get(), reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr)),\n+ SyscallSucceeds());\n+\n+ struct stat statbuf = {};\n+ ASSERT_THAT(stat(addr.sun_path, &statbuf), SyscallSucceeds());\n+ EXPECT_EQ(statbuf.st_mode, S_IFSOCK | sock_perm & ~mask);\n+}\n+\n+TEST(SocketTest, UnixConnectNeedsWritePerm) {\n+ // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n+ // should succeed in VFS2.\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ FileDescriptor bound =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n+\n+ struct sockaddr_un addr =\n+ ASSERT_NO_ERRNO_AND_VALUE(UniqueUnixAddr(/*abstract=*/false, AF_UNIX));\n+ ASSERT_THAT(bind(bound.get(), reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr)),\n+ SyscallSucceeds());\n+ ASSERT_THAT(listen(bound.get(), 1), SyscallSucceeds());\n+\n+ // Connect should fail without write perms.\n+ ASSERT_THAT(chmod(addr.sun_path, 0500), SyscallSucceeds());\n+ FileDescriptor client =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n+ EXPECT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr)),\n+ SyscallFailsWithErrno(EACCES));\n+\n+ // Connect should succeed with write perms.\n+ ASSERT_THAT(chmod(addr.sun_path, 0200), SyscallSucceeds());\n+ EXPECT_THAT(connect(client.get(), reinterpret_cast<struct sockaddr*>(&addr),\n+ sizeof(addr)),\n+ SyscallSucceeds());\n+}\n+\nusing SocketOpenTest = ::testing::TestWithParam<int>;\n// UDS cannot be opened.\nTEST_P(SocketOpenTest, Unix) {\n// FIXME(b/142001530): Open incorrectly succeeds on gVisor.\n+ //\n+ // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n+ // should succeed in VFS2.\nSKIP_IF(IsRunningOnGvisor());\nFileDescriptor bound =\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix Unix socket permissions.
Enforce write permission checks in BoundEndpointAt, which corresponds to the
permission checks in Linux (net/unix/af_unix.c:unix_find_other).
Also, create bound socket files with the correct permissions in VFS2.
Fixes #2324.
PiperOrigin-RevId: 308949084 |
259,891 | 29.04.2020 13:36:29 | 25,200 | a105d185ff9fc24f5bf0c1ca28cbc0f7ec7c4ea5 | iptables: don't pollute logs
The netfilter package uses logs to make debugging the (de)serialization of
structs easier. This generates a lot of (usually irrelevant) logs. Logging is
now hidden behind a debug flag. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -53,9 +53,14 @@ type metadata struct {\nSize uint32\n}\n+// enableLogging controls whether to log the (de)serialization of netfilter\n+// structs between userspace and netstack. These logs are useful when\n+// developing iptables, but can pollute sentry logs otherwise.\n+const enableLogging = false\n+\n// nflog logs messages related to the writing and reading of iptables.\nfunc nflog(format string, args ...interface{}) {\n- if log.IsLogging(log.Debug) {\n+ if enableLogging && log.IsLogging(log.Debug) {\nlog.Debugf(\"netfilter: \"+format, args...)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: don't pollute logs
The netfilter package uses logs to make debugging the (de)serialization of
structs easier. This generates a lot of (usually irrelevant) logs. Logging is
now hidden behind a debug flag.
PiperOrigin-RevId: 309087115 |
259,860 | 29.04.2020 14:34:28 | 25,200 | ef94401955bbcfb5296daa29ab373423cdd289db | Add read/write timeouts for VFS2 socket files.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/read_write.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/read_write.go",
"diff": "package vfs2\nimport (\n+ \"time\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ ktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket\"\nslinux \"gvisor.dev/gvisor/pkg/sentry/syscalls/linux\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -88,7 +92,12 @@ func Readv(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\nfunc read(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\nn, err := file.Read(t, dst, opts)\n- if err != syserror.ErrWouldBlock || file.StatusFlags()&linux.O_NONBLOCK != 0 {\n+ if err != syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+\n+ allowBlock, deadline, hasDeadline := blockPolicy(t, file)\n+ if !allowBlock {\nreturn n, err\n}\n@@ -108,7 +117,12 @@ func read(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, opt\nif err != syserror.ErrWouldBlock {\nbreak\n}\n- if err := t.Block(ch); err != nil {\n+\n+ // Wait for a notification that we should retry.\n+ if err = t.BlockWithDeadline(ch, hasDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n@@ -233,7 +247,12 @@ func Preadv2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\nfunc pread(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\nn, err := file.PRead(t, dst, offset, opts)\n- if err != syserror.ErrWouldBlock || file.StatusFlags()&linux.O_NONBLOCK != 0 {\n+ if err != syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+\n+ allowBlock, deadline, hasDeadline := blockPolicy(t, file)\n+ if !allowBlock {\nreturn n, err\n}\n@@ -253,7 +272,12 @@ func pread(t *kernel.Task, file *vfs.FileDescription, dst usermem.IOSequence, of\nif err != syserror.ErrWouldBlock {\nbreak\n}\n- if err := t.Block(ch); err != nil {\n+\n+ // Wait for a notification that we should retry.\n+ if err = t.BlockWithDeadline(ch, hasDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n@@ -320,7 +344,12 @@ func Writev(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nfunc write(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\nn, err := file.Write(t, src, opts)\n- if err != syserror.ErrWouldBlock || file.StatusFlags()&linux.O_NONBLOCK != 0 {\n+ if err != syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+\n+ allowBlock, deadline, hasDeadline := blockPolicy(t, file)\n+ if !allowBlock {\nreturn n, err\n}\n@@ -340,7 +369,12 @@ func write(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, op\nif err != syserror.ErrWouldBlock {\nbreak\n}\n- if err := t.Block(ch); err != nil {\n+\n+ // Wait for a notification that we should retry.\n+ if err = t.BlockWithDeadline(ch, hasDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n@@ -465,7 +499,12 @@ func Pwritev2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nfunc pwrite(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\nn, err := file.PWrite(t, src, offset, opts)\n- if err != syserror.ErrWouldBlock || file.StatusFlags()&linux.O_NONBLOCK != 0 {\n+ if err != syserror.ErrWouldBlock {\n+ return n, err\n+ }\n+\n+ allowBlock, deadline, hasDeadline := blockPolicy(t, file)\n+ if !allowBlock {\nreturn n, err\n}\n@@ -485,7 +524,12 @@ func pwrite(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, o\nif err != syserror.ErrWouldBlock {\nbreak\n}\n- if err := t.Block(ch); err != nil {\n+\n+ // Wait for a notification that we should retry.\n+ if err = t.BlockWithDeadline(ch, hasDeadline, deadline); err != nil {\n+ if err == syserror.ETIMEDOUT {\n+ err = syserror.ErrWouldBlock\n+ }\nbreak\n}\n}\n@@ -494,6 +538,23 @@ func pwrite(t *kernel.Task, file *vfs.FileDescription, src usermem.IOSequence, o\nreturn total, err\n}\n+func blockPolicy(t *kernel.Task, file *vfs.FileDescription) (allowBlock bool, deadline ktime.Time, hasDeadline bool) {\n+ if file.StatusFlags()&linux.O_NONBLOCK != 0 {\n+ return false, ktime.Time{}, false\n+ }\n+ // Sockets support read/write timeouts.\n+ if s, ok := file.Impl().(socket.SocketVFS2); ok {\n+ dl := s.RecvTimeout()\n+ if dl < 0 {\n+ return false, ktime.Time{}, false\n+ }\n+ if dl > 0 {\n+ return true, t.Kernel().MonotonicClock().Now().Add(time.Duration(dl) * time.Nanosecond), true\n+ }\n+ }\n+ return true, ktime.Time{}, false\n+}\n+\n// Lseek implements Linux syscall lseek(2).\nfunc Lseek(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nfd := args[0].Int()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add read/write timeouts for VFS2 socket files.
Updates #1476
PiperOrigin-RevId: 309098590 |
259,853 | 30.04.2020 00:32:58 | 25,200 | 44a57646d88b0a03545f97defb12f5bde54a55bf | make_repository.sh has to print only the repo path on stdout | [
{
"change_type": "MODIFY",
"old_path": "tools/make_repository.sh",
"new_path": "tools/make_repository.sh",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n+# We need to be sure that only a repo path is printed on stdout.\n+exec 50<&1\n+exec 1<&2\n+\n+echo_stdout() {\n+ echo \"$@\" >&50\n+}\n+\n# Parse arguments. We require more than two arguments, which are the private\n# keyring, the e-mail associated with the signer, and the list of packages.\nif [ \"$#\" -le 3 ]; then\n@@ -61,7 +69,7 @@ cleanup() {\nrm -f \"${keyring}\"\n}\ntrap cleanup EXIT\n-gpg --no-default-keyring --keyring \"${keyring}\" --import \"${private_key}\" >&2\n+gpg --no-default-keyring --keyring \"${keyring}\" --import \"${private_key}\"\n# Copy the packages into the root.\nfor pkg in \"$@\"; do\n@@ -92,7 +100,7 @@ find \"${root}\"/pool -type f -exec chmod 0644 {} \\;\n# Sign all packages.\nfor file in \"${root}\"/pool/*/binary-*/*.deb; do\n- dpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\" >&2\n+ dpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\"\ndone\n# Build the package list.\n@@ -124,8 +132,8 @@ rm \"${tmpdir}\"/apt.conf\n# Sign the release.\ndeclare -r digest_opts=(\"--digest-algo\" \"SHA512\" \"--cert-digest-algo\" \"SHA512\")\n-(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" --clearsign \"${digest_opts[@]}\" -o InRelease Release >&2)\n-(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" -abs \"${digest_opts[@]}\" -o Release.gpg Release >&2)\n+(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" --clearsign \"${digest_opts[@]}\" -o InRelease Release)\n+(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" -abs \"${digest_opts[@]}\" -o Release.gpg Release)\n# Show the results.\n-echo \"${tmpdir}\"\n+echo_stdout \"${tmpdir}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | make_repository.sh has to print only the repo path on stdout
PiperOrigin-RevId: 309176385 |
259,860 | 30.04.2020 09:46:36 | 25,200 | 442fde405d86c555ac09994772c85ca15a3b4fc7 | Fix proc net bugs in VFS2.
The /proc/net/udp header was missing, and /proc/sys/net was set up as
/proc/sys/net/net. Discovered while trying to run networking tests for VFS2. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/task_net.go",
"new_path": "pkg/sentry/fsimpl/proc/task_net.go",
"diff": "@@ -511,6 +511,8 @@ func (d *netUDPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// degrade gracefully and retrieve what we can.\nt := kernel.TaskFromContext(ctx)\n+ buf.WriteString(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode ref pointer drops \\n\")\n+\nfor _, se := range d.kernel.ListSockets() {\ns := se.SockVFS2\nif !s.TryIncRef() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/proc/tasks_sys.go",
"new_path": "pkg/sentry/fsimpl/proc/tasks_sys.go",
"diff": "@@ -112,9 +112,7 @@ func newSysNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel)\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+ return kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, contents)\n}\n// mmapMinAddrData implements vfs.DynamicBytesSource for\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix proc net bugs in VFS2.
The /proc/net/udp header was missing, and /proc/sys/net was set up as
/proc/sys/net/net. Discovered while trying to run networking tests for VFS2.
PiperOrigin-RevId: 309243758 |
260,004 | 30.04.2020 10:21:57 | 25,200 | 043b7d83bd76c616fa32b815528eec77f2aad5ff | Prefer temporary addresses
Implement rule 7 of Source Address Selection RFC 6724 section 5. This
makes temporary (short-lived) addresses preferred over non-temporary
addresses when earlier rules are equal.
Test: stack_test.TestIPv6SourceAddressSelectionScopeAndSameAddress | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -452,7 +452,7 @@ type ipv6AddrCandidate struct {\n// primaryIPv6Endpoint returns an IPv6 endpoint following Source Address\n// Selection (RFC 6724 section 5).\n//\n-// Note, only rules 1-3 are followed.\n+// Note, only rules 1-3 and 7 are followed.\n//\n// remoteAddr must be a valid IPv6 address.\nfunc (n *NIC) primaryIPv6Endpoint(remoteAddr tcpip.Address) *referencedNetworkEndpoint {\n@@ -523,6 +523,11 @@ func (n *NIC) primaryIPv6Endpoint(remoteAddr tcpip.Address) *referencedNetworkEn\nreturn sbDep\n}\n+ // Prefer temporary addresses as per RFC 6724 section 5 rule 7.\n+ if saTemp, sbTemp := sa.ref.configType == slaacTemp, sb.ref.configType == slaacTemp; saTemp != sbTemp {\n+ return saTemp\n+ }\n+\n// sa and sb are equal, return the endpoint that is closest to the front of\n// the primary endpoint list.\nreturn i < j\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -2870,12 +2870,23 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nglobalAddr1 = tcpip.Address(\"\\xa0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\")\nglobalAddr2 = tcpip.Address(\"\\xa0\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\")\nnicID = 1\n+ lifetimeSeconds = 9999\n)\n+ prefix1, _, stableGlobalAddr1 := prefixSubnetAddr(0, linkAddr1)\n+ prefix2, _, stableGlobalAddr2 := prefixSubnetAddr(1, linkAddr1)\n+\n+ var tempIIDHistory [header.IIDSize]byte\n+ header.InitialTempIID(tempIIDHistory[:], nil, nicID)\n+ tempGlobalAddr1 := header.GenerateTempIPv6SLAACAddr(tempIIDHistory[:], stableGlobalAddr1.Address).Address\n+ tempGlobalAddr2 := header.GenerateTempIPv6SLAACAddr(tempIIDHistory[:], stableGlobalAddr2.Address).Address\n+\n// Rule 3 is not tested here, and is instead tested by NDP's AutoGenAddr test.\ntests := []struct {\nname string\n+ slaacPrefixForTempAddrBeforeNICAddrAdd tcpip.AddressWithPrefix\nnicAddrs []tcpip.Address\n+ slaacPrefixForTempAddrAfterNICAddrAdd tcpip.AddressWithPrefix\nconnectAddr tcpip.Address\nexpectedLocalAddr tcpip.Address\n}{\n@@ -2967,6 +2978,22 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nexpectedLocalAddr: uniqueLocalAddr1,\n},\n+ // Test Rule 7 of RFC 6724 section 5.\n+ {\n+ name: \"Temp Global most preferred (last address)\",\n+ slaacPrefixForTempAddrBeforeNICAddrAdd: prefix1,\n+ nicAddrs: []tcpip.Address{linkLocalAddr1, uniqueLocalAddr1, globalAddr1},\n+ connectAddr: globalAddr2,\n+ expectedLocalAddr: tempGlobalAddr1,\n+ },\n+ {\n+ name: \"Temp Global most preferred (first address)\",\n+ nicAddrs: []tcpip.Address{linkLocalAddr1, uniqueLocalAddr1, globalAddr1},\n+ slaacPrefixForTempAddrAfterNICAddrAdd: prefix1,\n+ connectAddr: globalAddr2,\n+ expectedLocalAddr: tempGlobalAddr1,\n+ },\n+\n// Test returning the endpoint that is closest to the front when\n// candidate addresses are \"equal\" from the perspective of RFC 6724\n// section 5.\n@@ -2988,6 +3015,13 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\nconnectAddr: uniqueLocalAddr2,\nexpectedLocalAddr: linkLocalAddr1,\n},\n+ {\n+ name: \"Temp Global for Global\",\n+ slaacPrefixForTempAddrBeforeNICAddrAdd: prefix1,\n+ slaacPrefixForTempAddrAfterNICAddrAdd: prefix2,\n+ connectAddr: globalAddr1,\n+ expectedLocalAddr: tempGlobalAddr2,\n+ },\n}\nfor _, test := range tests {\n@@ -2996,6 +3030,12 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\nTransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ NDPConfigs: stack.NDPConfigurations{\n+ HandleRAs: true,\n+ AutoGenGlobalAddresses: true,\n+ AutoGenTempGlobalAddresses: true,\n+ },\n+ NDPDisp: &ndpDispatcher{},\n})\nif err := s.CreateNIC(nicID, e); err != nil {\nt.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n@@ -3007,12 +3047,20 @@ func TestIPv6SourceAddressSelectionScopeAndSameAddress(t *testing.T) {\n}})\ns.AddLinkAddress(nicID, llAddr3, linkAddr3)\n+ if test.slaacPrefixForTempAddrBeforeNICAddrAdd != (tcpip.AddressWithPrefix{}) {\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr3, 0, test.slaacPrefixForTempAddrBeforeNICAddrAdd, true, true, lifetimeSeconds, lifetimeSeconds))\n+ }\n+\nfor _, a := range test.nicAddrs {\nif err := s.AddAddress(nicID, ipv6.ProtocolNumber, a); err != nil {\nt.Errorf(\"s.AddAddress(%d, %d, %s): %s\", nicID, ipv6.ProtocolNumber, a, err)\n}\n}\n+ if test.slaacPrefixForTempAddrAfterNICAddrAdd != (tcpip.AddressWithPrefix{}) {\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithPI(llAddr3, 0, test.slaacPrefixForTempAddrAfterNICAddrAdd, true, true, lifetimeSeconds, lifetimeSeconds))\n+ }\n+\nif t.Failed() {\nt.FailNow()\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Prefer temporary addresses
Implement rule 7 of Source Address Selection RFC 6724 section 5. This
makes temporary (short-lived) addresses preferred over non-temporary
addresses when earlier rules are equal.
Test: stack_test.TestIPv6SourceAddressSelectionScopeAndSameAddress
PiperOrigin-RevId: 309250975 |
259,853 | 30.04.2020 11:31:37 | 25,200 | c01e103256a75de4488f50fd34506222c058c151 | Allow to run kvm syscall tests on the RBE cluster | [
{
"change_type": "MODIFY",
"old_path": "scripts/syscall_kvm_tests.sh",
"new_path": "scripts/syscall_kvm_tests.sh",
"diff": "source $(dirname $0)/common.sh\n-# TODO(b/112165693): \"test --test_tag_filters=runsc_kvm\" can be used\n-# when the \"manual\" tag will be removed for kvm tests.\n-test `bazel query \"attr(tags, runsc_kvm, tests(//test/syscalls/...))\"`\n+# Run all ptrace-variants of the system call tests.\n+test --test_tag_filters=runsc_kvm //test/syscalls/...\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/platforms.bzl",
"new_path": "tools/bazeldefs/platforms.bzl",
"diff": "# Platform to associated tags.\nplatforms = {\n\"ptrace\": [],\n- \"kvm\": [\n- \"manual\",\n- \"local\",\n- ],\n+ \"kvm\": [],\n}\ndefault_platform = \"ptrace\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow to run kvm syscall tests on the RBE cluster
PiperOrigin-RevId: 309265978 |
259,885 | 30.04.2020 16:03:04 | 25,200 | 01beec3bb457a2a3a7313c7fe6dc795817f47746 | Add gofer.InternalFilesystemOptions.LeakConnection. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -73,6 +73,7 @@ type filesystem struct {\n// Immutable options.\nopts filesystemOptions\n+ iopts InternalFilesystemOptions\n// client is the client used by this filesystem. client is immutable.\nclient *p9.Client\n@@ -209,6 +210,16 @@ const (\nInteropModeShared\n)\n+// InternalFilesystemOptions may be passed as\n+// vfs.GetFilesystemOptions.InternalData to FilesystemType.GetFilesystem.\n+type InternalFilesystemOptions struct {\n+ // If LeakConnection is true, do not close the connection to the server\n+ // when the Filesystem is released. This is necessary for deployments in\n+ // which servers can handle only a single client and report failure if that\n+ // client disconnects.\n+ LeakConnection bool\n+}\n+\n// Name implements vfs.FilesystemType.Name.\nfunc (FilesystemType) Name() string {\nreturn Name\n@@ -347,6 +358,14 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn nil, nil, syserror.EINVAL\n}\n+ // Handle internal options.\n+ iopts, ok := opts.InternalData.(InternalFilesystemOptions)\n+ if opts.InternalData != nil && !ok {\n+ ctx.Warningf(\"gofer.FilesystemType.GetFilesystem: GetFilesystemOptions.InternalData has type %T, wanted gofer.InternalFilesystemOptions\", opts.InternalData)\n+ return nil, nil, syserror.EINVAL\n+ }\n+ // If !ok, iopts being the zero value is correct.\n+\n// Establish a connection with the server.\nconn, err := unet.NewSocket(fsopts.fd)\nif err != nil {\n@@ -383,6 +402,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfs := &filesystem{\nmfp: mfp,\nopts: fsopts,\n+ iopts: iopts,\nuid: creds.EffectiveKUID,\ngid: creds.EffectiveKGID,\nclient: client,\n@@ -440,9 +460,11 @@ func (fs *filesystem) Release() {\n// fs.\nfs.syncMu.Unlock()\n+ if !fs.iopts.LeakConnection {\n// Close the connection to the server. This implicitly clunks all fids.\nfs.client.Close()\n}\n+}\n// dentry implements vfs.DentryImpl.\ntype dentry struct {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add gofer.InternalFilesystemOptions.LeakConnection.
PiperOrigin-RevId: 309317605 |
259,858 | 01.05.2020 18:01:58 | 25,200 | 56c64e4bb9dc75659799f3e5df9daddf10d810e1 | Fix include type. | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/dut/posix_server.cc",
"new_path": "test/packetimpact/dut/posix_server.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n+#include <arpa/inet.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <netdb.h>\n#include <iostream>\n#include <unordered_map>\n-#include \"arpa/inet.h\"\n#include \"include/grpcpp/security/server_credentials.h\"\n#include \"include/grpcpp/server_builder.h\"\n#include \"test/packetimpact/proto/posix_server.grpc.pb.h\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix include type.
PiperOrigin-RevId: 309506957 |
259,858 | 04.05.2020 10:39:36 | 25,200 | 2c986870e35f967c88ebc1b7df7b576aad2c46d4 | Fix flaky monotonic time.
This change ensures that even platforms with some TSC issues (e.g. KVM),
can get reliable monotonic time by applied a lower bound on each read. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/timekeeper.go",
"new_path": "pkg/sentry/kernel/timekeeper.go",
"diff": "@@ -16,6 +16,7 @@ package kernel\nimport (\n\"fmt\"\n+ \"sync/atomic\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -48,6 +49,9 @@ type Timekeeper struct {\n// It is set only once, by SetClocks.\nmonotonicOffset int64 `state:\"nosave\"`\n+ // monotonicLowerBound is the lowerBound for monotonic time.\n+ monotonicLowerBound int64 `state:\"nosave\"`\n+\n// restored, if non-nil, indicates that this Timekeeper was restored\n// from a state file. The clocks are not set until restored is closed.\nrestored chan struct{} `state:\"nosave\"`\n@@ -271,6 +275,21 @@ func (t *Timekeeper) GetTime(c sentrytime.ClockID) (int64, error) {\nnow, err := t.clocks.GetTime(c)\nif err == nil && c == sentrytime.Monotonic {\nnow += t.monotonicOffset\n+ for {\n+ // It's possible that the clock is shaky. This may be due to\n+ // platform issues, e.g. the KVM platform relies on the guest\n+ // TSC and host TSC, which may not be perfectly in sync. To\n+ // work around this issue, ensure that the monotonic time is\n+ // always bounded by the last time read.\n+ oldLowerBound := atomic.LoadInt64(&t.monotonicLowerBound)\n+ if now < oldLowerBound {\n+ now = oldLowerBound\n+ break\n+ }\n+ if atomic.CompareAndSwapInt64(&t.monotonicLowerBound, oldLowerBound, now) {\n+ break\n+ }\n+ }\n}\nreturn now, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix flaky monotonic time.
This change ensures that even platforms with some TSC issues (e.g. KVM),
can get reliable monotonic time by applied a lower bound on each read.
PiperOrigin-RevId: 309773801 |
259,992 | 04.05.2020 11:41:38 | 25,200 | 0a307d00726af987793204ef84ac89df064257e6 | Mount VSFS2 filesystem using root credentials | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader_test.go",
"new_path": "runsc/boot/loader_test.go",
"diff": "@@ -438,7 +438,6 @@ func createMountTestcases(vfs2 bool) []*CreateMountTestcase {\n// Test that MountNamespace can be created with various specs.\nfunc TestCreateMountNamespace(t *testing.T) {\n-\nfor _, tc := range createMountTestcases(false /* vfs2 */) {\nt.Run(tc.name, func(t *testing.T) {\nconf := testConfig()\n@@ -476,7 +475,6 @@ func TestCreateMountNamespace(t *testing.T) {\n// Test that MountNamespace can be created with various specs.\nfunc TestCreateMountNamespaceVFS2(t *testing.T) {\n-\nfor _, tc := range createMountTestcases(true /* vfs2 */) {\nt.Run(tc.name, func(t *testing.T) {\ndefer resetSyscallTable()\n@@ -485,6 +483,7 @@ func TestCreateMountNamespaceVFS2(t *testing.T) {\nspec.Mounts = tc.spec.Mounts\nspec.Root = tc.spec.Root\n+ t.Logf(\"Using root: %q\", spec.Root.Path)\nl, loaderCleanup, err := createLoader(true /* VFS2 Enabled */, spec)\nif err != nil {\nt.Fatalf(\"failed to create loader: %v\", err)\n@@ -497,7 +496,7 @@ func TestCreateMountNamespaceVFS2(t *testing.T) {\nt.Fatalf(\"failed process hints: %v\", err)\n}\n- ctx := l.rootProcArgs.NewContext(l.k)\n+ ctx := l.k.SupervisorContext()\nmns, err := mntr.setupVFS2(ctx, l.conf, &l.rootProcArgs)\nif err != nil {\nt.Fatalf(\"failed to setupVFS2: %v\", err)\n@@ -506,7 +505,6 @@ func TestCreateMountNamespaceVFS2(t *testing.T) {\nroot := mns.Root()\ndefer root.DecRef()\nfor _, p := range tc.expectedPaths {\n-\ntarget := &vfs.PathOperation{\nRoot: root,\nStart: root,\n@@ -518,7 +516,6 @@ func TestCreateMountNamespaceVFS2(t *testing.T) {\n} else {\nd.DecRef()\n}\n-\n}\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -166,30 +166,28 @@ func (c *containerMounter) setupVFS2(ctx context.Context, conf *Config, procArgs\n// Create context with root credentials to mount the filesystem (the current\n// user may not be privileged enough).\n+ rootCreds := auth.NewRootCredentials(procArgs.Credentials.UserNamespace)\nrootProcArgs := *procArgs\nrootProcArgs.WorkingDirectory = \"/\"\n- rootProcArgs.Credentials = auth.NewRootCredentials(procArgs.Credentials.UserNamespace)\n+ rootProcArgs.Credentials = rootCreds\nrootProcArgs.Umask = 0022\nrootProcArgs.MaxSymlinkTraversals = linux.MaxSymlinkTraversals\nrootCtx := procArgs.NewContext(c.k)\n- creds := procArgs.Credentials\n- if err := registerFilesystems(rootCtx, c.k.VFS(), creds); err != nil {\n+ if err := registerFilesystems(rootCtx, c.k.VFS(), rootCreds); err != nil {\nreturn nil, fmt.Errorf(\"register filesystems: %w\", err)\n}\n- mns, err := c.createMountNamespaceVFS2(ctx, conf, creds)\n+ mns, err := c.createMountNamespaceVFS2(rootCtx, conf, rootCreds)\nif err != nil {\nreturn nil, fmt.Errorf(\"creating mount namespace: %w\", err)\n}\n-\nrootProcArgs.MountNamespaceVFS2 = mns\n// Mount submounts.\n- if err := c.mountSubmountsVFS2(rootCtx, conf, mns, creds); err != nil {\n+ if err := c.mountSubmountsVFS2(rootCtx, conf, mns, rootCreds); err != nil {\nreturn nil, fmt.Errorf(\"mounting submounts vfs2: %w\", err)\n}\n-\nreturn mns, nil\n}\n@@ -318,7 +316,6 @@ func p9MountOptionsVFS2(fd int, fa FileAccessType) []string {\n}\nfunc (c *containerMounter) makeSyntheticMount(ctx context.Context, currentPath string, root vfs.VirtualDentry, creds *auth.Credentials) error {\n-\ntarget := &vfs.PathOperation{\nRoot: root,\nStart: root,\n@@ -327,12 +324,10 @@ func (c *containerMounter) makeSyntheticMount(ctx context.Context, currentPath s\n_, err := c.k.VFS().StatAt(ctx, creds, target, &vfs.StatOptions{})\nswitch {\n-\ncase err == syserror.ENOENT:\nif err := c.makeSyntheticMount(ctx, path.Dir(currentPath), root, creds); err != nil {\nreturn err\n}\n-\nmkdirOpts := &vfs.MkdirOptions{Mode: 0777, ForSyntheticMountpoint: true}\nif err := c.k.VFS().MkdirAt(ctx, creds, target, mkdirOpts); err != nil {\nreturn fmt.Errorf(\"failed to makedir for mount %+v: %w\", target, err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mount VSFS2 filesystem using root credentials
PiperOrigin-RevId: 309787938 |
259,992 | 04.05.2020 12:27:38 | 25,200 | e2b0e0e272cda5174e17263763f4b78c70a2d927 | Enable TestRunNonRoot on VFS2
Also added back the default test dimension back which was
dropped in a previous refactor. | [
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -256,6 +256,8 @@ var (\nfunc configs(t *testing.T, opts ...configOption) map[string]*boot.Config {\n// Always load the default config.\ncs := make(map[string]*boot.Config)\n+ cs[\"default\"] = testutil.TestConfig(t)\n+\nfor _, o := range opts {\nswitch o {\ncase overlay:\n@@ -281,7 +283,7 @@ func configs(t *testing.T, opts ...configOption) map[string]*boot.Config {\nreturn cs\n}\n-func configsWithVFS2(t *testing.T, opts []configOption) map[string]*boot.Config {\n+func configsWithVFS2(t *testing.T, opts ...configOption) map[string]*boot.Config {\nvfs1 := configs(t, opts...)\nvfs2 := configs(t, opts...)\n@@ -302,7 +304,7 @@ func TestLifecycle(t *testing.T) {\nchildReaper.Start()\ndefer childReaper.Stop()\n- for name, conf := range configsWithVFS2(t, all) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\n// The container will just sleep for a long time. We will kill it before\n// it finishes sleeping.\n@@ -476,7 +478,7 @@ func TestExePath(t *testing.T) {\nt.Fatalf(\"error making directory: %v\", err)\n}\n- for name, conf := range configsWithVFS2(t, []configOption{overlay}) {\n+ for name, conf := range configsWithVFS2(t, overlay) {\nt.Run(name, func(t *testing.T) {\nfor _, test := range []struct {\npath string\n@@ -1297,7 +1299,7 @@ func TestCapabilities(t *testing.T) {\n// TestRunNonRoot checks that sandbox can be configured when running as\n// non-privileged user.\nfunc TestRunNonRoot(t *testing.T) {\n- for name, conf := range configs(t, noOverlay...) {\n+ for name, conf := range configsWithVFS2(t, noOverlay...) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/true\")\n@@ -1341,7 +1343,7 @@ func TestRunNonRoot(t *testing.T) {\n// TestMountNewDir checks that runsc will create destination directory if it\n// doesn't exit.\nfunc TestMountNewDir(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, []configOption{overlay}) {\n+ for name, conf := range configsWithVFS2(t, overlay) {\nt.Run(name, func(t *testing.T) {\nroot, err := ioutil.TempDir(testutil.TmpDir(), \"root\")\nif err != nil {\n@@ -1370,7 +1372,7 @@ func TestMountNewDir(t *testing.T) {\n}\nfunc TestReadonlyRoot(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, []configOption{overlay}) {\n+ for name, conf := range configsWithVFS2(t, overlay) {\nt.Run(name, func(t *testing.T) {\nspec := testutil.NewSpecWithArgs(\"/bin/touch\", \"/foo\")\nspec.Root.Readonly = true\n@@ -1488,7 +1490,7 @@ func TestUIDMap(t *testing.T) {\n}\nfunc TestReadonlyMount(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, []configOption{overlay}) {\n+ for name, conf := range configsWithVFS2(t, overlay) {\nt.Run(name, func(t *testing.T) {\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"ro-mount\")\nspec := testutil.NewSpecWithArgs(\"/bin/touch\", path.Join(dir, \"file\"))\n@@ -1764,7 +1766,7 @@ func TestUserLog(t *testing.T) {\n}\nfunc TestWaitOnExitedSandbox(t *testing.T) {\n- for name, conf := range configsWithVFS2(t, all) {\n+ for name, conf := range configsWithVFS2(t, all...) {\nt.Run(name, func(t *testing.T) {\n// Run a shell that sleeps for 1 second and then exits with a\n// non-zero code.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable TestRunNonRoot on VFS2
Also added back the default test dimension back which was
dropped in a previous refactor.
PiperOrigin-RevId: 309797327 |
259,853 | 04.05.2020 12:57:04 | 25,200 | 006f9788291359fc871b2fa7b82338912af7abb7 | Deflake //third_party/gvisor/test/syscalls:proc_test_native
There is the known issue of the linux procfs, that two consequent calls of
readdir can return the same entry twice if between these calls one or more
entries have been removed from this directory. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc.cc",
"new_path": "test/syscalls/linux/proc.cc",
"diff": "@@ -1939,7 +1939,16 @@ TEST(ProcSelfMounts, RequiredFieldsArePresent) {\n}\nvoid CheckDuplicatesRecursively(std::string path) {\n+ std::vector<std::string> child_dirs;\n+\n+ // There is the known issue of the linux procfs, that two consequent calls of\n+ // readdir can return the same entry twice if between these calls one or more\n+ // entries have been removed from this directory.\n+ int max_attempts = 5;\n+ for (int i = 0; i < max_attempts; i++) {\n+ child_dirs.clear();\nerrno = 0;\n+ bool success = true;\nDIR* dir = opendir(path.c_str());\nif (dir == nullptr) {\n// Ignore any directories we can't read or missing directories as the\n@@ -1951,10 +1960,10 @@ void CheckDuplicatesRecursively(std::string path) {\nstd::unordered_set<std::string> children;\nwhile (true) {\n// Readdir(3): If the end of the directory stream is reached, NULL is\n- // returned and errno is not changed. If an error occurs, NULL is returned\n- // and errno is set appropriately. To distinguish end of stream and from an\n- // error, set errno to zero before calling readdir() and then check the\n- // value of errno if NULL is returned.\n+ // returned and errno is not changed. If an error occurs, NULL is\n+ // returned and errno is set appropriately. To distinguish end of stream\n+ // and from an error, set errno to zero before calling readdir() and then\n+ // check the value of errno if NULL is returned.\nerrno = 0;\nstruct dirent* dp = readdir(dir);\nif (dp == nullptr) {\n@@ -1966,16 +1975,30 @@ void CheckDuplicatesRecursively(std::string path) {\ncontinue;\n}\n+ // Ignore a duplicate entry if it isn't the last attempt.\n+ if (i == max_attempts - 1) {\nASSERT_EQ(children.find(std::string(dp->d_name)), children.end())\n- << dp->d_name;\n+ << absl::StrCat(path, \"/\", dp->d_name);\n+ } else if (children.find(std::string(dp->d_name)) != children.end()) {\n+ std::cerr << \"Duplicate entry: \" << i << \":\"\n+ << absl::StrCat(path, \"/\", dp->d_name) << std::endl;\n+ success = false;\n+ break;\n+ }\nchildren.insert(std::string(dp->d_name));\nASSERT_NE(dp->d_type, DT_UNKNOWN);\n- if (dp->d_type != DT_DIR) {\n- continue;\n+ if (dp->d_type == DT_DIR) {\n+ child_dirs.push_back(std::string(dp->d_name));\n+ }\n+ }\n+ if (success) {\n+ break;\n+ }\n}\n- CheckDuplicatesRecursively(absl::StrCat(path, \"/\", dp->d_name));\n+ for (auto dname = child_dirs.begin(); dname != child_dirs.end(); dname++) {\n+ CheckDuplicatesRecursively(absl::StrCat(path, \"/\", *dname));\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake //third_party/gvisor/test/syscalls:proc_test_native
There is the known issue of the linux procfs, that two consequent calls of
readdir can return the same entry twice if between these calls one or more
entries have been removed from this directory.
PiperOrigin-RevId: 309803066 |
259,992 | 04.05.2020 13:39:15 | 25,200 | 57dbd7f3624528a416664a618ce9edd4c9096d8d | Remove kernfs.Filesystem cast from GenericDirectoryFD
This allows for kerfs.Filesystem to be overridden by
different implementations.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"new_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/memmap\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n@@ -36,12 +37,19 @@ import (\n// inode.\n//\n// Must be initialize with Init before first use.\n+//\n+// Lock ordering: mu => children.mu.\ntype GenericDirectoryFD struct {\nvfs.FileDescriptionDefaultImpl\nvfs.DirectoryFileDescriptionDefaultImpl\nvfsfd vfs.FileDescription\nchildren *OrderedChildren\n+\n+ // mu protects the fields below.\n+ mu sync.Mutex\n+\n+ // off is the current directory offset. Protected by \"mu\".\noff int64\n}\n@@ -115,17 +123,13 @@ func (fd *GenericDirectoryFD) inode() Inode {\n// IterDirents implements vfs.FileDecriptionImpl.IterDirents. IterDirents holds\n// o.mu when calling cb.\nfunc (fd *GenericDirectoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback) error {\n- vfsFS := fd.filesystem()\n- fs := vfsFS.Impl().(*Filesystem)\n- vfsd := fd.vfsfd.VirtualDentry().Dentry()\n-\n- fs.mu.Lock()\n- defer fs.mu.Unlock()\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\nopts := vfs.StatOptions{Mask: linux.STATX_INO}\n// Handle \".\".\nif fd.off == 0 {\n- stat, err := fd.inode().Stat(vfsFS, opts)\n+ stat, err := fd.inode().Stat(fd.filesystem(), opts)\nif err != nil {\nreturn err\n}\n@@ -143,8 +147,9 @@ func (fd *GenericDirectoryFD) IterDirents(ctx context.Context, cb vfs.IterDirent\n// Handle \"..\".\nif fd.off == 1 {\n+ vfsd := fd.vfsfd.VirtualDentry().Dentry()\nparentInode := genericParentOrSelf(vfsd.Impl().(*Dentry)).inode\n- stat, err := parentInode.Stat(vfsFS, opts)\n+ stat, err := parentInode.Stat(fd.filesystem(), opts)\nif err != nil {\nreturn err\n}\n@@ -168,7 +173,7 @@ func (fd *GenericDirectoryFD) IterDirents(ctx context.Context, cb vfs.IterDirent\nchildIdx := fd.off - 2\nfor it := fd.children.nthLocked(childIdx); it != nil; it = it.Next() {\ninode := it.Dentry.Impl().(*Dentry).inode\n- stat, err := inode.Stat(vfsFS, opts)\n+ stat, err := inode.Stat(fd.filesystem(), opts)\nif err != nil {\nreturn err\n}\n@@ -192,9 +197,8 @@ func (fd *GenericDirectoryFD) IterDirents(ctx context.Context, cb vfs.IterDirent\n// Seek implements vfs.FileDecriptionImpl.Seek.\nfunc (fd *GenericDirectoryFD) Seek(ctx context.Context, offset int64, whence int32) (int64, error) {\n- fs := fd.filesystem().Impl().(*Filesystem)\n- fs.mu.Lock()\n- defer fs.mu.Unlock()\n+ fd.mu.Lock()\n+ defer fd.mu.Unlock()\nswitch whence {\ncase linux.SEEK_SET:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove kernfs.Filesystem cast from GenericDirectoryFD
This allows for kerfs.Filesystem to be overridden by
different implementations.
Updates #1672
PiperOrigin-RevId: 309809321 |
259,992 | 05.05.2020 09:18:21 | 25,200 | b3bd41434c17a95a87d67490f2b9bfd71e1ad705 | Return correct name for imported host files
Implement PrependPath() in host.filesystem to correctly format
name for host files.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"new_path": "pkg/sentry/fsimpl/devpts/devpts.go",
"diff": "@@ -59,7 +59,7 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n// master inode. It returns the filesystem and root Dentry.\nfunc (fstype FilesystemType) newFilesystem(vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials) (*kernfs.Filesystem, *kernfs.Dentry) {\nfs := &kernfs.Filesystem{}\n- fs.Init(vfsObj, fstype)\n+ fs.VFSFilesystem().Init(vfsObj, fstype, fs)\n// Construct the root directory. This is always inode id 1.\nroot := &rootInode{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -20,6 +20,7 @@ go_library(\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/fdnotifier\",\n+ \"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/sentry/arch\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/refs\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n@@ -39,37 +40,9 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// filesystemType implements vfs.FilesystemType.\n-type filesystemType struct{}\n-\n-// GetFilesystem implements FilesystemType.GetFilesystem.\n-func (filesystemType) GetFilesystem(context.Context, *vfs.VirtualFilesystem, *auth.Credentials, string, vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n- panic(\"host.filesystemType.GetFilesystem should never be called\")\n-}\n-\n-// Name implements FilesystemType.Name.\n-func (filesystemType) Name() string {\n- return \"none\"\n-}\n-\n-// filesystem implements vfs.FilesystemImpl.\n-type filesystem struct {\n- kernfs.Filesystem\n-}\n-\n-// NewFilesystem sets up and returns a new hostfs filesystem.\n-//\n-// Note that there should only ever be one instance of host.filesystem,\n-// a global mount for host fds.\n-func NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n- fs := &filesystem{}\n- fs.Init(vfsObj, filesystemType{})\n- return fs.VFSFilesystem()\n-}\n-\n// ImportFD sets up and returns a vfs.FileDescription from a donated fd.\nfunc ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs.FileDescription, error) {\n- fs, ok := mnt.Filesystem().Impl().(*kernfs.Filesystem)\n+ fs, ok := mnt.Filesystem().Impl().(*filesystem)\nif !ok {\nreturn nil, fmt.Errorf(\"can't import host FDs into filesystems of type %T\", mnt.Filesystem().Impl())\n}\n@@ -119,12 +92,47 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\nd := &kernfs.Dentry{}\nd.Init(i)\n+\n// i.open will take a reference on d.\ndefer d.DecRef()\n-\nreturn i.open(ctx, d.VFSDentry(), mnt)\n}\n+// filesystemType implements vfs.FilesystemType.\n+type filesystemType struct{}\n+\n+// GetFilesystem implements FilesystemType.GetFilesystem.\n+func (filesystemType) GetFilesystem(context.Context, *vfs.VirtualFilesystem, *auth.Credentials, string, vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ panic(\"host.filesystemType.GetFilesystem should never be called\")\n+}\n+\n+// Name implements FilesystemType.Name.\n+func (filesystemType) Name() string {\n+ return \"none\"\n+}\n+\n+// NewFilesystem sets up and returns a new hostfs filesystem.\n+//\n+// Note that there should only ever be one instance of host.filesystem,\n+// a global mount for host fds.\n+func NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n+ fs := &filesystem{}\n+ fs.VFSFilesystem().Init(vfsObj, filesystemType{}, fs)\n+ return fs.VFSFilesystem()\n+}\n+\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n+ kernfs.Filesystem\n+}\n+\n+func (fs *filesystem) PrependPath(ctx context.Context, vfsroot, vd vfs.VirtualDentry, b *fspath.Builder) error {\n+ d := vd.Dentry().Impl().(*kernfs.Dentry)\n+ inode := d.Inode().(*inode)\n+ b.PrependComponent(fmt.Sprintf(\"host:[%d]\", inode.ino))\n+ return vfs.PrependPathSyntheticError{}\n+}\n+\n// inode implements kernfs.Inode.\ntype inode struct {\nkernfs.InodeNotDirectory\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -132,13 +132,6 @@ func (fs *Filesystem) processDeferredDecRefsLocked() {\nfs.droppedDentriesMu.Unlock()\n}\n-// Init initializes a kernfs filesystem. This should be called from during\n-// vfs.FilesystemType.NewFilesystem for the concrete filesystem embedding\n-// kernfs.\n-func (fs *Filesystem) Init(vfsObj *vfs.VirtualFilesystem, fsType vfs.FilesystemType) {\n- fs.vfsfs.Init(vfsObj, fsType, fs)\n-}\n-\n// VFSFilesystem returns the generic vfs filesystem object.\nfunc (fs *Filesystem) VFSFilesystem() *vfs.Filesystem {\nreturn &fs.vfsfs\n@@ -261,6 +254,11 @@ func (d *Dentry) insertChildLocked(name string, child *Dentry) {\nd.children[name] = child\n}\n+// Inode returns the dentry's inode.\n+func (d *Dentry) Inode() Inode {\n+ return d.inode\n+}\n+\n// The Inode interface maps filesystem-level operations that operate on paths to\n// equivalent operations on specific filesystem nodes.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"diff": "@@ -195,7 +195,7 @@ func (fsType) Name() string {\nfunc (fst fsType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opt vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\nfs := &filesystem{}\n- fs.Init(vfsObj, &fst)\n+ fs.VFSFilesystem().Init(vfsObj, &fst, fs)\nroot := fst.rootFn(creds, fs)\nreturn fs.VFSFilesystem(), root.VFSDentry(), nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/pipefs/pipefs.go",
"new_path": "pkg/sentry/fsimpl/pipefs/pipefs.go",
"diff": "@@ -40,10 +40,6 @@ func (filesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFile\npanic(\"pipefs.filesystemType.GetFilesystem should never be called\")\n}\n-// filesystem implements vfs.FilesystemImpl.\n-type filesystem struct {\n- kernfs.Filesystem\n-\n// TODO(gvisor.dev/issue/1193):\n//\n// - kernfs does not provide a way to implement statfs, from which we\n@@ -52,13 +48,11 @@ type filesystem struct {\n// - kernfs does not provide a way to override names for\n// vfs.FilesystemImpl.PrependPath(); pipefs inodes should use synthetic\n// name fmt.Sprintf(\"pipe:[%d]\", inode.ino).\n-}\n-// NewFilesystem sets up and returns a new vfs.Filesystem implemented by\n-// pipefs.\n+// NewFilesystem sets up and returns a new vfs.Filesystem implemented by pipefs.\nfunc NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n- fs := &filesystem{}\n- fs.Init(vfsObj, filesystemType{})\n+ fs := &kernfs.Filesystem{}\n+ fs.VFSFilesystem().Init(vfsObj, filesystemType{}, fs)\nreturn fs.VFSFilesystem()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"new_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"diff": "@@ -41,18 +41,13 @@ func (filesystemType) Name() string {\nreturn \"sockfs\"\n}\n-// filesystem implements vfs.FilesystemImpl.\n-type filesystem struct {\n- kernfs.Filesystem\n-}\n-\n// NewFilesystem sets up and returns a new sockfs filesystem.\n//\n// Note that there should only ever be one instance of sockfs.Filesystem,\n// backing a global socket mount.\nfunc NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n- fs := &filesystem{}\n- fs.Init(vfsObj, filesystemType{})\n+ fs := &kernfs.Filesystem{}\n+ fs.VFSFilesystem().Init(vfsObj, filesystemType{}, fs)\nreturn fs.VFSFilesystem()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sys/sys.go",
"new_path": "pkg/sentry/fsimpl/sys/sys.go",
"diff": "@@ -47,7 +47,7 @@ func (FilesystemType) Name() string {\n// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\nfunc (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\nfs := &filesystem{}\n- fs.Filesystem.Init(vfsObj, &fsType)\n+ fs.VFSFilesystem().Init(vfsObj, &fsType, fs)\nk := kernel.KernelFromContext(ctx)\nmaxCPUCores := k.ApplicationCores()\ndefaultSysDirMode := linux.FileMode(0755)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return correct name for imported host files
Implement PrependPath() in host.filesystem to correctly format
name for host files.
Updates #1672
PiperOrigin-RevId: 309959135 |
259,860 | 05.05.2020 10:00:02 | 25,200 | a6dbf9596de58f1a264c236bf5afb8dfcfe78174 | Update comments for synthetic gofer files in vfs2. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -686,6 +686,8 @@ func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\nreturn fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, name string) error {\ncreds := rp.Credentials()\n_, err := parent.file.mknod(ctx, name, (p9.FileMode)(opts.Mode), opts.DevMajor, opts.DevMinor, (p9.UID)(creds.EffectiveKUID), (p9.GID)(creds.EffectiveKGID))\n+ // If the gofer does not allow creating a socket or pipe, create a\n+ // synthetic one, i.e. one that is kept entirely in memory.\nif err == syserror.EPERM {\nswitch opts.Mode.FileType() {\ncase linux.S_IFSOCK:\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -496,10 +496,8 @@ type dentry struct {\n// file is the unopened p9.File that backs this dentry. file is immutable.\n//\n// If file.isNil(), this dentry represents a synthetic file, i.e. a file\n- // that does not exist on the remote filesystem. As of this writing, this\n- // is only possible for a directory created with\n- // MkdirOptions.ForSyntheticMountpoint == true.\n- // TODO(gvisor.dev/issue/1476): Support synthetic sockets (and pipes).\n+ // that does not exist on the remote filesystem. As of this writing, the\n+ // only files that can be synthetic are sockets, pipes, and directories.\nfile p9file\n// If deleted is non-zero, the file represented by this dentry has been\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update comments for synthetic gofer files in vfs2.
PiperOrigin-RevId: 309966538 |
259,860 | 05.05.2020 12:09:39 | 25,200 | faf89dd31a44b8409b32919d7193834e194ecc56 | Update vfs2 socket TODOs.
Three updates:
Mark all vfs2 socket syscalls as supported.
Use the same dev number and ino number generator for all types of sockets,
unlike in VFS1.
Do not use host fd for hostinet metadata.
Fixes 1485, | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"new_path": "pkg/sentry/fsimpl/sockfs/sockfs.go",
"diff": "@@ -53,9 +53,7 @@ func NewFilesystem(vfsObj *vfs.VirtualFilesystem) *vfs.Filesystem {\n// inode implements kernfs.Inode.\n//\n-// TODO(gvisor.dev/issue/1476): Add device numbers to this inode (which are\n-// not included in InodeAttrs) to store the numbers of the appropriate\n-// socket device. Override InodeAttrs.Stat() accordingly.\n+// TODO(gvisor.dev/issue/1193): Device numbers.\ntype inode struct {\nkernfs.InodeNotDirectory\nkernfs.InodeNotSymlink\n@@ -69,11 +67,6 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\n}\n// NewDentry constructs and returns a sockfs dentry.\n-//\n-// TODO(gvisor.dev/issue/1476): Currently, we are using\n-// sockfs.filesystem.NextIno() to get inode numbers. We should use\n-// device-specific numbers, so that we are not using the same generator for\n-// netstack, unix, etc.\nfunc NewDentry(creds *auth.Credentials, ino uint64) *vfs.Dentry {\n// File mode matches net/socket.c:sock_alloc.\nfilemode := linux.FileMode(linux.S_IFSOCK | 0600)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/socket_vfs2.go",
"new_path": "pkg/sentry/socket/hostinet/socket_vfs2.go",
"diff": "@@ -36,8 +36,11 @@ import (\ntype socketVFS2 struct {\nvfsfd vfs.FileDescription\nvfs.FileDescriptionDefaultImpl\n- // TODO(gvisor.dev/issue/1484): VFS1 stores internal metadata for hostinet.\n- // We should perhaps rely on the host, much like in hostfs.\n+\n+ // We store metadata for hostinet sockets internally. Technically, we should\n+ // access metadata (e.g. through stat, chmod) on the host for correctness,\n+ // but this is not very useful for inet socket fds, which do not belong to a\n+ // concrete file anyway.\nvfs.DentryMetadataFileDescriptionImpl\nsocketOpsCommon\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go",
"new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netfilter\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n@@ -41,6 +42,8 @@ type SocketVFS2 struct {\nsocketOpsCommon\n}\n+var _ = socket.SocketVFS2(&SocketVFS2{})\n+\n// NewVFS2 creates a new endpoint socket.\nfunc NewVFS2(t *kernel.Task, family int, skType linux.SockType, protocol int, queue *waiter.Queue, endpoint tcpip.Endpoint) (*vfs.FileDescription, *syserr.Error) {\nif skType == linux.SOCK_STREAM {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"new_path": "pkg/sentry/socket/unix/unix_vfs2.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/control\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netstack\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n@@ -43,6 +44,8 @@ type SocketVFS2 struct {\nsocketOpsCommon\n}\n+var _ = socket.SocketVFS2(&SocketVFS2{})\n+\n// NewSockfsFile creates a new socket file in the global sockfs mount and\n// returns a corresponding file description.\nfunc NewSockfsFile(t *kernel.Task, ep transport.Endpoint, stype linux.SockType) (*vfs.FileDescription, *syserr.Error) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/linux64_override_amd64.go",
"diff": "@@ -44,22 +44,21 @@ func Override(table map[uintptr]kernel.Syscall) {\ntable[32] = syscalls.Supported(\"dup\", Dup)\ntable[33] = syscalls.Supported(\"dup2\", Dup2)\ndelete(table, 40) // sendfile\n- // TODO(gvisor.dev/issue/1485): Port all socket variants to VFS2.\n- table[41] = syscalls.PartiallySupported(\"socket\", Socket, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[42] = syscalls.PartiallySupported(\"connect\", Connect, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[43] = syscalls.PartiallySupported(\"accept\", Accept, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[44] = syscalls.PartiallySupported(\"sendto\", SendTo, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[45] = syscalls.PartiallySupported(\"recvfrom\", RecvFrom, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[46] = syscalls.PartiallySupported(\"sendmsg\", SendMsg, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[47] = syscalls.PartiallySupported(\"recvmsg\", RecvMsg, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[48] = syscalls.PartiallySupported(\"shutdown\", Shutdown, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[49] = syscalls.PartiallySupported(\"bind\", Bind, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[50] = syscalls.PartiallySupported(\"listen\", Listen, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[51] = syscalls.PartiallySupported(\"getsockname\", GetSockName, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[52] = syscalls.PartiallySupported(\"getpeername\", GetPeerName, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[53] = syscalls.PartiallySupported(\"socketpair\", SocketPair, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[54] = syscalls.PartiallySupported(\"setsockopt\", SetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\n- table[55] = syscalls.PartiallySupported(\"getsockopt\", GetSockOpt, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[41] = syscalls.Supported(\"socket\", Socket)\n+ table[42] = syscalls.Supported(\"connect\", Connect)\n+ table[43] = syscalls.Supported(\"accept\", Accept)\n+ table[44] = syscalls.Supported(\"sendto\", SendTo)\n+ table[45] = syscalls.Supported(\"recvfrom\", RecvFrom)\n+ table[46] = syscalls.Supported(\"sendmsg\", SendMsg)\n+ table[47] = syscalls.Supported(\"recvmsg\", RecvMsg)\n+ table[48] = syscalls.Supported(\"shutdown\", Shutdown)\n+ table[49] = syscalls.Supported(\"bind\", Bind)\n+ table[50] = syscalls.Supported(\"listen\", Listen)\n+ table[51] = syscalls.Supported(\"getsockname\", GetSockName)\n+ table[52] = syscalls.Supported(\"getpeername\", GetPeerName)\n+ table[53] = syscalls.Supported(\"socketpair\", SocketPair)\n+ table[54] = syscalls.Supported(\"setsockopt\", SetSockOpt)\n+ table[55] = syscalls.Supported(\"getsockopt\", GetSockOpt)\ntable[59] = syscalls.Supported(\"execve\", Execve)\ntable[72] = syscalls.Supported(\"fcntl\", Fcntl)\ndelete(table, 73) // flock\n@@ -145,8 +144,7 @@ func Override(table map[uintptr]kernel.Syscall) {\ndelete(table, 285) // fallocate\ntable[286] = syscalls.Supported(\"timerfd_settime\", TimerfdSettime)\ntable[287] = syscalls.Supported(\"timerfd_gettime\", TimerfdGettime)\n- // TODO(gvisor.dev/issue/1485): Port all socket variants to VFS2.\n- table[288] = syscalls.PartiallySupported(\"accept4\", Accept4, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[288] = syscalls.Supported(\"accept4\", Accept4)\ndelete(table, 289) // signalfd4\ntable[290] = syscalls.Supported(\"eventfd2\", Eventfd2)\ntable[291] = syscalls.Supported(\"epoll_create1\", EpollCreate1)\n@@ -155,11 +153,9 @@ func Override(table map[uintptr]kernel.Syscall) {\ndelete(table, 294) // inotify_init1\ntable[295] = syscalls.Supported(\"preadv\", Preadv)\ntable[296] = syscalls.Supported(\"pwritev\", Pwritev)\n- // TODO(gvisor.dev/issue/1485): Port all socket variants to VFS2.\n- table[299] = syscalls.PartiallySupported(\"recvmmsg\", RecvMMsg, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[299] = syscalls.Supported(\"recvmmsg\", RecvMMsg)\ntable[306] = syscalls.Supported(\"syncfs\", Syncfs)\n- // TODO(gvisor.dev/issue/1485): Port all socket variants to VFS2.\n- table[307] = syscalls.PartiallySupported(\"sendmmsg\", SendMMsg, \"In process of porting socket syscalls to VFS2.\", nil)\n+ table[307] = syscalls.Supported(\"sendmmsg\", SendMMsg)\ntable[316] = syscalls.Supported(\"renameat2\", Renameat2)\ndelete(table, 319) // memfd_create\ntable[322] = syscalls.Supported(\"execveat\", Execveat)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update vfs2 socket TODOs.
Three updates:
- Mark all vfs2 socket syscalls as supported.
- Use the same dev number and ino number generator for all types of sockets,
unlike in VFS1.
- Do not use host fd for hostinet metadata.
Fixes #1476, #1478, #1484, 1485, #2017.
PiperOrigin-RevId: 309994579 |
259,853 | 05.05.2020 15:59:27 | 25,200 | 9509c0b3886f29b488a62d0cc8edde9ccdefa335 | gvisor/test: use RetryEINTR for connect()
connect() returns EINTR after S/R and usually we
use RetryEINTR to workaround this. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_inet_loopback.cc",
"new_path": "test/syscalls/linux/socket_inet_loopback.cc",
"diff": "@@ -162,7 +162,7 @@ TEST_P(DualStackSocketTest, AddressOperations) {\nASSERT_NO_ERRNO(SetAddrPort(\naddr.family(), const_cast<sockaddr_storage*>(&addr.addr), 1337));\n- EXPECT_THAT(connect(fd.get(), addr_in, addr.addr_len),\n+ EXPECT_THAT(RetryEINTR(connect)(fd.get(), addr_in, addr.addr_len),\nSyscallSucceeds())\n<< GetAddrStr(addr_in);\nbound = true;\n@@ -353,7 +353,8 @@ TEST_P(SocketInetLoopbackTest, TCPListenShutdownListen) {\nfor (int i = 0; i < kBacklog; i++) {\nauto client = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n- ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(client.get(),\n+ reinterpret_cast<sockaddr*>(&conn_addr),\nconnector.addr_len),\nSyscallSucceeds());\n}\n@@ -397,7 +398,8 @@ TEST_P(SocketInetLoopbackTest, TCPListenShutdown) {\nfor (int i = 0; i < kFDs; i++) {\nauto client = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n- ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(client.get(),\n+ reinterpret_cast<sockaddr*>(&conn_addr),\nconnector.addr_len),\nSyscallSucceeds());\nASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());\n@@ -425,7 +427,8 @@ TEST_P(SocketInetLoopbackTest, TCPListenShutdown) {\nfor (int i = 0; i < kFDs; i++) {\nauto client = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\n- ASSERT_THAT(connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(client.get(),\n+ reinterpret_cast<sockaddr*>(&conn_addr),\nconnector.addr_len),\nSyscallFailsWithErrno(ECONNREFUSED));\n}\n@@ -1824,8 +1827,8 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, V6EphemeralPortReserved) {\n// Connect to bind an ephemeral port.\nconst FileDescriptor connected_fd =\nASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));\n- ASSERT_THAT(\n- connect(connected_fd.get(), reinterpret_cast<sockaddr*>(&bound_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\nbound_addr_len),\nSyscallSucceeds());\n@@ -1930,8 +1933,9 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, V6EphemeralPortReservedReuseAddr) {\nASSERT_THAT(setsockopt(connected_fd.get(), SOL_SOCKET, SO_REUSEADDR,\n&kSockOptOn, sizeof(kSockOptOn)),\nSyscallSucceeds());\n- ASSERT_THAT(connect(connected_fd.get(),\n- reinterpret_cast<sockaddr*>(&bound_addr), bound_addr_len),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\n+ bound_addr_len),\nSyscallSucceeds());\n// Get the ephemeral port.\n@@ -1991,8 +1995,8 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedEphemeralPortReserved) {\n// Connect to bind an ephemeral port.\nconst FileDescriptor connected_fd =\nASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));\n- ASSERT_THAT(\n- connect(connected_fd.get(), reinterpret_cast<sockaddr*>(&bound_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\nbound_addr_len),\nSyscallSucceeds());\n@@ -2121,8 +2125,9 @@ TEST_P(SocketMultiProtocolInetLoopbackTest,\nASSERT_THAT(setsockopt(connected_fd.get(), SOL_SOCKET, SO_REUSEADDR,\n&kSockOptOn, sizeof(kSockOptOn)),\nSyscallSucceeds());\n- ASSERT_THAT(connect(connected_fd.get(),\n- reinterpret_cast<sockaddr*>(&bound_addr), bound_addr_len),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\n+ bound_addr_len),\nSyscallSucceeds());\n// Get the ephemeral port.\n@@ -2182,8 +2187,8 @@ TEST_P(SocketMultiProtocolInetLoopbackTest, V4EphemeralPortReserved) {\n// Connect to bind an ephemeral port.\nconst FileDescriptor connected_fd =\nASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));\n- ASSERT_THAT(\n- connect(connected_fd.get(), reinterpret_cast<sockaddr*>(&bound_addr),\n+ ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(),\n+ reinterpret_cast<sockaddr*>(&bound_addr),\nbound_addr_len),\nSyscallSucceeds());\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor/test: use RetryEINTR for connect()
connect() returns EINTR after S/R and usually we
use RetryEINTR to workaround this.
PiperOrigin-RevId: 310038525 |
259,891 | 06.05.2020 13:36:48 | 25,200 | b08222cf3a80a57e77ac4af7a410f188ba01e0f4 | sniffer: fix accidental logging of good packets as bad
We need to check vv.Size() instead of len(tcp), as tcp will always be 20 bytes
long. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -391,7 +391,7 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nbreak\n}\nudp := header.UDP(hdr)\n- if fragmentOffset == 0 && len(udp) >= header.UDPMinimumSize {\n+ if fragmentOffset == 0 {\nsrcPort = udp.SourcePort()\ndstPort = udp.DestinationPort()\ndetails = fmt.Sprintf(\"xsum: 0x%x\", udp.Checksum())\n@@ -405,14 +405,14 @@ func logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, pkt *stack.P\nbreak\n}\ntcp := header.TCP(hdr)\n- if fragmentOffset == 0 && len(tcp) >= header.TCPMinimumSize {\n+ if fragmentOffset == 0 {\noffset := int(tcp.DataOffset())\nif offset < header.TCPMinimumSize {\ndetails += fmt.Sprintf(\"invalid packet: tcp data offset too small %d\", offset)\nbreak\n}\n- if offset > len(tcp) && !moreFragments {\n- details += fmt.Sprintf(\"invalid packet: tcp data offset %d larger than packet buffer length %d\", offset, len(tcp))\n+ if offset > vv.Size() && !moreFragments {\n+ details += fmt.Sprintf(\"invalid packet: tcp data offset %d larger than packet buffer length %d\", offset, vv.Size())\nbreak\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | sniffer: fix accidental logging of good packets as bad
We need to check vv.Size() instead of len(tcp), as tcp will always be 20 bytes
long.
PiperOrigin-RevId: 310218351 |
259,858 | 26.02.2020 22:44:50 | 28,800 | 1e943dcc9eed420731935e0c8aa1f25788584f95 | Add governance and security policies. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "GOVERNANCE.md",
"diff": "+# Governance\n+\n+## Projects\n+\n+A *project* is the primary unit of collaboration. Each project may have its own\n+repository and contribution process.\n+\n+All projects are covered by the [Code of Conduct](CODE_OF_CONDUCT.md), and\n+should include an up-to-date copy in the project repository or a link here.\n+\n+## Contributors\n+\n+Anyone can be a *contributor* to a project, provided they have signed relevant\n+Contributor License Agreements (CLAs) and follow the project's contribution\n+guidelines. Contributions will be reviewed by a maintainer, and must pass all\n+applicable tests.\n+\n+Reviews check for code quality and style, including documentation, and enforce\n+other policies. Contributions may be rejected for reasons unrelated to the code\n+in question. For example, a change may be too complex to maintain or duplicate\n+existing functionality.\n+\n+Note that contributions are not limited to code alone. Bugs, documentation,\n+experience reports or public advocacy are all valuable ways to contribute to a\n+project and build trust in the community.\n+\n+## Maintainers\n+\n+Each project has one or more *maintainers*. Maintainers set technical direction,\n+facilitate contributions and exercise overall stewardship.\n+\n+Maintainers have write access to the project repository. Maintainers review and\n+approve changes. They can also assign issues and add additional reviewers.\n+\n+Note that some repositories may not allow direct commit access, which is\n+reserved for administrators or automated processes. In this case, maintainers\n+have approval rights, and a separate process exists for merging a change.\n+\n+Maintainers are responsible for upholding the code of conduct in interactions\n+via project communication channels. If comments or exchanges are in violation,\n+they may remove them at their discretion.\n+\n+### Repositories requiring synchronization\n+\n+For some projects initiated by Google, the infrastructure which synchronizes and\n+merges internal and external changes requires that merges are performed by a\n+Google employee. In such cases, Google will initiate a rotation to merge changes\n+once they pass tests and are approved by a maintainer. This does not preclude\n+non-Google contributors from becoming maintainers, in which case the maintainer\n+holds approval rights and the merge is an automated process. In some cases,\n+Google-internal tests may fail and have to be fixed: the Google employee will\n+work with the submitter to achieve this.\n+\n+### Becoming a maintainer\n+\n+The list of maintainers is defined by the list of people with commit access or\n+approval authority on a repository, typically via a Gerrit group or a GitHub\n+team.\n+\n+Existing maintainers may elevate a contributor to maintainer status on evidence\n+of previous contributions and established trust. This decision is based on lazy\n+consensus from existing maintainers. While contributors may ask maintainers to\n+make this decision, existing maintainers will also pro-actively identify\n+contributors who have demonstrated a sustained track record of technical\n+leadership and direct contributions.\n+\n+## Special Interest Groups (SIGs)\n+\n+From time-to-time, a SIG may be formed in order to solve larger, more complex\n+problems across one or more projects. There are many avenues for collaboration\n+outside a SIG, but a SIG can provide structure for collaboration on a single\n+topic.\n+\n+Each group will be established by a charter, and governed by the Code of\n+Conduct. Some resources may be provided to the group, such as mailing lists or\n+meeting space, and archives will be public.\n+\n+## Security disclosure\n+\n+Projects may maintain security mailing lists for vulnerability reports and\n+internal project audits may occasionally reveal security issues. Access to these\n+lists and audits will be limited to project *maintainers*; individual\n+maintainers should opt to participate in these lists based on need and\n+expertise. Once maintainers become aware of a potential security issue, they\n+will assess the scope and potential impact. If reported externally, maintainers\n+will determine a reasonable embargo period with the reporter.\n+\n+During the embargo period, the maintainers will prioritize a fix for the\n+security issue. They may choose to disclose the issue to additional trusted\n+contributors in order to facilitate a fix, subjecting them to the embargo, or\n+notify affected users in order to give them an advanced opportunity to mitigate\n+the issue. The inclusion of specific users in this disclosure is left to the\n+discretion of the maintainers and contributors involved, and depends on the\n+scale of known project use and exposure.\n+\n+Once a fix is widely available or the embargo period ends, the maintainers will\n+make technical details about the vulnerability and associated fixes available.\n+\n+## Mailing lists\n+\n+There are four key mailing lists that span projects.\n+\n+* [gvisor-users](mailto:[email protected]): general purpose user list.\n+* [gvisor-dev](mailto:[email protected]): general purpose development list.\n+* [gvisor-security](mailto:[email protected]): private security list.\n+ Access to this list is restricted to maintainers of the core gVisor project,\n+ subject to the security disclosure policy described above.\n+* [gvisor-syzkaller](mailto:[email protected]): private syzkaller bug\n+ tracking list. Access to this list is not limited to maintainers, but will\n+ be granted to those who can credibly contribute to fixes.\n"
},
{
"change_type": "MODIFY",
"old_path": "SECURITY.md",
"new_path": "SECURITY.md",
"diff": "@@ -5,7 +5,7 @@ the [gvisor-security mailing list][gvisor-security-list]. You should receive a\nprompt response, typically within 48 hours.\nPolicies for security list access, vulnerability embargo, and vulnerability\n-disclosure are outlined in the [community][community] repository.\n+disclosure are outlined in the [governance policy](GOVERNANCE.md).\n[community]: https://gvisor.googlesource.com/community\n[gvisor-security-list]: https://groups.google.com/forum/#!forum/gvisor-security\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add governance and security policies. |
259,858 | 21.04.2020 12:49:43 | 25,200 | 228c6ad7ccbf9c61bcf05155c4ab75102b4303c7 | Move new post image. | [
{
"change_type": "MODIFY",
"old_path": "website/content/_posts/2019-11-18-security-basics.md",
"new_path": "website/content/_posts/2019-11-18-security-basics.md",
"diff": "@@ -46,7 +46,7 @@ A simplified version of the design is below ([more detailed version](https://gvi\n----\n-\n+\nFigure 1: Simplified design of gVisor.\n"
},
{
"change_type": "MODIFY",
"old_path": "website/content/_posts/2020-04-02-networking-security.md",
"new_path": "website/content/_posts/2020-04-02-networking-security.md",
"diff": "@@ -28,7 +28,7 @@ To enable networking functionality while preserving gVisor's security properties\n----\n-\n+\nFigure 1: Netstack and gVisor\n"
},
{
"change_type": "RENAME",
"old_path": "website/content/_posts/2020-04-02-networking-security-figure1.png",
"new_path": "website/content/assets/images/2020-04-02-networking-security-figure1.png",
"diff": ""
}
] | Go | Apache License 2.0 | google/gvisor | Move new post image. |
259,858 | 21.04.2020 12:50:18 | 25,200 | 8cb33ce5ded7d417710e7e749524b895deb20397 | Fix cache permissions. | [
{
"change_type": "MODIFY",
"old_path": "website/Makefile",
"new_path": "website/Makefile",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-build:\n+build: content/.jekyll-cache\n@bazel run //runsc -- help syscalls -format json -filename $(PWD)/syscalls.json\n@docker build -t gvisor-website .\n@docker run -v $$PWD:/work -w /work gcr.io/cloud-builders/npm ci\n@$(MAKE) update\n.PHONY: build\n+content/.jekyll-cache:\n+ @mkdir -p $@ && chmod a+rw $@\n+\nlint:\n@docker run -v $$PWD:/work -w /work gcr.io/cloud-builders/npm run lint-md\n.PHONY: lint\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix cache permissions. |
259,858 | 28.04.2020 00:39:29 | 25,200 | b6ba247fa665099fabdf845947a4e1eedb8cce13 | Update main landing page. | [
{
"change_type": "MODIFY",
"old_path": "website/_sass/front.scss",
"new_path": "website/_sass/front.scss",
"diff": "background-position: center;\nbackground-repeat: no-repeat;\nbackground-size: cover;\n+ background-blend-mode: darken;\n+ background-color: rgba(0,0,0,0.1);\np {\n- color: #eeeeee;\n+ color: #fff;\nmargin-top: 0;\nmargin-bottom: 0;\nfont-weight: 300;\n"
},
{
"change_type": "MODIFY",
"old_path": "website/index.md",
"new_path": "website/index.md",
"diff": "---\n-title: gVisor\nlayout: base\n---\n-\n<div class=\"jumbotron jumbotron-fluid\">\n- <div class=\"container text-center\">\n- <p>Efficient defense-in-depth for container infrastructure anywhere.</p>\n+ <div class=\"container\">\n+ <div class=\"row\">\n+ <div class=\"col-md-3\"></div>\n+ <div class=\"col-md-6\">\n+ <p>gVisor is an <b>application kernel</b> and <b>container runtime</b> providing defense-in-depth for containers <em>anywhere</em>.</p>\n<p style=\"margin-top: 20px;\">\n<a class=\"btn\" href=\"/docs/\">Get Started <i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n<a class=\"btn btn-inverse\" href=\"https://github.com/google/gvisor\">GitHub <i class=\"fab fa-github ml-2\"></i></a>\n</p>\n</div>\n-</div>\n-\n-<div class=\"container\"> <!-- Full page container. -->\n-\n-<!--\n-<div class=\"row\">\n<div class=\"col-md-3\"></div>\n- <div class=\"col-md-6\">\n- <h3>gVisor is an open-source application kernel and container runtime for\n- adding defense-in-depth or sandboxing workloads safely and easily. gVisor is\n- a container-native technology, designed to improve container isolation\n- without sacrificing the benefits of container efficiency and\n- portability.</h3>\n</div>\n- <div class=\"col-md-3\"></div>\n</div>\n--->\n+</div>\n-<div class=\"row\">\n+<div class=\"container\"> <!-- Full page container. -->\n+<div class=\"row\">\n<div class=\"col-md-4\">\n- <h4 id=\"seamless-security\">Container-native Security</h4>\n+ <h4 id=\"seamless-security\">Container-native Security <i class=\"fas fa-lock\"></i></h4>\n<p>By providing each container with its own application kernel instance,\ngVisor limits the attack surface of the host while still integrating\nseamlessly with popular container orchestration systems, such as Docker and\n@@ -44,7 +33,7 @@ layout: base\n</div>\n<div class=\"col-md-4\">\n- <h4 id=\"resource-efficiency\">Resource Efficiency</h4>\n+ <h4 id=\"resource-efficiency\">Resource Efficiency <i class=\"fas fa-feather-alt\"></i></h4>\n<p>Containers are efficient because workloads of different shapes and sizes\ncan be packed together by sharing host resources. By using host native\nabstractions such as threads and memory mappings, gVisor closely co-operates\n@@ -56,7 +45,7 @@ layout: base\n</div>\n<div class=\"col-md-4\">\n- <h4 id=\"platform-portability\">Platform Portability</h4>\n+ <h4 id=\"platform-portability\">Platform Portability <sup>☁</sup>☁</h4>\n<p>Modern infrastructure spans multiple clouds and data centers, often using\na mix of virtualized instances and traditional servers. The pluggable\nplatform architecture of gVisor allows it to run anywhere, enabling security\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update main landing page. |
259,858 | 28.04.2020 12:47:28 | 25,200 | f126de6a28b9d64abcab37392cde812957eb9a82 | Add resource model. | [
{
"change_type": "MODIFY",
"old_path": "g3doc/BUILD",
"new_path": "g3doc/BUILD",
"diff": "@@ -8,6 +8,7 @@ package(\ndoc(\nname = \"index\",\nsrc = \"README.md\",\n+ category = \"Project\",\npermalink = \"/docs/\",\nweight = \"0\",\n)\n@@ -20,13 +21,6 @@ doc(\nweight = \"10\",\n)\n-doc(\n- name = \"basics\",\n- src = \"basics.md\",\n- category = \"Project\",\n- permalink = \"/docs/basics/\",\n-)\n-\ndoc(\nname = \"community\",\nsrc = \"community.md\",\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/architecture_guide/resources.md",
"new_path": "g3doc/architecture_guide/resources.md",
"diff": "# Resource Model\n+\n+The resource model for gVisor does not assume a fixed number of threads of\n+execution (i.e. vCPUs) or amount of physical memory. Where possible, decisions\n+about underlying physical resources are delegated to the host system, where\n+optimizations can be made with global information. This delegation allows the\n+sandbox to be highly dynamic in terms of resource usage: spanning a large number\n+of cores and large amount of memory when busy, and yielding those resources back\n+to the host when not.\n+\n+Some of the details here may depend on the [platform](../platforms/), but in\n+general this page describes the resource model used by gVisor. If you're not\n+familiar with the terms here, uou may want to start with the [Overview](../).\n+\n+## Processes\n+\n+Much like a Virtual Machine (VM), a gVisor sandbox appears as an opaque process\n+on the system. Processes within the sandbox do not manifest as processes on the\n+host system, and process-level interactions within the sandbox requires entering\n+the sandbox (e.g. via a [Docker exec][exec]).\n+\n+## Networking\n+\n+Similarly to processes, the sandbox attaches a network endpoint to the system,\n+but runs it's own network stack. All network resources, other than packets in\n+flight, exist only inside the sandbox, bound by relevant resource limits.\n+\n+You can interact with network endpoints exposed by the sandbox, just as you\n+would any other container, but network introspection similarly requires entering\n+the sandbox.\n+\n+## Files\n+\n+Files may be backed by different implementations. For host-native files (where a\n+file descriptor is available), the Gofer may return a file descriptor to the\n+Sentry via [SCM_RIGHTS][scmrights][^1].\n+\n+These files may be read from and written to through standard system calls, and\n+also mapped into the associated application's address space. This allows the\n+same host memory to be shared across multiple sandboxes, although this mechanism\n+does not preclude the use of side-channels (see the [security\n+model](../security/)).\n+\n+Note that some file systems exist only within the context of the sandbox. For\n+example, in many cases a `tmpfs` mount will be available at `/tmp` or\n+`/dev/shm`, which allocates memory directly from the sandbox memory file (see\n+below). Ultimately, these will be accounted against relevant limits in a similar\n+way as the host native case.\n+\n+## Threads\n+\n+The Sentry models individual task threads with [goroutines][goroutine]. As a\n+result, each task thread is a lightweight [green thread][greenthread], and may\n+not correspond to an underlying host thread.\n+\n+However, application execution is modelled as a blocking system call with the\n+Sentry. This means that additional host threads may be created, *depending on\n+the number of active application threads*. In practice, a busy application will\n+converge on the number of active threads, and the host will be able to make\n+scheduling decisions about all application threads.\n+\n+## Time\n+\n+Time in the sandbox is provided by the Sentry, through its own [vDSO][vdso] and\n+timekeeping implementation. This is divorced from the host time, and no state is\n+shared with the host, although the time will be initialized with the host clock.\n+\n+The Sentry runs timers to note the passage of time, much like a kernel running\n+on hardware (though the timers are software timers, in this case). These timers\n+provide updates to the vDSO, the time returned through system calls, and the\n+time recorded for usage or limit tracking (e.g. [RLIMIT_CPU][rlimit]).\n+\n+When all application threads are idle, the Sentry disables timers until an event\n+occurs that wakes either the Sentry or an application thread, similar to a\n+[tickless kernel][tickless]. This allows the Sentry to achieve near zero CPU\n+usage for idle applications.\n+\n+## Memory\n+\n+The Sentry implements its own memory management, including demand-paging and a\n+Sentry internal page cache for files that cannot be used natively. A single\n+[memfd][memfd] backs all application memory.\n+\n+### Address spaces\n+\n+The creation of address spaces is platform-specific. For some platforms,\n+additional \"stub\" processes may be created on the host in order to support\n+additional address spaces. These stubs are subject to various limits applied at\n+the sandbox level (e.g. PID limits).\n+\n+### Physical memory\n+\n+The host is able to manage physical memory using regular means (e.g. tracking\n+working sets, reclaiming and swapping under pressure). The Sentry lazily\n+populates host mappings for applications, and allow the host to demand-page\n+those regions, which is critical for the functioning of those mechanisms.\n+\n+In order to avoid excessive overhead, the Sentry does not demand-page individual\n+pages. Instead, it selects appropriate regions based on heuristics. There is a\n+trade-off here: the Sentry is unable to trivially determine which pages are\n+active and which are not. Even if pages were individually faulted, the host may\n+select pages to be reclaimed or swapped without the Sentry's knowledge.\n+\n+Therefore, memory usage statistics within the sandbox (e.g. via `proc`) are\n+approximations. The Sentry maintains an internal breakdown of memory usage, and\n+can collect accurate information but only through a relatively expensive API\n+call. In any case, it would likely be considered unwise to share precise\n+information about how the host is managing memory with the sandbox.\n+\n+Finally, when an application marks a region of memory as no longer needed, for\n+example via a call to [madvise][madvise], the Sentry *releases this memory back\n+to the host*. There can be performance penalties for this, since it may be\n+cheaper in many cases to retain the memory and use it to satisfy some other\n+request. However, releasing it immediately to the host allows the host to more\n+effectively multiplex resources and apply an efficient global policy.\n+\n+## Limits\n+\n+All Sentry threads and Sentry memory are subject to a container cgroup. However,\n+application usage will not appear as anonymous memory usage, and will instead be\n+accounted to the `memfd`. All anonymous memory will correspond to Sentry usage,\n+and host memory charged to the container will work as standard.\n+\n+The cgroups can be monitored for standard signals: pressure indicators,\n+threshold notifiers, etc. and can also be adjusted dynamically. Note that the\n+Sentry itself may listen for pressure signals in its containing cgroup, in order\n+to purge internal caches.\n+\n+[goroutine]: https://tour.golang.org/concurrency/1\n+[greenthread]: https://en.wikipedia.org/wiki/Green_threads\n+[scheduler]: https://morsmachine.dk/go-scheduler\n+[vdso]: https://en.wikipedia.org/wiki/VDSO\n+[rlimit]: http://man7.org/linux/man-pages/man2/getrlimit.2.html\n+[tickless]: https://en.wikipedia.org/wiki/Tickless_kernel\n+[memfd]: http://man7.org/linux/man-pages/man2/memfd_create.2.html\n+[scmrights]: http://man7.org/linux/man-pages/man7/unix.7.html\n+[madvise]: http://man7.org/linux/man-pages/man2/madvise.2.html\n+[exec]: https://docs.docker.com/engine/reference/commandline/exec/\n+\n+[^1]: Unless host networking is enabled, the Sentry is not able to create or open host file descriptors itself, it can only receive them in this way from the Gofer.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add resource model. |
259,858 | 28.04.2020 12:51:24 | 25,200 | 3cb00c97e953df3d1970e1462d8dbcd47d496d61 | Add note about AArch64 support. | [
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/FAQ.md",
"new_path": "g3doc/user_guide/FAQ.md",
"diff": "@@ -7,7 +7,8 @@ Today, gVisor requires Linux.\n### What CPU architectures are supported? {#supported-cpus}\ngVisor currently supports [x86_64/AMD64](https://en.wikipedia.org/wiki/X86-64)\n-compatible processors.\n+compatible processors. Preliminary support is also available for\n+[ARM64](https://en.wikipedia.org/wiki/ARM_architecture#AArch64).\n### Do I need to modify my Linux application to use gVisor? {#modify-app}\n@@ -17,8 +18,11 @@ No. gVisor is capable of running unmodified Linux binaries.\ngVisor supports Linux\n[ELF](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format) binaries.\n+\nBinaries run in gVisor should be built for the\n-[AMD64](https://en.wikipedia.org/wiki/X86-64) CPU architecture.\n+[AMD64](https://en.wikipedia.org/wiki/X86-64) or\n+[AArch64](https://en.wikipedia.org/wiki/ARM_architecture#AArch64) CPU\n+architectures.\n### Can I run Docker images using gVisor? {#docker-images}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add note about AArch64 support. |
259,858 | 28.04.2020 18:18:04 | 25,200 | d3c43401a7277e0a7e7f2d28392e2e196d7ea74c | Fixup link in CODE_OF_CONDUCT.md. | [
{
"change_type": "MODIFY",
"old_path": "CODE_OF_CONDUCT.md",
"new_path": "CODE_OF_CONDUCT.md",
"diff": "@@ -87,6 +87,5 @@ harassment or threats to anyone's safety, we may take action without notice.\n## Attribution\n-This Code of Conduct is adapted from the Contributor Covenant, version 1.4,\n-available at\n-https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n+This Code of Conduct is adapted from the [Contributor Covenant, version\n+1.4](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html).\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fixup link in CODE_OF_CONDUCT.md. |
259,858 | 29.04.2020 10:53:25 | 25,200 | cf86ec5e40bd1abf5be45fabbc7591a0452747ea | Add powered by gVisor logo. | [
{
"change_type": "MODIFY",
"old_path": "website/_includes/footer-links.html",
"new_path": "website/_includes/footer-links.html",
"diff": "<div class=\"container\">\n<div class=\"row\">\n- <div class=\"col-sm-4 col-md-2\">\n+ <div class=\"col-sm-3 col-md-2\">\n<p>About</p>\n<ul class=\"list-unstyled\">\n<li><a href=\"/roadmap/\">Roadmap</a></li>\n<li><a href=\"https://policies.google.com/privacy\">Privacy Policy</a></li>\n</ul>\n</div>\n- <div class=\"col-sm-4 col-md-2\">\n+ <div class=\"col-sm-3 col-md-2\">\n<p>Support</p>\n<ul class=\"list-unstyled\">\n<li><a href=\"https://github.com/google/gvisor/issues\">Issues</a></li>\n<li><a href=\"/docs/user_guide/FAQ\">FAQ</a></li>\n</ul>\n</div>\n- <div class=\"col-sm-4 col-md-2\">\n+ <div class=\"col-sm-3 col-md-2\">\n<p>Connect</p>\n<ul class=\"list-unstyled\">\n<li><a href=\"https://github.com/google/gvisor\">GitHub</a></li>\n<li><a href=\"/blog\">Blog</a></li>\n</ul>\n</div>\n+ <div class=\"col-sm-3 col-md-3\"></div>\n+ <div class=\"hidden-xs hidden-sm col-md-3\">\n+ <a href=\"https://cloud.google.com/run\">\n+ <img style=\"float: right;\" src=\"/assets/logos/powered-gvisor.png\" alt=\"Powered by gVisor\"/>\n+ </a>\n+ </div>\n</div>\n<div class=\"row\">\n<div class=\"col-lg-12\">\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/logos/powered-gvisor.png",
"new_path": "website/assets/logos/powered-gvisor.png",
"diff": "Binary files /dev/null and b/website/assets/logos/powered-gvisor.png differ\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add powered by gVisor logo. |
259,858 | 29.04.2020 11:45:04 | 25,200 | 7de6fb18f9a284b8f70191effd442a48c232603b | Clean-up documentation. | [
{
"change_type": "MODIFY",
"old_path": "website/index.md",
"new_path": "website/index.md",
"diff": "@@ -8,7 +8,7 @@ layout: base\n<div class=\"col-md-6\">\n<p>gVisor is an <b>application kernel</b> and <b>container runtime</b> providing defense-in-depth for containers <em>anywhere</em>.</p>\n<p style=\"margin-top: 20px;\">\n- <a class=\"btn\" href=\"/docs/\">Get Started <i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n+ <a class=\"btn\" href=\"/docs/\">Learn More <i class=\"fas fa-arrow-alt-circle-right ml-2\"></i></a>\n<a class=\"btn btn-inverse\" href=\"https://github.com/google/gvisor\">GitHub <i class=\"fab fa-github ml-2\"></i></a>\n</p>\n</div>\n@@ -22,36 +22,30 @@ layout: base\n<div class=\"row\">\n<div class=\"col-md-4\">\n<h4 id=\"seamless-security\">Container-native Security <i class=\"fas fa-lock\"></i></h4>\n- <p>By providing each container with its own application kernel instance,\n- gVisor limits the attack surface of the host while still integrating\n- seamlessly with popular container orchestration systems, such as Docker and\n- Kubernetes. This includes support for advanced features, such as a volumes,\n- terminals and sidecars, and still providing visibility into the application\n- behavior through cgroups and other monitoring mechanisms.\n- </p>\n+ <p>By providing each container with its own userspace kernel, gVisor limits\n+ the attack surface of the host. This protection does not limit\n+ functionality: gVisor runs unmodified binaries and integrates with container\n+ orchestration systems, such as Docker and Kubernetes, and supports features\n+ such as volumes and sidecars.</p>\n<a class=\"button\" href=\"/docs/architecture_guide/security/\">Read More »</a>\n</div>\n<div class=\"col-md-4\">\n<h4 id=\"resource-efficiency\">Resource Efficiency <i class=\"fas fa-feather-alt\"></i></h4>\n<p>Containers are efficient because workloads of different shapes and sizes\n- can be packed together by sharing host resources. By using host native\n- abstractions such as threads and memory mappings, gVisor closely co-operates\n- with the host to enable the same resource model as native containers.\n- Sandboxed containers can safely and securely share host resources with each\n- other and native containers on the same system.\n- </p>\n+ can be packed together by sharing host resources. gVisor uses host-native\n+ abstractions, such as threads and memory mappings, to co-operate with the\n+ host and enable the same resource model as native containers.</p>\n<a class=\"button\" href=\"/docs/architecture_guide/resources/\">Read More »</a>\n</div>\n<div class=\"col-md-4\">\n<h4 id=\"platform-portability\">Platform Portability <sup>☁</sup>☁</h4>\n- <p>Modern infrastructure spans multiple clouds and data centers, often using\n- a mix of virtualized instances and traditional servers. The pluggable\n- platform architecture of gVisor allows it to run anywhere, enabling security\n- policies to be enforced consistently across multiple environments.\n- Sandboxing requirements need not dictate where workloads can run.\n- </p>\n+ <p>Modern infrastructure spans multiple cloud services and data centers,\n+ often with a mix of managed services and virtualized or traditional servers.\n+ The pluggable platform architecture of gVisor allows it to run anywhere,\n+ enabling consistent security policies across multiple environments without\n+ having to rearchitect your infrastructure.</p>\n<a class=\"button\" href=\"/docs/architecture_guide/platforms/\">Read More »</a>\n</div>\n</div>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clean-up documentation. |
259,858 | 29.04.2020 18:00:21 | 25,200 | a10d5ed9691d341c60dc8590d19302332120d365 | Add atom feed (at previous URL). | [
{
"change_type": "MODIFY",
"old_path": "images/jekyll/Dockerfile",
"new_path": "images/jekyll/Dockerfile",
"diff": "@@ -7,5 +7,6 @@ RUN gem install \\\njekyll-inline-svg:1.1.4 \\\njekyll-paginate:1.1.0 \\\nkramdown-parser-gfm:1.1.0 \\\n- jekyll-relative-links:0.6.1\n+ jekyll-relative-links:0.6.1 \\\n+ jekyll-feed:0.13.0\nCMD [\"/usr/gem/gems/jekyll-4.0.0/exe/jekyll\", \"build\", \"-t\", \"-s\", \"/input\", \"-d\", \"/output\"]\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_config.yml",
"new_path": "website/_config.yml",
"diff": "@@ -11,7 +11,10 @@ plugins:\n- jekyll-autoprefixer\n- jekyll-inline-svg\n- jekyll-relative-links\n+ - jekyll-feed\nsite_url: https://gvisor.dev\n+feed:\n+ path: blog/index.xml\nsvg:\noptimize: true\ndefaults:\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_layouts/blog.html",
"new_path": "website/_layouts/blog.html",
"diff": "@@ -7,6 +7,9 @@ layout: base\n<div class=\"col-lg-2\"></div>\n<div class=\"col-lg-8\">\n<h1>{{ page.title }}</h1>\n+ {% if page.feed %}\n+ <a class=\"btn-inverse\" href=\"/blog/index.xml\">Feed <i class=\"fas fa-rss ml-2\"></i></a>\n+ {% endif %}\n{{ content }}\n</div>\n<div class=\"col-lg-2\"></div>\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_sass/front.scss",
"new_path": "website/_sass/front.scss",
"diff": "margin-bottom: 0;\nfont-weight: 300;\n}\n- .btn {\n- color: $text-color;\n- background-color: $inverse-link-color;\n- }\n- .btn-inverse {\n- color: $text-color;\n- background-color: #ffffff;\n- }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_sass/style.scss",
"new_path": "website/_sass/style.scss",
"diff": "@@ -104,7 +104,13 @@ code {\n}\n.btn {\n- background-color: $primary;\n+ color: $text-color;\n+ background-color: $inverse-link-color;\n+}\n+\n+.btn-inverse {\n+ color: $text-color;\n+ background-color: #ffffff;\n}\n.well {\n"
},
{
"change_type": "MODIFY",
"old_path": "website/blog/index.html",
"new_path": "website/blog/index.html",
"diff": "---\ntitle: Blog\nlayout: blog\n+feed: true\npagination:\nenabled: true\n---\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add atom feed (at previous URL). |
259,858 | 29.04.2020 18:54:48 | 25,200 | 5f3a256425f4fa99fd3e5363418c5978659cecf3 | Add support for kramdown TOC. | [
{
"change_type": "MODIFY",
"old_path": "g3doc/architecture_guide/performance.md",
"new_path": "g3doc/architecture_guide/performance.md",
"diff": "# Performance Guide\n+[TOC]\n+\ngVisor is designed to provide a secure, virtualized environment while preserving\nkey benefits of containerization, such as small fixed overheads and a dynamic\nresource footprint. For containerized infrastructure, this can provide a\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/architecture_guide/resources.md",
"new_path": "g3doc/architecture_guide/resources.md",
"diff": "# Resource Model\n+[TOC]\n+\nThe resource model for gVisor does not assume a fixed number of threads of\nexecution (i.e. vCPUs) or amount of physical memory. Where possible, decisions\nabout underlying physical resources are delegated to the host system, where\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/architecture_guide/security.md",
"new_path": "g3doc/architecture_guide/security.md",
"diff": "# Security Model\n+[TOC]\n+\ngVisor was created in order to provide additional defense against the\nexploitation of kernel bugs by untrusted userspace code. In order to understand\nhow gVisor achieves this goal, it is first necessary to understand the basic\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/FAQ.md",
"new_path": "g3doc/user_guide/FAQ.md",
"diff": "# FAQ\n+[TOC]\n+\n### What operating systems are supported? {#supported-os}\nToday, gVisor requires Linux.\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/checkpoint_restore.md",
"new_path": "g3doc/user_guide/checkpoint_restore.md",
"diff": "# Checkpoint/Restore\n+[TOC]\n+\ngVisor has the ability to checkpoint a process, save its current state in a\nstate file, and restore into a new container using the state file.\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/compatibility.md",
"new_path": "g3doc/user_guide/compatibility.md",
"diff": "# Applications\n+[TOC]\n+\ngVisor implements a large portion of the Linux surface and while we strive to\nmake it broadly compatible, there are (and always will be) unimplemented\nfeatures and bugs. The only real way to know if it will work is to try. If you\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/debugging.md",
"new_path": "g3doc/user_guide/debugging.md",
"diff": "# Debugging\n+[TOC]\n+\nTo enable debug and system call logging, add the `runtimeArgs` below to your\n[Docker](../quick_start/docker/) configuration (`/etc/docker/daemon.json`):\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/filesystem.md",
"new_path": "g3doc/user_guide/filesystem.md",
"diff": "# Filesystem\n+[TOC]\n+\ngVisor accesses the filesystem through a file proxy, called the Gofer. The gofer\nruns as a separate process, that is isolated from the sandbox. Gofer instances\ncommunicate with their respective sentry using the 9P protocol. For a more detailed\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/install.md",
"new_path": "g3doc/user_guide/install.md",
"diff": "# Installation\n--> Note: gVisor supports only x86\\_64 and requires Linux 4.14.77+\n--> ([older Linux](./networking.md#gso)).\n+[TOC]\n+\n+> Note: gVisor supports only x86\\_64 and requires Linux 4.14.77+\n+> ([older Linux](./networking.md#gso)).\n## Versions\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/platforms.md",
"new_path": "g3doc/user_guide/platforms.md",
"diff": "# Platforms (KVM)\n+[TOC]\n+\nThis document will help you set up your system to use a different gVisor\nplatform.\n"
},
{
"change_type": "MODIFY",
"old_path": "website/defs.bzl",
"new_path": "website/defs.bzl",
"diff": "@@ -130,7 +130,14 @@ layout: {layout}\"\"\"\nbuilder_content += [header.format(**args)]\nbuilder_content += [\"---\"]\nbuilder_content += [\"EOF\"]\n- builder_content += [\"grep -v -E '^# ' %s >>$T/%s || true\" % (f.path, f.short_path)]\n+\n+ # To generate the final page, we need to strip out the title (which\n+ # was pulled above to generate the annotation in the frontmatter,\n+ # and substitute the [TOC] tag with the {% toc %} plugin tag. Note\n+ # that the pipeline here is almost important, as the grep will\n+ # return non-zero if the file is empty, but we ignore that within\n+ # the pipeline.\n+ builder_content += [\"grep -v -E '^# ' %s | sed -e 's|^\\\\[TOC\\\\]$|- TOC\\\\n{:toc}|' >>$T/%s\" % (f.path, f.short_path)]\nbuilder_content += [\"declare -r filename=$(readlink -m %s)\" % tarball.path]\nbuilder_content += [\"(cd $T && tar -zcf \\\"${filename}\\\" .)\\n\"]\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add support for kramdown TOC. |
260,004 | 06.05.2020 15:57:42 | 25,200 | 485ca36adf18fbb587df9f34a2deea730882fb36 | Do not assume no DHCPv6 configurations
Do not assume that networks need any DHCPv6 configurations. Instead,
notify the NDP dispatcher in response to the first NDP RA's DHCPv6
flags, even if the flags indicate no DHCPv6 configurations are
available. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/dhcpv6configurationfromndpra_string.go",
"new_path": "pkg/tcpip/stack/dhcpv6configurationfromndpra_string.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// Code generated by \"stringer -type=DHCPv6ConfigurationFromNDPRA\"; DO NOT EDIT.\n+// Code generated by \"stringer -type DHCPv6ConfigurationFromNDPRA\"; DO NOT EDIT.\npackage stack\n@@ -22,9 +22,9 @@ func _() {\n// An \"invalid array index\" compiler error signifies that the constant values have changed.\n// Re-run the stringer command to generate them again.\nvar x [1]struct{}\n- _ = x[DHCPv6NoConfiguration-0]\n- _ = x[DHCPv6ManagedAddress-1]\n- _ = x[DHCPv6OtherConfigurations-2]\n+ _ = x[DHCPv6NoConfiguration-1]\n+ _ = x[DHCPv6ManagedAddress-2]\n+ _ = x[DHCPv6OtherConfigurations-3]\n}\nconst _DHCPv6ConfigurationFromNDPRA_name = \"DHCPv6NoConfigurationDHCPv6ManagedAddressDHCPv6OtherConfigurations\"\n@@ -32,8 +32,9 @@ const _DHCPv6ConfigurationFromNDPRA_name = \"DHCPv6NoConfigurationDHCPv6ManagedAd\nvar _DHCPv6ConfigurationFromNDPRA_index = [...]uint8{0, 21, 41, 66}\nfunc (i DHCPv6ConfigurationFromNDPRA) String() string {\n+ i -= 1\nif i < 0 || i >= DHCPv6ConfigurationFromNDPRA(len(_DHCPv6ConfigurationFromNDPRA_index)-1) {\n- return \"DHCPv6ConfigurationFromNDPRA(\" + strconv.FormatInt(int64(i), 10) + \")\"\n+ return \"DHCPv6ConfigurationFromNDPRA(\" + strconv.FormatInt(int64(i+1), 10) + \")\"\n}\nreturn _DHCPv6ConfigurationFromNDPRA_name[_DHCPv6ConfigurationFromNDPRA_index[i]:_DHCPv6ConfigurationFromNDPRA_index[i+1]]\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp.go",
"new_path": "pkg/tcpip/stack/ndp.go",
"diff": "@@ -199,9 +199,11 @@ var (\ntype DHCPv6ConfigurationFromNDPRA int\nconst (\n+ _ DHCPv6ConfigurationFromNDPRA = iota\n+\n// DHCPv6NoConfiguration indicates that no configurations are available via\n// DHCPv6.\n- DHCPv6NoConfiguration DHCPv6ConfigurationFromNDPRA = iota\n+ DHCPv6NoConfiguration\n// DHCPv6ManagedAddress indicates that addresses are available via DHCPv6.\n//\n@@ -315,9 +317,6 @@ type NDPDispatcher interface {\n// OnDHCPv6Configuration will be called with an updated configuration that is\n// available via DHCPv6 for a specified NIC.\n//\n- // NDPDispatcher assumes that the initial configuration available by DHCPv6 is\n- // DHCPv6NoConfiguration.\n- //\n// This function is not permitted to block indefinitely. It must not\n// call functions on the stack itself.\nOnDHCPv6Configuration(tcpip.NICID, DHCPv6ConfigurationFromNDPRA)\n@@ -1808,6 +1807,8 @@ func (ndp *ndpState) cleanupState(hostOnly bool) {\nif got := len(ndp.defaultRouters); got != 0 {\npanic(fmt.Sprintf(\"ndp: still have discovered default routers after cleaning up; found = %d\", got))\n}\n+\n+ ndp.dhcpv6Configuration = 0\n}\n// startSolicitingRouters starts soliciting routers, as per RFC 4861 section\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/ndp_test.go",
"new_path": "pkg/tcpip/stack/ndp_test.go",
"diff": "@@ -4888,7 +4888,12 @@ func TestDHCPv6ConfigurationFromNDPDA(t *testing.T) {\n}\n}\n- // The initial DHCPv6 configuration should be stack.DHCPv6NoConfiguration.\n+ // Even if the first RA reports no DHCPv6 configurations are available, the\n+ // dispatcher should get an event.\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, false))\n+ expectDHCPv6Event(stack.DHCPv6NoConfiguration)\n+ // Receiving the same update again should not result in an event to the\n+ // dispatcher.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, false))\nexpectNoDHCPv6Event()\n@@ -4896,8 +4901,6 @@ func TestDHCPv6ConfigurationFromNDPDA(t *testing.T) {\n// Configurations.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, true))\nexpectDHCPv6Event(stack.DHCPv6OtherConfigurations)\n- // Receiving the same update again should not result in an event to the\n- // NDPDispatcher.\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, true))\nexpectNoDHCPv6Event()\n@@ -4933,6 +4936,21 @@ func TestDHCPv6ConfigurationFromNDPDA(t *testing.T) {\nexpectDHCPv6Event(stack.DHCPv6OtherConfigurations)\ne.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, true))\nexpectNoDHCPv6Event()\n+\n+ // Cycling the NIC should cause the last DHCPv6 configuration to be cleared.\n+ if err := s.DisableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.DisableNIC(%d): %s\", nicID, err)\n+ }\n+ if err := s.EnableNIC(nicID); err != nil {\n+ t.Fatalf(\"s.EnableNIC(%d): %s\", nicID, err)\n+ }\n+\n+ // Receive an RA that updates the DHCPv6 configuration to Other\n+ // Configurations.\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, true))\n+ expectDHCPv6Event(stack.DHCPv6OtherConfigurations)\n+ e.InjectInbound(header.IPv6ProtocolNumber, raBufWithDHCPv6(llAddr2, false, true))\n+ expectNoDHCPv6Event()\n}\n// TestRouterSolicitation tests the initial Router Solicitations that are sent\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not assume no DHCPv6 configurations
Do not assume that networks need any DHCPv6 configurations. Instead,
notify the NDP dispatcher in response to the first NDP RA's DHCPv6
flags, even if the flags indicate no DHCPv6 configurations are
available.
PiperOrigin-RevId: 310245068 |
259,885 | 06.05.2020 16:06:49 | 25,200 | 7cd54c1f1437dccdf1840e8f893de06f9d1e70e6 | Remove vfs.FileDescriptionOptions.InvalidWrite.
Compare: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/timerfd.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/timerfd.go",
"diff": "@@ -46,7 +46,10 @@ func TimerfdCreate(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel\ndefault:\nreturn 0, nil, syserror.EINVAL\n}\n- file, err := t.Kernel().VFS().NewTimerFD(clock, fileFlags)\n+ // Timerfds aren't writable per se (their implementation of Write just\n+ // returns EINVAL), but they are \"opened for writing\", which is necessary\n+ // to actually reach said implementation of Write.\n+ file, err := t.Kernel().VFS().NewTimerFD(clock, linux.O_RDWR|fileFlags)\nif err != nil {\nreturn 0, nil, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -91,10 +91,6 @@ type FileDescriptionOptions struct {\n// ESPIPE.\nDenyPWrite bool\n- // if InvalidWrite is true, calls to FileDescription.Write() return\n- // EINVAL.\n- InvalidWrite bool\n-\n// If UseDentryMetadata is true, calls to FileDescription methods that\n// interact with file and filesystem metadata (Stat, SetStat, StatFS,\n// Listxattr, Getxattr, Setxattr, Removexattr) are implemented by calling\n@@ -570,9 +566,6 @@ func (fd *FileDescription) PWrite(ctx context.Context, src usermem.IOSequence, o\n// Write is similar to PWrite, but does not specify an offset.\nfunc (fd *FileDescription) Write(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error) {\n- if fd.opts.InvalidWrite {\n- return 0, syserror.EINVAL\n- }\nif !fd.writable {\nreturn 0, syserror.EBADF\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/timerfd.go",
"new_path": "pkg/sentry/vfs/timerfd.go",
"diff": "@@ -53,7 +53,6 @@ func (vfs *VirtualFilesystem) NewTimerFD(clock ktime.Clock, flags uint32) (*File\nUseDentryMetadata: true,\nDenyPRead: true,\nDenyPWrite: true,\n- InvalidWrite: true,\n}); err != nil {\nreturn nil, err\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove vfs.FileDescriptionOptions.InvalidWrite.
Compare:
https://elixir.bootlin.com/linux/v5.6/source/fs/timerfd.c#L431
PiperOrigin-RevId: 310246908 |
259,891 | 06.05.2020 22:23:41 | 25,200 | 763b5ad5968532249c69f29c997a1f6ec291db8b | Add basic incoming ipv4 fragment tests
Based on ipv6's TestReceiveIPv6Fragments. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/BUILD",
"new_path": "pkg/tcpip/network/ipv4/BUILD",
"diff": "@@ -34,5 +34,6 @@ go_test(\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4_test.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"math/rand\"\n\"testing\"\n+ \"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n@@ -473,3 +474,252 @@ func TestInvalidFragments(t *testing.T) {\n})\n}\n}\n+\n+// TestReceiveFragments feeds fragments in through the incoming packet path to\n+// test reassembly\n+func TestReceiveFragments(t *testing.T) {\n+ const addr1 = \"\\x0c\\xa8\\x00\\x01\" // 192.168.0.1\n+ const addr2 = \"\\x0c\\xa8\\x00\\x02\" // 192.168.0.2\n+ const nicID = 1\n+\n+ // Build and return a UDP header containing payload.\n+ udpGen := func(payloadLen int, multiplier uint8) buffer.View {\n+ payload := buffer.NewView(payloadLen)\n+ for i := 0; i < len(payload); i++ {\n+ payload[i] = uint8(i) * multiplier\n+ }\n+\n+ udpLength := header.UDPMinimumSize + len(payload)\n+\n+ hdr := buffer.NewPrependable(udpLength)\n+ u := header.UDP(hdr.Prepend(udpLength))\n+ u.Encode(&header.UDPFields{\n+ SrcPort: 5555,\n+ DstPort: 80,\n+ Length: uint16(udpLength),\n+ })\n+ copy(u.Payload(), payload)\n+ sum := header.PseudoHeaderChecksum(udp.ProtocolNumber, addr1, addr2, uint16(udpLength))\n+ sum = header.Checksum(payload, sum)\n+ u.SetChecksum(^u.CalculateChecksum(sum))\n+ return hdr.View()\n+ }\n+\n+ // UDP header plus a payload of 0..256\n+ ipv4Payload1 := udpGen(256, 1)\n+ udpPayload1 := ipv4Payload1[header.UDPMinimumSize:]\n+ // UDP header plus a payload of 0..256 in increments of 2.\n+ ipv4Payload2 := udpGen(128, 2)\n+ udpPayload2 := ipv4Payload2[header.UDPMinimumSize:]\n+\n+ type fragmentData struct {\n+ id uint16\n+ flags uint8\n+ fragmentOffset uint16\n+ payload buffer.View\n+ }\n+\n+ tests := []struct {\n+ name string\n+ fragments []fragmentData\n+ expectedPayloads [][]byte\n+ }{\n+ {\n+ name: \"No fragmentation\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1,\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload1},\n+ },\n+ {\n+ name: \"More fragments without payload\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1,\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n+ {\n+ name: \"Non-zero fragment offset without payload\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 8,\n+ payload: ipv4Payload1,\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n+ {\n+ name: \"Two fragments\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1[:64],\n+ },\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload1[64:],\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload1},\n+ },\n+ {\n+ name: \"Second fragment has MoreFlags set\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1[:64],\n+ },\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload1[64:],\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n+ {\n+ name: \"Two fragments with different IDs\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1[:64],\n+ },\n+ {\n+ id: 2,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload1[64:],\n+ },\n+ },\n+ expectedPayloads: nil,\n+ },\n+ {\n+ name: \"Two interleaved fragmented packets\",\n+ fragments: []fragmentData{\n+ {\n+ id: 1,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload1[:64],\n+ },\n+ {\n+ id: 2,\n+ flags: header.IPv4FlagMoreFragments,\n+ fragmentOffset: 0,\n+ payload: ipv4Payload2[:64],\n+ },\n+ {\n+ id: 1,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload1[64:],\n+ },\n+ {\n+ id: 2,\n+ flags: 0,\n+ fragmentOffset: 64,\n+ payload: ipv4Payload2[64:],\n+ },\n+ },\n+ expectedPayloads: [][]byte{udpPayload1, udpPayload2},\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ // Setup a stack and endpoint.\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ })\n+ e := channel.New(0, 1280, tcpip.LinkAddress(\"\\xf0\\x00\"))\n+ if err := s.CreateNIC(nicID, e); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _) = %s\", nicID, err)\n+ }\n+ if err := s.AddAddress(nicID, header.IPv4ProtocolNumber, addr2); err != nil {\n+ t.Fatalf(\"AddAddress(%d, %d, %s) = %s\", nicID, header.IPv4ProtocolNumber, addr2, err)\n+ }\n+\n+ wq := waiter.Queue{}\n+ we, ch := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.EventIn)\n+ defer wq.EventUnregister(&we)\n+ defer close(ch)\n+ ep, err := s.NewEndpoint(udp.ProtocolNumber, header.IPv4ProtocolNumber, &wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, header.IPv4ProtocolNumber, err)\n+ }\n+ defer ep.Close()\n+\n+ bindAddr := tcpip.FullAddress{Addr: addr2, Port: 80}\n+ if err := ep.Bind(bindAddr); err != nil {\n+ t.Fatalf(\"Bind(%+v): %s\", bindAddr, err)\n+ }\n+\n+ // Prepare and send the fragments.\n+ for _, frag := range test.fragments {\n+ hdr := buffer.NewPrependable(header.IPv4MinimumSize)\n+\n+ // Serialize IPv4 fixed header.\n+ ip := header.IPv4(hdr.Prepend(header.IPv4MinimumSize))\n+ ip.Encode(&header.IPv4Fields{\n+ IHL: header.IPv4MinimumSize,\n+ TotalLength: header.IPv4MinimumSize + uint16(len(frag.payload)),\n+ ID: frag.id,\n+ Flags: frag.flags,\n+ FragmentOffset: frag.fragmentOffset,\n+ TTL: 64,\n+ Protocol: uint8(header.UDPProtocolNumber),\n+ SrcAddr: addr1,\n+ DstAddr: addr2,\n+ })\n+\n+ vv := hdr.View().ToVectorisedView()\n+ vv.AppendView(frag.payload)\n+\n+ e.InjectInbound(header.IPv4ProtocolNumber, stack.PacketBuffer{\n+ Data: vv,\n+ })\n+ }\n+\n+ if got, want := s.Stats().UDP.PacketsReceived.Value(), uint64(len(test.expectedPayloads)); got != want {\n+ t.Errorf(\"got UDP Rx Packets = %d, want = %d\", got, want)\n+ }\n+\n+ for i, expectedPayload := range test.expectedPayloads {\n+ gotPayload, _, err := ep.Read(nil)\n+ if err != nil {\n+ t.Fatalf(\"(i=%d) Read(nil): %s\", i, err)\n+ }\n+ if diff := cmp.Diff(buffer.View(expectedPayload), gotPayload); diff != \"\" {\n+ t.Errorf(\"(i=%d) got UDP payload mismatch (-want +got):\\n%s\", i, diff)\n+ }\n+ }\n+\n+ if gotPayload, _, err := ep.Read(nil); err != tcpip.ErrWouldBlock {\n+ t.Fatalf(\"(last) got Read(nil) = (%x, _, %v), want = (_, _, %s)\", gotPayload, err, tcpip.ErrWouldBlock)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add basic incoming ipv4 fragment tests
Based on ipv6's TestReceiveIPv6Fragments. |
259,860 | 07.05.2020 09:52:39 | 25,200 | e0089a20e4830d6b6659414e393905e0fd6a2e66 | Remove outdated TODO for VFS2 AccessAt.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/anonfs.go",
"new_path": "pkg/sentry/vfs/anonfs.go",
"diff": "@@ -91,8 +91,6 @@ func (fs *anonFilesystem) Sync(ctx context.Context) error {\n}\n// AccessAt implements vfs.Filesystem.Impl.AccessAt.\n-//\n-// TODO(gvisor.dev/issue/1965): Implement access permissions.\nfunc (fs *anonFilesystem) AccessAt(ctx context.Context, rp *ResolvingPath, creds *auth.Credentials, ats AccessTypes) error {\nif !rp.Done() {\nreturn syserror.ENOTDIR\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove outdated TODO for VFS2 AccessAt.
Fixes #1965.
PiperOrigin-RevId: 310380433 |
259,860 | 07.05.2020 10:19:11 | 25,200 | 16da7e790f570d9743fb47e50c304e6a24834772 | Update privateunixsocket TODOs.
Synthetic sockets do not have the race condition issue in VFS2, and we will
get rid of privateunixsocket as well.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/session.go",
"new_path": "pkg/sentry/fs/gofer/session.go",
"diff": "@@ -190,9 +190,9 @@ type session struct {\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+ // There are a few possible races with someone stat'ing the file and another\n+ // deleting it concurrently, where the file will not be reported as socket\n+ // file.\noverrides *overrideMaps `state:\"wait\"`\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -301,8 +301,8 @@ func (c *containerMounter) getMountNameAndOptionsVFS2(conf *Config, m specs.Moun\n}\n// p9MountOptions creates a slice of options for a p9 mount.\n-// TODO(gvisor.dev/issue/1200): Remove this version in favor of the one in\n-// fs.go when privateunixsocket lands.\n+// TODO(gvisor.dev/issue/1624): Remove this version once privateunixsocket is\n+// deleted, along with the rest of VFS1.\nfunc p9MountOptionsVFS2(fd int, fa FileAccessType) []string {\nopts := []string{\n\"trans=fd\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update privateunixsocket TODOs.
Synthetic sockets do not have the race condition issue in VFS2, and we will
get rid of privateunixsocket as well.
Fixes #1200.
PiperOrigin-RevId: 310386474 |
259,858 | 07.05.2020 13:17:33 | 25,200 | 1f4087e7cd6c3cc696e6b26446abd6c5214cfd67 | Fix tags used for determining file sets.
Updates
Updates | [
{
"change_type": "MODIFY",
"old_path": "tools/bazeldefs/tags.bzl",
"new_path": "tools/bazeldefs/tags.bzl",
"diff": "\"\"\"List of special Go suffixes.\"\"\"\n-go_suffixes = [\n+def explode(tagset, suffixes):\n+ \"\"\"explode combines tagset and suffixes in all ways.\n+\n+ Args:\n+ tagset: Original suffixes.\n+ suffixes: Suffixes to combine before and after.\n+\n+ Returns:\n+ The set of possible combinations.\n+ \"\"\"\n+ result = [t for t in tagset]\n+ result += [s for s in suffixes]\n+ for t in tagset:\n+ result += [t + s for s in suffixes]\n+ result += [s + t for s in suffixes]\n+ return result\n+\n+archs = [\n\"_386\",\n- \"_386_unsafe\",\n\"_aarch64\",\n- \"_aarch64_unsafe\",\n\"_amd64\",\n- \"_amd64_unsafe\",\n\"_arm\",\n\"_arm64\",\n- \"_arm64_unsafe\",\n- \"_arm_unsafe\",\n- \"_impl\",\n- \"_impl_unsafe\",\n- \"_linux\",\n- \"_linux_unsafe\",\n\"_mips\",\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- \"_ppc64le_unsafe\",\n\"_riscv64\",\n- \"_riscv64_unsafe\",\n\"_s390x\",\n- \"_s390x_unsafe\",\n\"_sparc64\",\n- \"_sparc64_unsafe\",\n- \"_wasm\",\n- \"_wasm_unsafe\",\n+ \"_x86\",\n+]\n+\n+oses = [\n+ \"_linux\",\n]\n+\n+generic = [\n+ \"_impl\",\n+ \"_race\",\n+ \"_norace\",\n+ \"_unsafe\",\n+ \"_opts\",\n+]\n+\n+# State explosion? Sure. This is approximately:\n+# len(archs) * (1 + 2 * len(oses) * (1 + 2 * len(generic))\n+#\n+# This evaluates to 495 at the time of writing. So it's a lot of different\n+# combinations, but not so much that it will cause issues. We can probably add\n+# quite a few more variants before this becomes a genuine problem.\n+go_suffixes = explode(explode(archs, oses), generic)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix tags used for determining file sets.
Updates #2569
Updates #2298
PiperOrigin-RevId: 310423629 |
259,858 | 07.05.2020 15:17:09 | 25,200 | 7b4a913f36e2fededca9b1d2f73588eca9c4b683 | Fix ARM64 build.
The common syscall definitions mean that ARM64-exclusive files need stubs in
the ARM64 build. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/BUILD",
"new_path": "pkg/sentry/syscalls/linux/BUILD",
"diff": "@@ -49,7 +49,8 @@ go_library(\n\"sys_time.go\",\n\"sys_timer.go\",\n\"sys_timerfd.go\",\n- \"sys_tls.go\",\n+ \"sys_tls_amd64.go\",\n+ \"sys_tls_arm64.go\",\n\"sys_utsname.go\",\n\"sys_write.go\",\n\"sys_xattr.go\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/syscalls/linux/sys_tls.go",
"new_path": "pkg/sentry/syscalls/linux/sys_tls_amd64.go",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/syscalls/linux/sys_tls_arm64.go",
"diff": "+// Copyright 2018 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//+build arm64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// ArchPrctl is not defined for ARM64.\n+func ArchPrctl(*kernel.Task, arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return 0, nil, syserror.ENOSYS\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_utsname.go",
"new_path": "pkg/sentry/syscalls/linux/sys_utsname.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64 arm64\n-\npackage linux\nimport (\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix ARM64 build.
The common syscall definitions mean that ARM64-exclusive files need stubs in
the ARM64 build.
PiperOrigin-RevId: 310446698 |
259,898 | 08.05.2020 11:21:40 | 25,200 | 5d7d5ed7d6ffd8d420f042a22b22e0527e78d441 | Send ACK to OTW SEQs/unacc ACKs in CLOSE_WAIT
This fixed the corresponding packetimpact test. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/tcp.go",
"new_path": "pkg/tcpip/header/tcp.go",
"diff": "@@ -609,5 +609,8 @@ func Acceptable(segSeq seqnum.Value, segLen seqnum.Size, rcvNxt, rcvAcc seqnum.V\n}\n// Page 70 of RFC 793 allows packets that can be made \"acceptable\" by trimming\n// the payload, so we'll accept any payload that overlaps the receieve window.\n- return rcvNxt.LessThan(segSeq.Add(segLen)) && segSeq.LessThan(rcvAcc)\n+ // segSeq < rcvAcc is more correct according to RFC, however, Linux does it\n+ // differently, it uses segSeq <= rcvAcc, we'd want to keep the same behavior\n+ // as Linux.\n+ return rcvNxt.LessThan(segSeq.Add(segLen)) && segSeq.LessThanEq(rcvAcc)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv.go",
"new_path": "pkg/tcpip/transport/tcp/rcv.go",
"diff": "@@ -70,7 +70,16 @@ func newReceiver(ep *endpoint, irs seqnum.Value, rcvWnd seqnum.Size, rcvWndScale\n// acceptable checks if the segment sequence number range is acceptable\n// according to the table on page 26 of RFC 793.\nfunc (r *receiver) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {\n- return header.Acceptable(segSeq, segLen, r.rcvNxt, r.rcvAcc)\n+ // r.rcvWnd could be much larger than the window size we advertised in our\n+ // outgoing packets, we should use what we have advertised for acceptability\n+ // test.\n+ scaledWindowSize := r.rcvWnd >> r.rcvWndScale\n+ if scaledWindowSize > 0xffff {\n+ // This is what we actually put in the Window field.\n+ scaledWindowSize = 0xffff\n+ }\n+ advertisedWindowSize := scaledWindowSize << r.rcvWndScale\n+ return header.Acceptable(segSeq, segLen, r.rcvNxt, r.rcvNxt.Add(advertisedWindowSize))\n}\n// getSendParams returns the parameters needed by the sender when building\n@@ -259,7 +268,14 @@ func (r *receiver) handleRcvdSegmentClosing(s *segment, state EndpointState, clo\n// If we are in one of the shutdown states then we need to do\n// additional checks before we try and process the segment.\nswitch state {\n- case StateCloseWait, StateClosing, StateLastAck:\n+ case StateCloseWait:\n+ // If the ACK acks something not yet sent then we send an ACK.\n+ if r.ep.snd.sndNxt.LessThan(s.ackNumber) {\n+ r.ep.snd.sendAck()\n+ return true, nil\n+ }\n+ fallthrough\n+ case StateClosing, StateLastAck:\nif !s.sequenceNumber.LessThanEq(r.rcvNxt) {\n// Just drop the segment as we have\n// already received a FIN and this\n@@ -276,7 +292,7 @@ func (r *receiver) handleRcvdSegmentClosing(s *segment, state EndpointState, clo\n// SHUT_RD) then any data past the rcvNxt should\n// trigger a RST.\nendDataSeq := s.sequenceNumber.Add(seqnum.Size(s.data.Size()))\n- if rcvClosed && r.rcvNxt.LessThan(endDataSeq) {\n+ if state != StateCloseWait && rcvClosed && r.rcvNxt.LessThan(endDataSeq) {\nreturn true, tcpip.ErrConnectionAborted\n}\nif state == StateFinWait1 {\n@@ -329,13 +345,6 @@ func (r *receiver) handleRcvdSegment(s *segment) (drop bool, err *tcpip.Error) {\nstate := r.ep.EndpointState()\nclosed := r.ep.closed\n- if state != StateEstablished {\n- drop, err := r.handleRcvdSegmentClosing(s, state, closed)\n- if drop || err != nil {\n- return drop, err\n- }\n- }\n-\nsegLen := seqnum.Size(s.data.Size())\nsegSeq := s.sequenceNumber\n@@ -347,6 +356,13 @@ func (r *receiver) handleRcvdSegment(s *segment) (drop bool, err *tcpip.Error) {\nreturn true, nil\n}\n+ if state != StateEstablished {\n+ drop, err := r.handleRcvdSegmentClosing(s, state, closed)\n+ if drop || err != nil {\n+ return drop, err\n+ }\n+ }\n+\n// Store the time of the last ack.\nr.lastRcvdAckTime = time.Now()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv_test.go",
"new_path": "pkg/tcpip/transport/tcp/rcv_test.go",
"diff": "@@ -30,7 +30,7 @@ func TestAcceptable(t *testing.T) {\n}{\n// The segment is smaller than the window.\n{105, 2, 100, 104, false},\n- {105, 2, 101, 105, false},\n+ {105, 2, 101, 105, true},\n{105, 2, 102, 106, true},\n{105, 2, 103, 107, true},\n{105, 2, 104, 108, true},\n@@ -39,7 +39,7 @@ func TestAcceptable(t *testing.T) {\n{105, 2, 107, 111, false},\n// The segment is larger than the window.\n- {105, 4, 103, 105, false},\n+ {105, 4, 103, 105, true},\n{105, 4, 104, 106, true},\n{105, 4, 105, 107, true},\n{105, 4, 106, 108, true},\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -117,8 +117,6 @@ packetimpact_go_test(\npacketimpact_go_test(\nname = \"tcp_close_wait_ack\",\nsrcs = [\"tcp_close_wait_ack_test.go\"],\n- # TODO(b/153574037): Fix netstack then remove the line below.\n- netstack = False,\ndeps = [\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/seqnum\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Send ACK to OTW SEQs/unacc ACKs in CLOSE_WAIT
This fixed the corresponding packetimpact test.
PiperOrigin-RevId: 310593470 |
259,885 | 08.05.2020 11:34:15 | 25,200 | 21b71395a6aa2eafbc4c59222574d56c2db2e23b | Pass flags to fsimpl/host.inode.open().
This has two effects: It makes flags passed to open("/proc/[pid]/fd/[hostfd]")
effective, and it prevents imported pipes/sockets/character devices from being
opened with O_NONBLOCK unconditionally (because the underlying host FD was set
to non-blocking in ImportFD()). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -53,13 +53,19 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\nreturn nil, err\n}\n+ // Get flags for the imported FD.\n+ flags, err := unix.FcntlInt(uintptr(hostFD), syscall.F_GETFL, 0)\n+ if err != nil {\n+ return nil, err\n+ }\n+\nfileMode := linux.FileMode(s.Mode)\nfileType := fileMode.FileType()\n// Determine if hostFD is seekable. If not, this syscall will return ESPIPE\n// (see fs/read_write.c:llseek), e.g. for pipes, sockets, and some character\n// devices.\n- _, err := unix.Seek(hostFD, 0, linux.SEEK_CUR)\n+ _, err = unix.Seek(hostFD, 0, linux.SEEK_CUR)\nseekable := err != syserror.ESPIPE\ni := &inode{\n@@ -95,7 +101,7 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\n// i.open will take a reference on d.\ndefer d.DecRef()\n- return i.open(ctx, d.VFSDentry(), mnt)\n+ return i.open(ctx, d.VFSDentry(), mnt, uint32(flags))\n}\n// filesystemType implements vfs.FilesystemType.\n@@ -198,19 +204,6 @@ type inode struct {\nqueue waiter.Queue\n}\n-// Note that these flags may become out of date, since they can be modified\n-// on the host, e.g. with fcntl.\n-func fileFlagsFromHostFD(fd int) (uint32, error) {\n- flags, err := unix.FcntlInt(uintptr(fd), syscall.F_GETFL, 0)\n- if err != nil {\n- log.Warningf(\"Failed to get file flags for donated FD %d: %v\", fd, err)\n- return 0, err\n- }\n- // TODO(gvisor.dev/issue/1672): implement behavior corresponding to these allowed flags.\n- flags &= syscall.O_ACCMODE | syscall.O_DIRECT | syscall.O_NONBLOCK | syscall.O_DSYNC | syscall.O_SYNC | syscall.O_APPEND\n- return uint32(flags), nil\n-}\n-\n// CheckPermissions implements kernfs.Inode.\nfunc (i *inode) CheckPermissions(ctx context.Context, creds *auth.Credentials, ats vfs.AccessTypes) error {\nvar s syscall.Stat_t\n@@ -406,19 +399,19 @@ func (i *inode) Open(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentr\nif i.Mode().FileType() == linux.S_IFSOCK {\nreturn nil, syserror.ENXIO\n}\n- return i.open(ctx, vfsd, rp.Mount())\n+ return i.open(ctx, vfsd, rp.Mount(), opts.Flags)\n}\n-func (i *inode) open(ctx context.Context, d *vfs.Dentry, mnt *vfs.Mount) (*vfs.FileDescription, error) {\n+func (i *inode) open(ctx context.Context, d *vfs.Dentry, mnt *vfs.Mount, flags uint32) (*vfs.FileDescription, error) {\nvar s syscall.Stat_t\nif err := syscall.Fstat(i.hostFD, &s); err != nil {\nreturn nil, err\n}\nfileType := s.Mode & linux.FileTypeMask\n- flags, err := fileFlagsFromHostFD(i.hostFD)\n- if err != nil {\n- return nil, err\n- }\n+\n+ // Constrain flags to a subset we can handle.\n+ // TODO(gvisor.dev/issue/1672): implement behavior corresponding to these allowed flags.\n+ flags &= syscall.O_ACCMODE | syscall.O_DIRECT | syscall.O_NONBLOCK | syscall.O_DSYNC | syscall.O_SYNC | syscall.O_APPEND\nif fileType == syscall.S_IFSOCK {\nif i.isTTY {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Pass flags to fsimpl/host.inode.open().
This has two effects: It makes flags passed to open("/proc/[pid]/fd/[hostfd]")
effective, and it prevents imported pipes/sockets/character devices from being
opened with O_NONBLOCK unconditionally (because the underlying host FD was set
to non-blocking in ImportFD()).
PiperOrigin-RevId: 310596062 |
259,962 | 08.05.2020 15:38:42 | 25,200 | e4d2d21f6b1b93146378ed5edc0c55d2ae4fb3af | Add UDP send/recv packetimpact tests.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/connections.go",
"new_path": "test/packetimpact/testbench/connections.go",
"diff": "@@ -841,6 +841,7 @@ func (conn *UDPIPv4) SendIP(additionalLayers ...Layer) {\n// Expect expects a frame with the UDP layer matching the provided UDP within\n// the timeout specified. If it doesn't arrive in time, an error is returned.\nfunc (conn *UDPIPv4) Expect(udp UDP, timeout time.Duration) (*UDP, error) {\n+ conn.t.Helper()\nlayer, err := (*Connection)(conn).Expect(&udp, timeout)\nif layer == nil {\nreturn nil, err\n@@ -852,6 +853,18 @@ func (conn *UDPIPv4) Expect(udp UDP, timeout time.Duration) (*UDP, error) {\nreturn gotUDP, err\n}\n+// ExpectData is a convenient method that expects a Layer and the Layer after\n+// it. If it doens't arrive in time, it returns nil.\n+func (conn *UDPIPv4) ExpectData(udp UDP, payload Payload, timeout time.Duration) (Layers, error) {\n+ conn.t.Helper()\n+ expected := make([]Layer, len(conn.layerStates))\n+ expected[len(expected)-1] = &udp\n+ if payload.length() != 0 {\n+ expected = append(expected, &payload)\n+ }\n+ return (*Connection)(conn).ExpectFrame(expected, timeout)\n+}\n+\n// Close frees associated resources held by the UDPIPv4 connection.\nfunc (conn *UDPIPv4) Close() {\n(*Connection)(conn).Close()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -898,11 +898,8 @@ func (l *UDP) match(other Layer) bool {\n}\nfunc (l *UDP) length() int {\n- if l.Length == nil {\nreturn header.UDPMinimumSize\n}\n- return int(*l.Length)\n-}\n// merge implements Layer.merge.\nfunc (l *UDP) merge(other Layer) error {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/rawsockets.go",
"new_path": "test/packetimpact/testbench/rawsockets.go",
"diff": "@@ -169,7 +169,7 @@ func NewInjector(t *testing.T) (Injector, error) {\n// Send a raw frame.\nfunc (i *Injector) Send(b []byte) {\nif _, err := unix.Write(i.fd, b); err != nil {\n- i.t.Fatalf(\"can't write: %s\", err)\n+ i.t.Fatalf(\"can't write: %s of len %d\", err, len(b))\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -148,6 +148,15 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"udp_send_recv_dgram\",\n+ srcs = [\"udp_send_recv_dgram_test.go\"],\n+ deps = [\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\nsh_binary(\nname = \"test_runner\",\nsrcs = [\"test_runner.sh\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetimpact/tests/udp_send_recv_dgram_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 udp_send_recv_dgram_test\n+\n+import (\n+ \"math/rand\"\n+ \"net\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func generateRandomPayload(t *testing.T, n int) string {\n+ t.Helper()\n+ buf := make([]byte, n)\n+ if _, err := rand.Read(buf); err != nil {\n+ t.Fatalf(\"rand.Read(buf) failed: %s\", err)\n+ }\n+ return string(buf)\n+}\n+\n+func TestUDPRecv(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ boundFD, remotePort := dut.CreateBoundSocket(unix.SOCK_DGRAM, unix.IPPROTO_UDP, net.ParseIP(\"0.0.0.0\"))\n+ defer dut.Close(boundFD)\n+ conn := tb.NewUDPIPv4(t, tb.UDP{DstPort: &remotePort}, tb.UDP{SrcPort: &remotePort})\n+ defer conn.Close()\n+\n+ testCases := []struct {\n+ name string\n+ payload string\n+ }{\n+ {\"emptypayload\", \"\"},\n+ {\"small payload\", \"hello world\"},\n+ {\"1kPayload\", generateRandomPayload(t, 1<<10)},\n+ // Even though UDP allows larger dgrams we don't test it here as\n+ // they need to be fragmented and written out as individual\n+ // frames.\n+ }\n+ for _, tc := range testCases {\n+ t.Run(tc.name, func(t *testing.T) {\n+ frame := conn.CreateFrame(&tb.UDP{}, &tb.Payload{Bytes: []byte(tc.payload)})\n+ conn.SendFrame(frame)\n+ if got, want := string(dut.Recv(boundFD, int32(len(tc.payload)), 0)), tc.payload; got != want {\n+ t.Fatalf(\"received payload does not match sent payload got: %s, want: %s\", got, want)\n+ }\n+ })\n+ }\n+}\n+\n+func TestUDPSend(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ boundFD, remotePort := dut.CreateBoundSocket(unix.SOCK_DGRAM, unix.IPPROTO_UDP, net.ParseIP(\"0.0.0.0\"))\n+ defer dut.Close(boundFD)\n+ conn := tb.NewUDPIPv4(t, tb.UDP{DstPort: &remotePort}, tb.UDP{SrcPort: &remotePort})\n+ defer conn.Close()\n+\n+ testCases := []struct {\n+ name string\n+ payload string\n+ }{\n+ {\"emptypayload\", \"\"},\n+ {\"small payload\", \"hello world\"},\n+ {\"1kPayload\", generateRandomPayload(t, 1<<10)},\n+ // Even though UDP allows larger dgrams we don't test it here as\n+ // they need to be fragmented and written out as individual\n+ // frames.\n+ }\n+ for _, tc := range testCases {\n+ t.Run(tc.name, func(t *testing.T) {\n+ conn.Drain()\n+ if got, want := int(dut.SendTo(boundFD, []byte(tc.payload), 0, conn.LocalAddr())), len(tc.payload); got != want {\n+ t.Fatalf(\"short write got: %d, want: %d\", got, want)\n+ }\n+ if _, err := conn.ExpectData(tb.UDP{SrcPort: &remotePort}, tb.Payload{Bytes: []byte(tc.payload)}, 1*time.Second); err != nil {\n+ t.Fatal(err)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add UDP send/recv packetimpact tests.
Fixes #2654
PiperOrigin-RevId: 310642216 |
259,885 | 11.05.2020 16:13:14 | 25,200 | 15de8cc9e0e7789c3d55595171b3272ec726931f | Add fsimpl/gofer.InternalFilesystemOptions.OpenSocketsByConnecting. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"new_path": "pkg/sentry/fsimpl/gofer/filesystem.go",
"diff": "@@ -21,6 +21,8 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/p9\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/host\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/pipe\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n@@ -835,6 +837,9 @@ func (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vf\nif d.isSynthetic() {\nreturn nil, syserror.ENXIO\n}\n+ if d.fs.iopts.OpenSocketsByConnecting {\n+ return d.connectSocketLocked(ctx, opts)\n+ }\ncase linux.S_IFIFO:\nif d.isSynthetic() {\nreturn d.pipe.Open(ctx, mnt, &d.vfsd, opts.Flags)\n@@ -843,10 +848,28 @@ func (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vf\nreturn d.openSpecialFileLocked(ctx, mnt, opts)\n}\n+func (d *dentry) connectSocketLocked(ctx context.Context, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\n+ if opts.Flags&linux.O_DIRECT != 0 {\n+ return nil, syserror.EINVAL\n+ }\n+ fdObj, err := d.file.connect(ctx, p9.AnonymousSocket)\n+ if err != nil {\n+ return nil, err\n+ }\n+ fd, err := host.NewFD(ctx, kernel.KernelFromContext(ctx).HostMount(), fdObj.FD(), &host.NewFDOptions{\n+ HaveFlags: true,\n+ Flags: opts.Flags,\n+ })\n+ if err != nil {\n+ fdObj.Close()\n+ return nil, err\n+ }\n+ fdObj.Release()\n+ return fd, nil\n+}\n+\nfunc (d *dentry) openSpecialFileLocked(ctx context.Context, mnt *vfs.Mount, opts *vfs.OpenOptions) (*vfs.FileDescription, error) {\nats := vfs.AccessTypesForOpenFlags(opts)\n- // Treat as a special file. This is done for non-synthetic pipes as well as\n- // regular files when d.fs.opts.regularFilesUseSpecialFileFD is true.\nif opts.Flags&linux.O_DIRECT != 0 {\nreturn nil, syserror.EINVAL\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -221,6 +221,10 @@ type InternalFilesystemOptions struct {\n// which servers can handle only a single client and report failure if that\n// client disconnects.\nLeakConnection bool\n+\n+ // If OpenSocketsByConnecting is true, silently translate attempts to open\n+ // files identifying as sockets to connect RPCs.\n+ OpenSocketsByConnecting bool\n}\n// Name implements vfs.FilesystemType.Name.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -40,8 +40,20 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// ImportFD sets up and returns a vfs.FileDescription from a donated fd.\n-func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs.FileDescription, error) {\n+// NewFDOptions contains options to NewFD.\n+type NewFDOptions struct {\n+ // If IsTTY is true, the file descriptor is a TTY.\n+ IsTTY bool\n+\n+ // If HaveFlags is true, use Flags for the new file description. Otherwise,\n+ // the new file description will inherit flags from hostFD.\n+ HaveFlags bool\n+ Flags uint32\n+}\n+\n+// NewFD returns a vfs.FileDescription representing the given host file\n+// descriptor. mnt must be Kernel.HostMount().\n+func NewFD(ctx context.Context, mnt *vfs.Mount, hostFD int, opts *NewFDOptions) (*vfs.FileDescription, error) {\nfs, ok := mnt.Filesystem().Impl().(*filesystem)\nif !ok {\nreturn nil, fmt.Errorf(\"can't import host FDs into filesystems of type %T\", mnt.Filesystem().Impl())\n@@ -53,11 +65,15 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\nreturn nil, err\n}\n+ flags := opts.Flags\n+ if !opts.HaveFlags {\n// Get flags for the imported FD.\n- flags, err := unix.FcntlInt(uintptr(hostFD), syscall.F_GETFL, 0)\n+ flagsInt, err := unix.FcntlInt(uintptr(hostFD), syscall.F_GETFL, 0)\nif err != nil {\nreturn nil, err\n}\n+ flags = uint32(flagsInt)\n+ }\nfileMode := linux.FileMode(s.Mode)\nfileType := fileMode.FileType()\n@@ -65,13 +81,13 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\n// Determine if hostFD is seekable. If not, this syscall will return ESPIPE\n// (see fs/read_write.c:llseek), e.g. for pipes, sockets, and some character\n// devices.\n- _, err = unix.Seek(hostFD, 0, linux.SEEK_CUR)\n+ _, err := unix.Seek(hostFD, 0, linux.SEEK_CUR)\nseekable := err != syserror.ESPIPE\ni := &inode{\nhostFD: hostFD,\nseekable: seekable,\n- isTTY: isTTY,\n+ isTTY: opts.IsTTY,\ncanMap: canMap(uint32(fileType)),\nwouldBlock: wouldBlock(uint32(fileType)),\nino: fs.NextIno(),\n@@ -101,7 +117,14 @@ func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs\n// i.open will take a reference on d.\ndefer d.DecRef()\n- return i.open(ctx, d.VFSDentry(), mnt, uint32(flags))\n+ return i.open(ctx, d.VFSDentry(), mnt, flags)\n+}\n+\n+// ImportFD sets up and returns a vfs.FileDescription from a donated fd.\n+func ImportFD(ctx context.Context, mnt *vfs.Mount, hostFD int, isTTY bool) (*vfs.FileDescription, error) {\n+ return NewFD(ctx, mnt, hostFD, &NewFDOptions{\n+ IsTTY: isTTY,\n+ })\n}\n// filesystemType implements vfs.FilesystemType.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add fsimpl/gofer.InternalFilesystemOptions.OpenSocketsByConnecting.
PiperOrigin-RevId: 311014995 |
259,891 | 23.03.2020 14:33:20 | 25,200 | 87225fad2a468e1516784f13abe8bb946d0172c6 | iptables: check for truly unconditional rules
We weren't properly checking whether the inserted default rule was
unconditional. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "@@ -59,6 +59,13 @@ type metadata struct {\n// developing iptables, but can pollute sentry logs otherwise.\nconst enableLogging = false\n+// emptyFilter is for comparison with a rule's filters to determine whether it\n+// is also empty. It is immutable.\n+var emptyFilter = stack.IPHeaderFilter{\n+ Dst: \"\\x00\\x00\\x00\\x00\",\n+ DstMask: \"\\x00\\x00\\x00\\x00\",\n+}\n+\n// nflog logs messages related to the writing and reading of iptables.\nfunc nflog(format string, args ...interface{}) {\nif enableLogging && log.IsLogging(log.Debug) {\n@@ -484,7 +491,7 @@ func SetEntries(stk *stack.Stack, optVal []byte) *syserr.Error {\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\", ruleIdx)\nreturn syserr.ErrInvalidArgument\n}\ntable.Underflows[hk] = ruleIdx\n@@ -547,7 +554,7 @@ func SetEntries(stk *stack.Stack, optVal []byte) *syserr.Error {\n// make sure all other chains point to ACCEPT rules.\nfor hook, ruleIdx := range table.BuiltinChains {\nif hook == stack.Forward || hook == stack.Postrouting {\n- if _, ok := table.Rules[ruleIdx].Target.(stack.AcceptTarget); !ok {\n+ if !isUnconditionalAccept(table.Rules[ruleIdx]) {\nnflog(\"hook %d is unsupported.\", hook)\nreturn syserr.ErrInvalidArgument\n}\n@@ -776,6 +783,9 @@ func validUnderflow(rule stack.Rule) bool {\nif len(rule.Matchers) != 0 {\nreturn false\n}\n+ if rule.Filter != emptyFilter {\n+ return false\n+ }\nswitch rule.Target.(type) {\ncase stack.AcceptTarget, stack.DropTarget:\nreturn true\n@@ -784,6 +794,14 @@ func validUnderflow(rule stack.Rule) bool {\n}\n}\n+func isUnconditionalAccept(rule stack.Rule) bool {\n+ if !validUnderflow(rule) {\n+ return false\n+ }\n+ _, ok := rule.Target.(stack.AcceptTarget)\n+ return ok\n+}\n+\nfunc hookFromLinux(hook int) stack.Hook {\nswitch hook {\ncase linux.NF_INET_PRE_ROUTING:\n"
}
] | Go | Apache License 2.0 | google/gvisor | iptables: check for truly unconditional rules
We weren't properly checking whether the inserted default rule was
unconditional. |
259,885 | 12.05.2020 12:24:23 | 25,200 | 8dd1d5b75a95100e747b1a88e9e557d5d2c30b64 | Don't call kernel.Task.Block() from netstack.SocketOperations.Write().
kernel.Task.Block() requires that the caller is running on the task goroutine.
netstack.SocketOperations.Write() uses kernel.TaskFromContext() to call
kernel.Task.Block() even if it's not running on the task goroutine. Stop doing
that. | [
{
"change_type": "MODIFY",
"old_path": "pkg/amutex/BUILD",
"new_path": "pkg/amutex/BUILD",
"diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"amutex\",\nsrcs = [\"amutex.go\"],\nvisibility = [\"//:sandbox\"],\n+ deps = [\"//pkg/syserror\"],\n)\ngo_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/amutex/amutex.go",
"new_path": "pkg/amutex/amutex.go",
"diff": "@@ -18,6 +18,8 @@ package amutex\nimport (\n\"sync/atomic\"\n+\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// Sleeper must be implemented by users of the abortable mutex to allow for\n@@ -53,6 +55,21 @@ func (NoopSleeper) SleepFinish(success bool) {}\n// Interrupted implements Sleeper.Interrupted.\nfunc (NoopSleeper) Interrupted() bool { return false }\n+// Block blocks until either receiving from ch succeeds (in which case it\n+// returns nil) or sleeper is interrupted (in which case it returns\n+// syserror.ErrInterrupted).\n+func Block(sleeper Sleeper, ch <-chan struct{}) error {\n+ cancel := sleeper.SleepStart()\n+ select {\n+ case <-ch:\n+ sleeper.SleepFinish(true)\n+ return nil\n+ case <-cancel:\n+ sleeper.SleepFinish(false)\n+ return syserror.ErrInterrupted\n+ }\n+}\n+\n// AbortableMutex is an abortable mutex. It allows Lock() to be aborted while it\n// waits to acquire the mutex.\ntype AbortableMutex struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/BUILD",
"new_path": "pkg/sentry/socket/netstack/BUILD",
"diff": "@@ -18,6 +18,7 @@ go_library(\n],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/amutex\",\n\"//pkg/binary\",\n\"//pkg/context\",\n\"//pkg/log\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -34,6 +34,7 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/amutex\"\n\"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/log\"\n@@ -553,11 +554,9 @@ func (s *SocketOperations) Write(ctx context.Context, _ *fs.File, src usermem.IO\n}\nif resCh != nil {\n- t := kernel.TaskFromContext(ctx)\n- if err := t.Block(resCh); err != nil {\n- return 0, syserr.FromError(err).ToError()\n+ if err := amutex.Block(ctx, resCh); err != nil {\n+ return 0, err\n}\n-\nn, _, err = s.Endpoint.Write(f, tcpip.WriteOptions{})\n}\n@@ -626,11 +625,9 @@ func (s *SocketOperations) ReadFrom(ctx context.Context, _ *fs.File, r io.Reader\n}\nif resCh != nil {\n- t := kernel.TaskFromContext(ctx)\n- if err := t.Block(resCh); err != nil {\n- return 0, syserr.FromError(err).ToError()\n+ if err := amutex.Block(ctx, resCh); err != nil {\n+ return 0, err\n}\n-\nn, _, err = s.Endpoint.Write(f, tcpip.WriteOptions{\nAtomic: true, // See above.\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack_vfs2.go",
"new_path": "pkg/sentry/socket/netstack/netstack_vfs2.go",
"diff": "@@ -16,6 +16,7 @@ package netstack\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/amutex\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs\"\n@@ -89,11 +90,6 @@ func (s *SocketVFS2) EventUnregister(e *waiter.Entry) {\ns.socketOpsCommon.EventUnregister(e)\n}\n-// PRead implements vfs.FileDescriptionImpl.\n-func (s *SocketVFS2) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n- return 0, syserror.ESPIPE\n-}\n-\n// Read implements vfs.FileDescriptionImpl.\nfunc (s *SocketVFS2) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.ReadOptions) (int64, error) {\n// All flags other than RWF_NOWAIT should be ignored.\n@@ -115,11 +111,6 @@ func (s *SocketVFS2) Read(ctx context.Context, dst usermem.IOSequence, opts vfs.\nreturn int64(n), nil\n}\n-// PWrite implements vfs.FileDescriptionImpl.\n-func (s *SocketVFS2) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- return 0, syserror.ESPIPE\n-}\n-\n// Write implements vfs.FileDescriptionImpl.\nfunc (s *SocketVFS2) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n// All flags other than RWF_NOWAIT should be ignored.\n@@ -135,11 +126,9 @@ func (s *SocketVFS2) Write(ctx context.Context, src usermem.IOSequence, opts vfs\n}\nif resCh != nil {\n- t := kernel.TaskFromContext(ctx)\n- if err := t.Block(resCh); err != nil {\n- return 0, syserr.FromError(err).ToError()\n+ if err := amutex.Block(ctx, resCh); err != nil {\n+ return 0, err\n}\n-\nn, _, err = s.Endpoint.Write(f, tcpip.WriteOptions{})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't call kernel.Task.Block() from netstack.SocketOperations.Write().
kernel.Task.Block() requires that the caller is running on the task goroutine.
netstack.SocketOperations.Write() uses kernel.TaskFromContext() to call
kernel.Task.Block() even if it's not running on the task goroutine. Stop doing
that.
PiperOrigin-RevId: 311178335 |
259,992 | 12.05.2020 17:24:46 | 25,200 | 305f786e51ea2092c633d97b06818e59c5f40552 | Adjust a few log messages | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -245,7 +245,6 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nif err := c.makeSyntheticMount(ctx, submount.Destination, root, creds); err != nil {\nreturn err\n}\n- log.Debugf(\"directory exists or made directory for submount: %s\", submount.Destination)\nopts := &vfs.MountOptions{\nGetFilesystemOptions: vfs.GetFilesystemOptions{\n@@ -260,7 +259,7 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nif err := c.k.VFS().MountAt(ctx, creds, \"\", target, fsName, opts); err != nil {\nreturn fmt.Errorf(\"failed to mount %q (type: %s): %w, opts: %v\", submount.Destination, submount.Type, err, opts)\n}\n- log.Infof(\"Mounted %q to %q type: %s, internal-options: %q\", submount.Source, submount.Destination, submount.Type, opts)\n+ log.Infof(\"Mounted %q to %q type: %s, internal-options: %q\", submount.Source, submount.Destination, submount.Type, opts.GetFilesystemOptions.Data)\nreturn nil\n}\n@@ -321,23 +320,23 @@ func (c *containerMounter) makeSyntheticMount(ctx context.Context, currentPath s\nStart: root,\nPath: fspath.Parse(currentPath),\n}\n-\n_, err := c.k.VFS().StatAt(ctx, creds, target, &vfs.StatOptions{})\n- switch {\n- case err == syserror.ENOENT:\n+ if err == nil {\n+ // Mount point exists, nothing else to do.\n+ return nil\n+ }\n+ if err != syserror.ENOENT {\n+ return fmt.Errorf(\"stat failed for %q during mount point creation: %w\", currentPath, err)\n+ }\n+\n+ // Recurse to ensure parent is created and then create the mount point.\nif err := c.makeSyntheticMount(ctx, path.Dir(currentPath), root, creds); err != nil {\nreturn err\n}\n+ log.Debugf(\"Creating dir %q for mount point\", currentPath)\nmkdirOpts := &vfs.MkdirOptions{Mode: 0777, ForSyntheticMountpoint: true}\nif err := c.k.VFS().MkdirAt(ctx, creds, target, mkdirOpts); err != nil {\n- return fmt.Errorf(\"failed to makedir for mount %+v: %w\", target, err)\n+ return fmt.Errorf(\"failed to create directory %q for mount: %w\", currentPath, err)\n}\nreturn nil\n-\n- case err != nil:\n- return fmt.Errorf(\"stat failed for mount %+v: %w\", target, err)\n-\n- default:\n- return nil\n- }\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Adjust a few log messages
PiperOrigin-RevId: 311234146 |
259,992 | 13.05.2020 10:30:00 | 25,200 | 18cb3d24cb3b59da11ebeac444021346495c95e4 | Use VFS2 mount names
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -37,6 +37,12 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/gofer\"\n\"gvisor.dev/gvisor/pkg/sentry/fs/ramfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devpts\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n+ gofervfs2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/gofer\"\n+ procvfs2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n+ sysvfs2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n+ tmpfsvfs2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n@@ -44,22 +50,14 @@ import (\n)\nconst (\n- // Filesystem name for 9p gofer mounts.\n- rootFsName = \"9p\"\n-\n// Device name for root mount.\nrootDevice = \"9pfs-/\"\n// MountPrefix is the annotation prefix for mount hints.\nMountPrefix = \"dev.gvisor.spec.mount.\"\n- // Filesystems that runsc supports.\n+ // Supported filesystems that map to different internal filesystem.\nbind = \"bind\"\n- devpts = \"devpts\"\n- devtmpfs = \"devtmpfs\"\n- proc = \"proc\"\n- sysfs = \"sysfs\"\n- tmpfs = \"tmpfs\"\nnonefs = \"none\"\n)\n@@ -108,12 +106,12 @@ func compileMounts(spec *specs.Spec) []specs.Mount {\n// Always mount /dev.\nmounts = append(mounts, specs.Mount{\n- Type: devtmpfs,\n+ Type: devtmpfs.Name,\nDestination: \"/dev\",\n})\nmounts = append(mounts, specs.Mount{\n- Type: devpts,\n+ Type: devpts.Name,\nDestination: \"/dev/pts\",\n})\n@@ -137,13 +135,13 @@ func compileMounts(spec *specs.Spec) []specs.Mount {\nvar mandatoryMounts []specs.Mount\nif !procMounted {\nmandatoryMounts = append(mandatoryMounts, specs.Mount{\n- Type: proc,\n+ Type: procvfs2.Name,\nDestination: \"/proc\",\n})\n}\nif !sysMounted {\nmandatoryMounts = append(mandatoryMounts, specs.Mount{\n- Type: sysfs,\n+ Type: sysvfs2.Name,\nDestination: \"/sys\",\n})\n}\n@@ -156,12 +154,16 @@ func compileMounts(spec *specs.Spec) []specs.Mount {\n}\n// p9MountOptions creates a slice of options for a p9 mount.\n-func p9MountOptions(fd int, fa FileAccessType) []string {\n+func p9MountOptions(fd int, fa FileAccessType, vfs2 bool) []string {\nopts := []string{\n\"trans=fd\",\n\"rfdno=\" + strconv.Itoa(fd),\n\"wfdno=\" + strconv.Itoa(fd),\n- \"privateunixsocket=true\",\n+ }\n+ if !vfs2 {\n+ // privateunixsocket is always enabled in VFS2. VFS1 requires explicit\n+ // enablement.\n+ opts = append(opts, \"privateunixsocket=true\")\n}\nif fa == FileAccessShared {\nopts = append(opts, \"cache=remote_revalidating\")\n@@ -234,7 +236,7 @@ func isSupportedMountFlag(fstype, opt string) bool {\ncase \"rw\", \"ro\", \"noatime\", \"noexec\":\nreturn true\n}\n- if fstype == tmpfs {\n+ if fstype == tmpfsvfs2.Name {\nok, err := parseMountOption(opt, tmpfsAllowedOptions...)\nreturn ok && err == nil\n}\n@@ -444,7 +446,7 @@ func (m *mountHint) setOptions(val string) error {\n}\nfunc (m *mountHint) isSupported() bool {\n- return m.mount.Type == tmpfs && m.share == pod\n+ return m.mount.Type == tmpfsvfs2.Name && m.share == pod\n}\n// checkCompatible verifies that shared mount is compatible with master.\n@@ -586,7 +588,7 @@ func (c *containerMounter) processHints(conf *Config) error {\nfor _, hint := range c.hints.mounts {\n// TODO(b/142076984): Only support tmpfs for now. Bind mounts require a\n// common gofer to mount all shared volumes.\n- if hint.mount.Type != tmpfs {\n+ if hint.mount.Type != tmpfsvfs2.Name {\ncontinue\n}\nlog.Infof(\"Mounting master of shared mount %q from %q type %q\", hint.name, hint.mount.Source, hint.mount.Type)\n@@ -723,7 +725,7 @@ func (c *containerMounter) createRootMount(ctx context.Context, conf *Config) (*\nfd := c.fds.remove()\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\np9FS := mustFindFilesystem(\"9p\")\n- opts := p9MountOptions(fd, conf.FileAccess)\n+ opts := p9MountOptions(fd, conf.FileAccess, false /* vfs2 */)\nif conf.OverlayfsStaleRead {\n// We can't check for overlayfs here because sandbox is chroot'ed and gofer\n@@ -779,11 +781,11 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\n}\nswitch m.Type {\n- case devpts, devtmpfs, proc, sysfs:\n+ case devpts.Name, devtmpfs.Name, procvfs2.Name, sysvfs2.Name:\nfsName = m.Type\ncase nonefs:\n- fsName = sysfs\n- case tmpfs:\n+ fsName = sysvfs2.Name\n+ case tmpfsvfs2.Name:\nfsName = m.Type\nvar err error\n@@ -794,8 +796,8 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\ncase bind:\nfd := c.fds.remove()\n- fsName = \"9p\"\n- opts = p9MountOptions(fd, c.getMountAccessType(m))\n+ fsName = gofervfs2.Name\n+ opts = p9MountOptions(fd, c.getMountAccessType(m), conf.VFS2)\n// If configured, add overlay to all writable mounts.\nuseOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n@@ -948,7 +950,7 @@ func (c *containerMounter) createRestoreEnvironment(conf *Config) (*fs.RestoreEn\n// Add root mount.\nfd := c.fds.remove()\n- opts := p9MountOptions(fd, conf.FileAccess)\n+ opts := p9MountOptions(fd, conf.FileAccess, false /* vfs2 */)\nmf := fs.MountSourceFlags{}\nif c.root.Readonly || conf.Overlay {\n@@ -960,7 +962,7 @@ func (c *containerMounter) createRestoreEnvironment(conf *Config) (*fs.RestoreEn\nFlags: mf,\nDataString: strings.Join(opts, \",\"),\n}\n- renv.MountSources[rootFsName] = append(renv.MountSources[rootFsName], rootMount)\n+ renv.MountSources[gofervfs2.Name] = append(renv.MountSources[gofervfs2.Name], rootMount)\n// Add submounts.\nvar tmpMounted bool\n@@ -976,7 +978,7 @@ func (c *containerMounter) createRestoreEnvironment(conf *Config) (*fs.RestoreEn\n// TODO(b/67958150): handle '/tmp' properly (see mountTmp()).\nif !tmpMounted {\ntmpMount := specs.Mount{\n- Type: tmpfs,\n+ Type: tmpfsvfs2.Name,\nDestination: \"/tmp\",\n}\nif err := c.addRestoreMount(conf, renv, tmpMount); err != nil {\n@@ -1032,7 +1034,7 @@ func (c *containerMounter) mountTmp(ctx context.Context, conf *Config, mns *fs.M\n// No '/tmp' found (or fallthrough from above). Safe to mount internal\n// tmpfs.\ntmpMount := specs.Mount{\n- Type: tmpfs,\n+ Type: tmpfsvfs2.Name,\nDestination: \"/tmp\",\n// Sticky bit is added to prevent accidental deletion of files from\n// another user. This is normally done for /tmp.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -18,7 +18,6 @@ import (\n\"fmt\"\n\"path\"\n\"sort\"\n- \"strconv\"\n\"strings\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n@@ -26,12 +25,12 @@ import (\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/devices/memdev\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n- devpts2 \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devpts\"\n- devtmpfsimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n- goferimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/gofer\"\n- procimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n- sysimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n- tmpfsimpl \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devpts\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/gofer\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -42,28 +41,28 @@ import (\n)\nfunc registerFilesystems(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials) error {\n- vfsObj.MustRegisterFilesystemType(devpts2.Name, &devpts2.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(devpts.Name, &devpts.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserList: true,\n// TODO(b/29356795): Users may mount this once the terminals are in a\n// usable state.\nAllowUserMount: false,\n})\n- vfsObj.MustRegisterFilesystemType(devtmpfsimpl.Name, &devtmpfsimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(devtmpfs.Name, &devtmpfs.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserMount: true,\nAllowUserList: true,\n})\n- vfsObj.MustRegisterFilesystemType(goferimpl.Name, &goferimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(gofer.Name, &gofer.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserList: true,\n})\n- vfsObj.MustRegisterFilesystemType(procimpl.Name, &procimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(proc.Name, &proc.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserMount: true,\nAllowUserList: true,\n})\n- vfsObj.MustRegisterFilesystemType(sysimpl.Name, &sysimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(sys.Name, &sys.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserMount: true,\nAllowUserList: true,\n})\n- vfsObj.MustRegisterFilesystemType(tmpfsimpl.Name, &tmpfsimpl.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ vfsObj.MustRegisterFilesystemType(tmpfs.Name, &tmpfs.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserMount: true,\nAllowUserList: true,\n})\n@@ -72,7 +71,7 @@ func registerFilesystems(ctx context.Context, vfsObj *vfs.VirtualFilesystem, cre\nif err := memdev.Register(vfsObj); err != nil {\nreturn fmt.Errorf(\"registering memdev: %w\", err)\n}\n- a, err := devtmpfsimpl.NewAccessor(ctx, vfsObj, creds, devtmpfsimpl.Name)\n+ a, err := devtmpfs.NewAccessor(ctx, vfsObj, creds, devtmpfs.Name)\nif err != nil {\nreturn fmt.Errorf(\"creating devtmpfs accessor: %w\", err)\n}\n@@ -193,10 +192,10 @@ func (c *containerMounter) setupVFS2(ctx context.Context, conf *Config, procArgs\nfunc (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *Config, creds *auth.Credentials) (*vfs.MountNamespace, error) {\nfd := c.fds.remove()\n- opts := strings.Join(p9MountOptionsVFS2(fd, conf.FileAccess), \",\")\n+ opts := strings.Join(p9MountOptions(fd, conf.FileAccess, true /* vfs2 */), \",\")\nlog.Infof(\"Mounting root over 9P, ioFD: %d\", fd)\n- mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", rootFsName, &vfs.GetFilesystemOptions{Data: opts})\n+ mns, err := c.k.VFS().NewMountNamespace(ctx, creds, \"\", gofer.Name, &vfs.GetFilesystemOptions{Data: opts})\nif err != nil {\nreturn nil, fmt.Errorf(\"setting up mount namespace: %w\", err)\n}\n@@ -223,7 +222,8 @@ func (c *containerMounter) prepareMountsVFS2() {\nsort.Slice(c.mounts, func(i, j int) bool { return len(c.mounts[i].Destination) < len(c.mounts[j].Destination) })\n}\n-// TODO(gvisor.dev/issue/1487): Implement submount options similar to the VFS1 version.\n+// TODO(gvisor.dev/issue/1487): Implement submount options similar to the VFS1\n+// version.\nfunc (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials, submount *specs.Mount) error {\nroot := mns.Root()\ndefer root.DecRef()\n@@ -233,7 +233,7 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nPath: fspath.Parse(submount.Destination),\n}\n- fsName, options, useOverlay, err := c.getMountNameAndOptionsVFS2(conf, *submount)\n+ fsName, options, useOverlay, err := c.getMountNameAndOptions(conf, *submount)\nif err != nil {\nreturn fmt.Errorf(\"mountOptions failed: %w\", err)\n}\n@@ -263,57 +263,6 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nreturn nil\n}\n-// getMountNameAndOptionsVFS2 retrieves the fsName, opts, and useOverlay values\n-// used for mounts.\n-func (c *containerMounter) getMountNameAndOptionsVFS2(conf *Config, m specs.Mount) (string, []string, bool, error) {\n- var (\n- fsName string\n- opts []string\n- useOverlay bool\n- )\n-\n- switch m.Type {\n- case devpts, devtmpfs, proc, sysfs:\n- fsName = m.Type\n- case nonefs:\n- fsName = sysfs\n- case tmpfs:\n- fsName = m.Type\n-\n- var err error\n- opts, err = parseAndFilterOptions(m.Options, tmpfsAllowedOptions...)\n- if err != nil {\n- return \"\", nil, false, err\n- }\n-\n- case bind:\n- fd := c.fds.remove()\n- fsName = \"9p\"\n- opts = p9MountOptionsVFS2(fd, c.getMountAccessType(m))\n- // If configured, add overlay to all writable mounts.\n- useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n-\n- default:\n- log.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n- }\n- return fsName, opts, useOverlay, nil\n-}\n-\n-// p9MountOptions creates a slice of options for a p9 mount.\n-// TODO(gvisor.dev/issue/1624): Remove this version once privateunixsocket is\n-// deleted, along with the rest of VFS1.\n-func p9MountOptionsVFS2(fd int, fa FileAccessType) []string {\n- opts := []string{\n- \"trans=fd\",\n- \"rfdno=\" + strconv.Itoa(fd),\n- \"wfdno=\" + strconv.Itoa(fd),\n- }\n- if fa == FileAccessShared {\n- opts = append(opts, \"cache=remote_revalidating\")\n- }\n- return opts\n-}\n-\nfunc (c *containerMounter) makeSyntheticMount(ctx context.Context, currentPath string, root vfs.VirtualDentry, creds *auth.Credentials) error {\ntarget := &vfs.PathOperation{\nRoot: root,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use VFS2 mount names
Updates #1487
PiperOrigin-RevId: 311356385 |
259,885 | 13.05.2020 18:16:45 | 25,200 | 64afaf0e9bb712938f3621b8588840b5398b883c | Fix runsc association of gofers and FDs on VFS2.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -770,14 +770,8 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nuseOverlay bool\n)\n- for _, opt := range m.Options {\n- // When options include either \"bind\" or \"rbind\", this behaves as\n- // bind mount even if the mount type is equal to a filesystem supported\n- // on runsc.\n- if opt == \"bind\" || opt == \"rbind\" {\n+ if isBindMount(m) {\nm.Type = bind\n- break\n- }\n}\nswitch m.Type {\n@@ -807,6 +801,18 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nreturn fsName, opts, useOverlay, nil\n}\n+func isBindMount(m specs.Mount) bool {\n+ for _, opt := range m.Options {\n+ // When options include either \"bind\" or \"rbind\", this behaves as\n+ // bind mount even if the mount type is equal to a filesystem supported\n+ // on runsc.\n+ if opt == \"bind\" || opt == \"rbind\" {\n+ return true\n+ }\n+ }\n+ return false\n+}\n+\nfunc (c *containerMounter) getMountAccessType(mount specs.Mount) FileAccessType {\nif hint := c.hints.findMount(mount); hint != nil {\nreturn hint.fileAccessType()\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -203,28 +203,61 @@ func (c *containerMounter) createMountNamespaceVFS2(ctx context.Context, conf *C\n}\nfunc (c *containerMounter) mountSubmountsVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials) error {\n- c.prepareMountsVFS2()\n+ mounts, err := c.prepareMountsVFS2()\n+ if err != nil {\n+ return err\n+ }\n- for _, submount := range c.mounts {\n+ for i := range mounts {\n+ submount := &mounts[i]\nlog.Debugf(\"Mounting %q to %q, type: %s, options: %s\", submount.Source, submount.Destination, submount.Type, submount.Options)\n- if err := c.mountSubmountVFS2(ctx, conf, mns, creds, &submount); err != nil {\n+ if err := c.mountSubmountVFS2(ctx, conf, mns, creds, submount); err != nil {\nreturn err\n}\n}\n// TODO(gvisor.dev/issue/1487): implement mountTmp from fs.go.\n- return c.checkDispenser()\n+ return nil\n+}\n+\n+type mountAndFD struct {\n+ specs.Mount\n+ fd int\n+}\n+\n+func (c *containerMounter) prepareMountsVFS2() ([]mountAndFD, error) {\n+ // Associate bind mounts with their FDs before sorting since there is an\n+ // undocumented assumption that FDs are dispensed in the order in which\n+ // they are required by mounts.\n+ var mounts []mountAndFD\n+ for _, m := range c.mounts {\n+ fd := -1\n+ // Only bind mounts use host FDs; see\n+ // containerMounter.getMountNameAndOptionsVFS2.\n+ if m.Type == bind || isBindMount(m) {\n+ fd = c.fds.remove()\n+ }\n+ mounts = append(mounts, mountAndFD{\n+ Mount: m,\n+ fd: fd,\n+ })\n+ }\n+ if err := c.checkDispenser(); err != nil {\n+ return nil, err\n}\n-func (c *containerMounter) prepareMountsVFS2() {\n// Sort the mounts so that we don't place children before parents.\n- sort.Slice(c.mounts, func(i, j int) bool { return len(c.mounts[i].Destination) < len(c.mounts[j].Destination) })\n+ sort.Slice(mounts, func(i, j int) bool {\n+ return len(mounts[i].Destination) < len(mounts[j].Destination)\n+ })\n+\n+ return mounts, nil\n}\n// TODO(gvisor.dev/issue/1487): Implement submount options similar to the VFS1\n// version.\n-func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials, submount *specs.Mount) error {\n+func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config, mns *vfs.MountNamespace, creds *auth.Credentials, submount *mountAndFD) error {\nroot := mns.Root()\ndefer root.DecRef()\ntarget := &vfs.PathOperation{\n@@ -233,7 +266,7 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nPath: fspath.Parse(submount.Destination),\n}\n- fsName, options, useOverlay, err := c.getMountNameAndOptions(conf, *submount)\n+ fsName, options, useOverlay, err := c.getMountNameAndOptionsVFS2(conf, submount)\nif err != nil {\nreturn fmt.Errorf(\"mountOptions failed: %w\", err)\n}\n@@ -263,6 +296,45 @@ func (c *containerMounter) mountSubmountVFS2(ctx context.Context, conf *Config,\nreturn nil\n}\n+// getMountNameAndOptionsVFS2 retrieves the fsName, opts, and useOverlay values\n+// used for mounts.\n+func (c *containerMounter) getMountNameAndOptionsVFS2(conf *Config, m *mountAndFD) (string, []string, bool, error) {\n+ var (\n+ fsName string\n+ opts []string\n+ useOverlay bool\n+ )\n+\n+ if isBindMount(m.Mount) {\n+ m.Type = bind\n+ }\n+\n+ switch m.Type {\n+ case devpts.Name, devtmpfs.Name, proc.Name, sys.Name:\n+ fsName = m.Type\n+ case nonefs:\n+ fsName = sys.Name\n+ case tmpfs.Name:\n+ fsName = m.Type\n+\n+ var err error\n+ opts, err = parseAndFilterOptions(m.Options, tmpfsAllowedOptions...)\n+ if err != nil {\n+ return \"\", nil, false, err\n+ }\n+\n+ case bind:\n+ fsName = gofer.Name\n+ opts = p9MountOptions(m.fd, c.getMountAccessType(m.Mount), true /* vfs2 */)\n+ // If configured, add overlay to all writable mounts.\n+ useOverlay = conf.Overlay && !mountFlags(m.Options).ReadOnly\n+\n+ default:\n+ log.Warningf(\"ignoring unknown filesystem type %q\", m.Type)\n+ }\n+ return fsName, opts, useOverlay, nil\n+}\n+\nfunc (c *containerMounter) makeSyntheticMount(ctx context.Context, currentPath string, root vfs.VirtualDentry, creds *auth.Credentials) error {\ntarget := &vfs.PathOperation{\nRoot: root,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix runsc association of gofers and FDs on VFS2.
Updates #1487
PiperOrigin-RevId: 311443628 |
259,962 | 13.05.2020 19:47:42 | 25,200 | 8b8774d7152eb61fc6273bbae679e80c34188517 | Stub support for TCP_SYNCNT and TCP_WINDOW_CLAMP.
This change adds support for TCP_SYNCNT and TCP_WINDOW_CLAMP options
in GetSockOpt/SetSockOpt. This change does not really change any
behaviour in Netstack and only stores/returns the stored value.
Actual honoring of these options will be added as required.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -1321,6 +1321,29 @@ func getSockOptTCP(t *kernel.Task, ep commonEndpoint, name, outLen int) (interfa\nreturn int32(time.Duration(v) / time.Second), nil\n+ case linux.TCP_SYNCNT:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ v, err := ep.GetSockOptInt(tcpip.TCPSynCountOption)\n+ if err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(v), nil\n+\n+ case linux.TCP_WINDOW_CLAMP:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ v, err := ep.GetSockOptInt(tcpip.TCPWindowClampOption)\n+ if err != nil {\n+ return nil, syserr.TranslateNetstackError(err)\n+ }\n+\n+ return int32(v), nil\ndefault:\nemitUnimplementedEventTCP(t, name)\n}\n@@ -1790,6 +1813,22 @@ func setSockOptTCP(t *kernel.Task, ep commonEndpoint, name int, optVal []byte) *\n}\nreturn syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.TCPDeferAcceptOption(time.Second * time.Duration(v))))\n+ case linux.TCP_SYNCNT:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ v := usermem.ByteOrder.Uint32(optVal)\n+\n+ return syserr.TranslateNetstackError(ep.SetSockOptInt(tcpip.TCPSynCountOption, int(v)))\n+\n+ case linux.TCP_WINDOW_CLAMP:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ v := usermem.ByteOrder.Uint32(optVal)\n+\n+ return syserr.TranslateNetstackError(ep.SetSockOptInt(tcpip.TCPWindowClampOption, int(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": "@@ -622,6 +622,19 @@ const (\n//\n// A zero value indicates the default.\nTTLOption\n+\n+ // TCPSynCountOption is used by SetSockOpt/GetSockOpt to specify the number of\n+ // SYN retransmits that TCP should send before aborting the attempt to\n+ // connect. It cannot exceed 255.\n+ //\n+ // NOTE: This option is currently only stubbed out and is no-op.\n+ TCPSynCountOption\n+\n+ // TCPWindowClampOption is used by SetSockOpt/GetSockOpt to bound the size\n+ // of the advertised window to this value.\n+ //\n+ // NOTE: This option is currently only stubed out and is a no-op\n+ TCPWindowClampOption\n)\n// ErrorOption is used in GetSockOpt to specify that the last error reported by\n@@ -690,6 +703,10 @@ type TCPMinRTOOption time.Duration\n// switches to using SYN cookies.\ntype TCPSynRcvdCountThresholdOption uint64\n+// TCPSynRetriesOption is used by SetSockOpt/GetSockOpt to specify stack-wide\n+// default for number of times SYN is retransmitted before aborting a connect.\n+type TCPSynRetriesOption uint8\n+\n// MulticastInterfaceOption is used by SetSockOpt/GetSockOpt to specify a\n// default interface for multicast.\ntype MulticastInterfaceOption struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -470,6 +470,17 @@ type endpoint struct {\n// for this endpoint using the TCP_MAXSEG setsockopt.\nuserMSS uint16\n+ // maxSynRetries is the maximum number of SYN retransmits that TCP should\n+ // send before aborting the attempt to connect. It cannot exceed 255.\n+ //\n+ // NOTE: This is currently a no-op and does not change the SYN\n+ // retransmissions.\n+ maxSynRetries uint8\n+\n+ // windowClamp is used to bound the size of the advertised window to\n+ // this value.\n+ windowClamp uint32\n+\n// The following fields are used to manage the send buffer. When\n// segments are ready to be sent, they are added to sndQueue and the\n// protocol goroutine is signaled via sndWaker.\n@@ -797,6 +808,8 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\n},\nuniqueID: s.UniqueID(),\ntxHash: s.Rand().Uint32(),\n+ windowClamp: DefaultReceiveBufferSize,\n+ maxSynRetries: DefaultSynRetries,\n}\nvar ss SendBufferSizeOption\n@@ -829,6 +842,11 @@ func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQue\ne.tcpLingerTimeout = time.Duration(tcpLT)\n}\n+ var synRetries tcpip.TCPSynRetriesOption\n+ if err := s.TransportProtocolOption(ProtocolNumber, &synRetries); err == nil {\n+ e.maxSynRetries = uint8(synRetries)\n+ }\n+\nif p := s.GetTCPProbe(); p != nil {\ne.probe = p\n}\n@@ -1603,6 +1621,36 @@ func (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) *tcpip.Error {\ne.ttl = uint8(v)\ne.UnlockUser()\n+ case tcpip.TCPSynCountOption:\n+ if v < 1 || v > 255 {\n+ return tcpip.ErrInvalidOptionValue\n+ }\n+ e.LockUser()\n+ e.maxSynRetries = uint8(v)\n+ e.UnlockUser()\n+\n+ case tcpip.TCPWindowClampOption:\n+ if v == 0 {\n+ e.LockUser()\n+ switch e.EndpointState() {\n+ case StateClose, StateInitial:\n+ e.windowClamp = 0\n+ e.UnlockUser()\n+ return nil\n+ default:\n+ e.UnlockUser()\n+ return tcpip.ErrInvalidOptionValue\n+ }\n+ }\n+ var rs ReceiveBufferSizeOption\n+ if err := e.stack.TransportProtocolOption(ProtocolNumber, &rs); err == nil {\n+ if v < rs.Min/2 {\n+ v = rs.Min / 2\n+ }\n+ }\n+ e.LockUser()\n+ e.windowClamp = uint32(v)\n+ e.UnlockUser()\n}\nreturn nil\n}\n@@ -1826,6 +1874,18 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, *tcpip.Error) {\ne.UnlockUser()\nreturn v, nil\n+ case tcpip.TCPSynCountOption:\n+ e.LockUser()\n+ v := int(e.maxSynRetries)\n+ e.UnlockUser()\n+ return v, nil\n+\n+ case tcpip.TCPWindowClampOption:\n+ e.LockUser()\n+ v := int(e.windowClamp)\n+ e.UnlockUser()\n+ return v, nil\n+\ndefault:\nreturn -1, tcpip.ErrUnknownProtocolOption\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -64,6 +64,10 @@ const (\n// DefaultTCPTimeWaitTimeout is the amount of time that sockets linger\n// in TIME_WAIT state before being marked closed.\nDefaultTCPTimeWaitTimeout = 60 * time.Second\n+\n+ // DefaultSynRetries is the default value for the number of SYN retransmits\n+ // before a connect is aborted.\n+ DefaultSynRetries = 6\n)\n// SACKEnabled option can be used to enable SACK support in the TCP\n@@ -164,6 +168,7 @@ type protocol struct {\ntcpTimeWaitTimeout time.Duration\nminRTO time.Duration\nsynRcvdCount synRcvdCounter\n+ synRetries uint8\ndispatcher *dispatcher\n}\n@@ -346,6 +351,15 @@ func (p *protocol) SetOption(option interface{}) *tcpip.Error {\np.mu.Unlock()\nreturn nil\n+ case tcpip.TCPSynRetriesOption:\n+ if v < 1 || v > 255 {\n+ return tcpip.ErrInvalidOptionValue\n+ }\n+ p.mu.Lock()\n+ p.synRetries = uint8(v)\n+ p.mu.Unlock()\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -420,6 +434,12 @@ func (p *protocol) Option(option interface{}) *tcpip.Error {\np.mu.RUnlock()\nreturn nil\n+ case *tcpip.TCPSynRetriesOption:\n+ p.mu.RLock()\n+ *v = tcpip.TCPSynRetriesOption(p.synRetries)\n+ p.mu.RUnlock()\n+ return nil\n+\ndefault:\nreturn tcpip.ErrUnknownProtocolOption\n}\n@@ -452,6 +472,7 @@ func NewProtocol() stack.TransportProtocol {\ntcpTimeWaitTimeout: DefaultTCPTimeWaitTimeout,\nsynRcvdCount: synRcvdCounter{threshold: SynRcvdCountThreshold},\ndispatcher: newDispatcher(runtime.GOMAXPROCS(0)),\n+ synRetries: DefaultSynRetries,\nminRTO: MinRTO,\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -876,6 +876,51 @@ TEST_P(TCPSocketPairTest, SetTCPUserTimeoutAboveZero) {\nEXPECT_EQ(get, kAbove);\n}\n+TEST_P(TCPSocketPairTest, SetTCPWindowClampBelowMinRcvBufConnectedSocket) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ // Discover minimum receive buf by setting a really low value\n+ // for the receive buffer.\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVBUF, &kZero,\n+ sizeof(kZero)),\n+ SyscallSucceeds());\n+\n+ // Now retrieve the minimum value for SO_RCVBUF as the set above should\n+ // have caused SO_RCVBUF for the socket to be set to the minimum.\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(sockets->first_fd(), SOL_SOCKET, SO_RCVBUF, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ int min_so_rcvbuf = get;\n+\n+ {\n+ // Setting TCP_WINDOW_CLAMP to zero for a connected socket is not permitted.\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_WINDOW_CLAMP,\n+ &kZero, sizeof(kZero)),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ // Non-zero clamp values below MIN_SO_RCVBUF/2 should result in the clamp\n+ // being set to MIN_SO_RCVBUF/2.\n+ int below_half_min_so_rcvbuf = min_so_rcvbuf / 2 - 1;\n+ EXPECT_THAT(\n+ setsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_WINDOW_CLAMP,\n+ &below_half_min_so_rcvbuf, sizeof(below_half_min_so_rcvbuf)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+\n+ ASSERT_THAT(getsockopt(sockets->first_fd(), IPPROTO_TCP, TCP_WINDOW_CLAMP,\n+ &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(min_so_rcvbuf / 2, get);\n+ }\n+}\n+\nTEST_P(TCPSocketPairTest, TCPResetDuringClose_NoRandomSave) {\nDisableSave ds; // Too many syscalls.\nconstexpr int kThreadCount = 1000;\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -1313,7 +1313,7 @@ TEST_P(SimpleTcpSocketTest, SetTCPDeferAcceptNeg) {\nint get = -1;\nsocklen_t get_len = sizeof(get);\nASSERT_THAT(\n- getsockopt(s.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT, &get, &get_len),\nSyscallSucceedsWithValue(0));\nEXPECT_EQ(get_len, sizeof(get));\nEXPECT_EQ(get, 0);\n@@ -1326,7 +1326,7 @@ TEST_P(SimpleTcpSocketTest, GetTCPDeferAcceptDefault) {\nint get = -1;\nsocklen_t get_len = sizeof(get);\nASSERT_THAT(\n- getsockopt(s.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT, &get, &get_len),\nSyscallSucceedsWithValue(0));\nEXPECT_EQ(get_len, sizeof(get));\nEXPECT_EQ(get, 0);\n@@ -1378,6 +1378,187 @@ TEST_P(SimpleTcpSocketTest, TCPConnectSoRcvBufRace) {\nSyscallSucceedsWithValue(0));\n}\n+TEST_P(SimpleTcpSocketTest, SetTCPSynCntLessThanOne) {\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(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ int default_syn_cnt = get;\n+\n+ {\n+ // TCP_SYNCNT less than 1 should be rejected with an EINVAL.\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &kZero, sizeof(kZero)),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ // TCP_SYNCNT less than 1 should be rejected with an EINVAL.\n+ constexpr int kNeg = -1;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &kNeg, sizeof(kNeg)),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+\n+ ASSERT_THAT(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(default_syn_cnt, get);\n+ }\n+}\n+\n+TEST_P(SimpleTcpSocketTest, GetTCPSynCntDefault) {\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+ constexpr int kDefaultSynCnt = 6;\n+\n+ ASSERT_THAT(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kDefaultSynCnt);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPSynCntGreaterThanOne) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+ constexpr int kTCPSynCnt = 20;\n+ ASSERT_THAT(setsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &kTCPSynCnt,\n+ sizeof(kTCPSynCnt)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kTCPSynCnt);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPSynCntAboveMax) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ int default_syn_cnt = get;\n+ {\n+ constexpr int kTCPSynCnt = 256;\n+ ASSERT_THAT(setsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &kTCPSynCnt,\n+ sizeof(kTCPSynCnt)),\n+ SyscallFailsWithErrno(EINVAL));\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(getsockopt(s.get(), IPPROTO_TCP, TCP_SYNCNT, &get, &get_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, default_syn_cnt);\n+ }\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPWindowClampBelowMinRcvBuf) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ // Discover minimum receive buf by setting a really low value\n+ // for the receive buffer.\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(s.get(), SOL_SOCKET, SO_RCVBUF, &kZero, sizeof(kZero)),\n+ SyscallSucceeds());\n+\n+ // Now retrieve the minimum value for SO_RCVBUF as the set above should\n+ // have caused SO_RCVBUF for the socket to be set to the minimum.\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(getsockopt(s.get(), SOL_SOCKET, SO_RCVBUF, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ int min_so_rcvbuf = get;\n+\n+ {\n+ // TCP_WINDOW_CLAMP less than min_so_rcvbuf/2 should be set to\n+ // min_so_rcvbuf/2.\n+ int below_half_min_rcvbuf = min_so_rcvbuf / 2 - 1;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP,\n+ &below_half_min_rcvbuf, sizeof(below_half_min_rcvbuf)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(min_so_rcvbuf / 2, get);\n+ }\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPWindowClampZeroClosedSocket) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+ constexpr int kZero = 0;\n+ ASSERT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP, &kZero, sizeof(kZero)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP, &get, &get_len),\n+ SyscallSucceeds());\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(get, kZero);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, SetTCPWindowClampAboveHalfMinRcvBuf) {\n+ FileDescriptor s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_STREAM, IPPROTO_TCP));\n+\n+ // Discover minimum receive buf by setting a really low value\n+ // for the receive buffer.\n+ constexpr int kZero = 0;\n+ EXPECT_THAT(setsockopt(s.get(), SOL_SOCKET, SO_RCVBUF, &kZero, sizeof(kZero)),\n+ SyscallSucceeds());\n+\n+ // Now retrieve the minimum value for SO_RCVBUF as the set above should\n+ // have caused SO_RCVBUF for the socket to be set to the minimum.\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+ ASSERT_THAT(getsockopt(s.get(), SOL_SOCKET, SO_RCVBUF, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ int min_so_rcvbuf = get;\n+\n+ {\n+ int above_half_min_rcv_buf = min_so_rcvbuf / 2 + 1;\n+ EXPECT_THAT(\n+ setsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP,\n+ &above_half_min_rcv_buf, sizeof(above_half_min_rcv_buf)),\n+ SyscallSucceeds());\n+\n+ int get = -1;\n+ socklen_t get_len = sizeof(get);\n+\n+ ASSERT_THAT(\n+ getsockopt(s.get(), IPPROTO_TCP, TCP_WINDOW_CLAMP, &get, &get_len),\n+ SyscallSucceedsWithValue(0));\n+ EXPECT_EQ(get_len, sizeof(get));\n+ EXPECT_EQ(above_half_min_rcv_buf, get);\n+ }\n+}\n+\nINSTANTIATE_TEST_SUITE_P(AllInetTests, SimpleTcpSocketTest,\n::testing::Values(AF_INET, AF_INET6));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub support for TCP_SYNCNT and TCP_WINDOW_CLAMP.
This change adds support for TCP_SYNCNT and TCP_WINDOW_CLAMP options
in GetSockOpt/SetSockOpt. This change does not really change any
behaviour in Netstack and only stores/returns the stored value.
Actual honoring of these options will be added as required.
Fixes #2626, #2625
PiperOrigin-RevId: 311453777 |
259,858 | 14.05.2020 14:00:52 | 25,200 | f589a85889c815cebac624122aebe14c8263a574 | Run issue_reviver via GitHub. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/issue_reviver.yml",
"diff": "+name: \"Issue reviver\"\n+on:\n+ schedule:\n+ - cron: '0 0 * * *'\n+\n+jobs:\n+ label:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/checkout@v2\n+ - run: make run TARGETS=\"//tools/issue_reviver\"\n+ env:\n+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n+ GITHUB_REPOSITORY: ${{ github.repository }}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -59,6 +59,8 @@ SHELL=/bin/bash -o pipefail\n## DOCKER_SOCKET - The Docker socket (default: detected).\n##\nbazel-server-start: load-default ## Starts the bazel server.\n+ @mkdir -p $(BAZEL_CACHE)\n+ @mkdir -p $(GCLOUD_CONFIG)\ndocker run -d --rm \\\n--init \\\n--name $(DOCKER_NAME) \\\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/issue_reviver/main.go",
"new_path": "tools/issue_reviver/main.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"fmt\"\n\"io/ioutil\"\n\"os\"\n+ \"strings\"\n\"gvisor.dev/gvisor/tools/issue_reviver/github\"\n\"gvisor.dev/gvisor/tools/issue_reviver/reviver\"\n@@ -35,14 +36,22 @@ var (\n// Keep the options simple for now. Supports only a single path and repo.\nfunc init() {\n- flag.StringVar(&owner, \"owner\", \"google\", \"Github project org/owner to look for issues\")\n- flag.StringVar(&repo, \"repo\", \"gvisor\", \"Github repo to look for issues\")\n+ flag.StringVar(&owner, \"owner\", \"\", \"Github project org/owner to look for issues\")\n+ flag.StringVar(&repo, \"repo\", \"\", \"Github repo to look for issues\")\nflag.StringVar(&tokenFile, \"oauth-token-file\", \"\", \"Path to file containing the OAUTH token to be used as credential to github\")\n- flag.StringVar(&path, \"path\", \"\", \"Path to scan for TODOs\")\n+ flag.StringVar(&path, \"path\", \".\", \"Path to scan for TODOs\")\nflag.BoolVar(&dryRun, \"dry-run\", false, \"If set to true, no changes are made to issues\")\n}\nfunc main() {\n+ // Set defaults from the environment.\n+ repository := os.Getenv(\"GITHUB_REPOSITORY\")\n+ if parts := strings.SplitN(repository, \"/\", 2); len(parts) == 2 {\n+ owner = parts[0]\n+ repo = parts[1]\n+ }\n+\n+ // Parse flags.\nflag.Parse()\n// Check for mandatory parameters.\n@@ -62,8 +71,10 @@ func main() {\nos.Exit(1)\n}\n- // Token is passed as a file so it doesn't show up in command line arguments.\n- var token string\n+ // The access token may be passed as a file so it doesn't show up in\n+ // command line arguments. It also may be provided through the\n+ // environment to faciliate use through GitHub's CI system.\n+ token := os.Getenv(\"GITHUB_TOKEN\")\nif len(tokenFile) != 0 {\nbytes, err := ioutil.ReadFile(tokenFile)\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run issue_reviver via GitHub.
PiperOrigin-RevId: 311600872 |
259,885 | 14.05.2020 20:08:25 | 25,200 | fb7e5f1676ad9e6e7e83312e09fe55f91ade41bc | Make utimes_test pass on VFS2. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -869,8 +869,8 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, stat *lin\nSize: stat.Mask&linux.STATX_SIZE != 0,\nATime: stat.Mask&linux.STATX_ATIME != 0,\nMTime: stat.Mask&linux.STATX_MTIME != 0,\n- ATimeNotSystemTime: stat.Atime.Nsec != linux.UTIME_NOW,\n- MTimeNotSystemTime: stat.Mtime.Nsec != linux.UTIME_NOW,\n+ ATimeNotSystemTime: stat.Mask&linux.STATX_ATIME != 0 && stat.Atime.Nsec != linux.UTIME_NOW,\n+ MTimeNotSystemTime: stat.Mask&linux.STATX_MTIME != 0 && stat.Mtime.Nsec != linux.UTIME_NOW,\n}, p9.SetAttr{\nPermissions: p9.FileMode(stat.Mode),\nUID: p9.UID(stat.UID),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/setstat.go",
"diff": "@@ -246,19 +246,57 @@ func Utimes(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nreturn 0, nil, err\n}\n- opts := vfs.SetStatOptions{\n- Stat: linux.Statx{\n- Mask: linux.STATX_ATIME | linux.STATX_MTIME,\n- },\n+ var opts vfs.SetStatOptions\n+ if err := populateSetStatOptionsForUtimes(t, timesAddr, &opts); err != nil {\n+ return 0, nil, err\n+ }\n+\n+ return 0, nil, setstatat(t, linux.AT_FDCWD, path, disallowEmptyPath, followFinalSymlink, &opts)\n+}\n+\n+// Futimesat implements Linux syscall futimesat(2).\n+func Futimesat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ dirfd := args[0].Int()\n+ pathAddr := args[1].Pointer()\n+ timesAddr := args[2].Pointer()\n+\n+ // \"If filename is NULL and dfd refers to an open file, then operate on the\n+ // file. Otherwise look up filename, possibly using dfd as a starting\n+ // point.\" - fs/utimes.c\n+ var path fspath.Path\n+ shouldAllowEmptyPath := allowEmptyPath\n+ if dirfd == linux.AT_FDCWD || pathAddr != 0 {\n+ var err error\n+ path, err = copyInPath(t, pathAddr)\n+ if err != nil {\n+ return 0, nil, err\n}\n+ shouldAllowEmptyPath = disallowEmptyPath\n+ }\n+\n+ var opts vfs.SetStatOptions\n+ if err := populateSetStatOptionsForUtimes(t, timesAddr, &opts); err != nil {\n+ return 0, nil, err\n+ }\n+\n+ return 0, nil, setstatat(t, dirfd, path, shouldAllowEmptyPath, followFinalSymlink, &opts)\n+}\n+\n+func populateSetStatOptionsForUtimes(t *kernel.Task, timesAddr usermem.Addr, opts *vfs.SetStatOptions) error {\nif timesAddr == 0 {\n+ opts.Stat.Mask = linux.STATX_ATIME | linux.STATX_MTIME\nopts.Stat.Atime.Nsec = linux.UTIME_NOW\nopts.Stat.Mtime.Nsec = linux.UTIME_NOW\n- } else {\n+ return nil\n+ }\nvar times [2]linux.Timeval\nif _, err := t.CopyIn(timesAddr, ×); err != nil {\n- return 0, nil, err\n+ return err\n+ }\n+ if times[0].Usec < 0 || times[0].Usec > 999999 || times[1].Usec < 0 || times[1].Usec > 999999 {\n+ return syserror.EINVAL\n}\n+ opts.Stat.Mask = linux.STATX_ATIME | linux.STATX_MTIME\nopts.Stat.Atime = linux.StatxTimestamp{\nSec: times[0].Sec,\nNsec: uint32(times[0].Usec * 1000),\n@@ -267,9 +305,7 @@ func Utimes(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nSec: times[1].Sec,\nNsec: uint32(times[1].Usec * 1000),\n}\n- }\n-\n- return 0, nil, setstatat(t, linux.AT_FDCWD, path, disallowEmptyPath, followFinalSymlink, &opts)\n+ return nil\n}\n// Utimensat implements Linux syscall utimensat(2).\n@@ -279,40 +315,35 @@ func Utimensat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sys\ntimesAddr := args[2].Pointer()\nflags := args[3].Int()\n- if flags&^linux.AT_SYMLINK_NOFOLLOW != 0 {\n- return 0, nil, syserror.EINVAL\n- }\n-\n- path, err := copyInPath(t, pathAddr)\n- if err != nil {\n- return 0, nil, err\n- }\n-\n+ // Linux requires that the UTIME_OMIT check occur before checking path or\n+ // flags.\nvar opts vfs.SetStatOptions\nif err := populateSetStatOptionsForUtimens(t, timesAddr, &opts); err != nil {\nreturn 0, nil, err\n}\n-\n- return 0, nil, setstatat(t, dirfd, path, disallowEmptyPath, followFinalSymlink, &opts)\n+ if opts.Stat.Mask == 0 {\n+ return 0, nil, nil\n}\n-// Futimens implements Linux syscall futimens(2).\n-func Futimens(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- fd := args[0].Int()\n- timesAddr := args[1].Pointer()\n-\n- file := t.GetFileVFS2(fd)\n- if file == nil {\n- return 0, nil, syserror.EBADF\n+ if flags&^linux.AT_SYMLINK_NOFOLLOW != 0 {\n+ return 0, nil, syserror.EINVAL\n}\n- defer file.DecRef()\n- var opts vfs.SetStatOptions\n- if err := populateSetStatOptionsForUtimens(t, timesAddr, &opts); err != nil {\n+ // \"If filename is NULL and dfd refers to an open file, then operate on the\n+ // file. Otherwise look up filename, possibly using dfd as a starting\n+ // point.\" - fs/utimes.c\n+ var path fspath.Path\n+ shouldAllowEmptyPath := allowEmptyPath\n+ if dirfd == linux.AT_FDCWD || pathAddr != 0 {\n+ var err error\n+ path, err = copyInPath(t, pathAddr)\n+ if err != nil {\nreturn 0, nil, err\n}\n+ shouldAllowEmptyPath = disallowEmptyPath\n+ }\n- return 0, nil, file.SetStat(t, opts)\n+ return 0, nil, setstatat(t, dirfd, path, shouldAllowEmptyPath, shouldFollowFinalSymlink(flags&linux.AT_SYMLINK_NOFOLLOW == 0), &opts)\n}\nfunc populateSetStatOptionsForUtimens(t *kernel.Task, timesAddr usermem.Addr, opts *vfs.SetStatOptions) error {\n@@ -327,6 +358,9 @@ func populateSetStatOptionsForUtimens(t *kernel.Task, timesAddr usermem.Addr, op\nreturn err\n}\nif times[0].Nsec != linux.UTIME_OMIT {\n+ if times[0].Nsec != linux.UTIME_NOW && (times[0].Nsec < 0 || times[0].Nsec > 999999999) {\n+ return syserror.EINVAL\n+ }\nopts.Stat.Mask |= linux.STATX_ATIME\nopts.Stat.Atime = linux.StatxTimestamp{\nSec: times[0].Sec,\n@@ -334,6 +368,9 @@ func populateSetStatOptionsForUtimens(t *kernel.Task, timesAddr usermem.Addr, op\n}\n}\nif times[1].Nsec != linux.UTIME_OMIT {\n+ if times[1].Nsec != linux.UTIME_NOW && (times[1].Nsec < 0 || times[1].Nsec > 999999999) {\n+ return syserror.EINVAL\n+ }\nopts.Stat.Mask |= linux.STATX_MTIME\nopts.Stat.Mtime = linux.StatxTimestamp{\nSec: times[1].Sec,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"new_path": "pkg/sentry/syscalls/linux/vfs2/vfs2.go",
"diff": "@@ -123,7 +123,7 @@ func Override() {\ns.Table[258] = syscalls.Supported(\"mkdirat\", Mkdirat)\ns.Table[259] = syscalls.Supported(\"mknodat\", Mknodat)\ns.Table[260] = syscalls.Supported(\"fchownat\", Fchownat)\n- s.Table[261] = syscalls.Supported(\"futimens\", Futimens)\n+ s.Table[261] = syscalls.Supported(\"futimesat\", Futimesat)\ns.Table[262] = syscalls.Supported(\"newfstatat\", Newfstatat)\ns.Table[263] = syscalls.Supported(\"unlinkat\", Unlinkat)\ns.Table[264] = syscalls.Supported(\"renameat\", Renameat)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/utimes.cc",
"new_path": "test/syscalls/linux/utimes.cc",
"diff": "@@ -48,12 +48,15 @@ void TimeBoxed(absl::Time* before, absl::Time* after,\n// filesystems set it to 1, so we don't do any truncation.\nstruct timespec ts;\nEXPECT_THAT(clock_gettime(CLOCK_REALTIME_COARSE, &ts), SyscallSucceeds());\n- *before = absl::TimeFromTimespec(ts);\n+ // FIXME(b/132819225): gVisor filesystem timestamps inconsistently use the\n+ // internal or host clock, which may diverge slightly. Allow some slack on\n+ // times to account for the difference.\n+ *before = absl::TimeFromTimespec(ts) - absl::Seconds(1);\nfn();\nEXPECT_THAT(clock_gettime(CLOCK_REALTIME_COARSE, &ts), SyscallSucceeds());\n- *after = absl::TimeFromTimespec(ts);\n+ *after = absl::TimeFromTimespec(ts) + absl::Seconds(1);\nif (*after < *before) {\n// Clock jumped backwards; retry.\n@@ -68,11 +71,11 @@ void TimeBoxed(absl::Time* before, absl::Time* after,\nvoid TestUtimesOnPath(std::string const& path) {\nstruct stat statbuf;\n- struct timeval times[2] = {{1, 0}, {2, 0}};\n+ struct timeval times[2] = {{10, 0}, {20, 0}};\nEXPECT_THAT(utimes(path.c_str(), times), SyscallSucceeds());\nEXPECT_THAT(stat(path.c_str(), &statbuf), SyscallSucceeds());\n- EXPECT_EQ(1, statbuf.st_atime);\n- EXPECT_EQ(2, statbuf.st_mtime);\n+ EXPECT_EQ(10, statbuf.st_atime);\n+ EXPECT_EQ(20, statbuf.st_mtime);\nabsl::Time before;\nabsl::Time after;\n@@ -103,18 +106,18 @@ TEST(UtimesTest, OnDir) {\nTEST(UtimesTest, MissingPath) {\nauto path = NewTempAbsPath();\n- struct timeval times[2] = {{1, 0}, {2, 0}};\n+ struct timeval times[2] = {{10, 0}, {20, 0}};\nEXPECT_THAT(utimes(path.c_str(), times), SyscallFailsWithErrno(ENOENT));\n}\nvoid TestFutimesat(int dirFd, std::string const& path) {\nstruct stat statbuf;\n- struct timeval times[2] = {{1, 0}, {2, 0}};\n+ struct timeval times[2] = {{10, 0}, {20, 0}};\nEXPECT_THAT(futimesat(dirFd, path.c_str(), times), SyscallSucceeds());\nEXPECT_THAT(fstatat(dirFd, path.c_str(), &statbuf, 0), SyscallSucceeds());\n- EXPECT_EQ(1, statbuf.st_atime);\n- EXPECT_EQ(2, statbuf.st_mtime);\n+ EXPECT_EQ(10, statbuf.st_atime);\n+ EXPECT_EQ(20, statbuf.st_mtime);\nabsl::Time before;\nabsl::Time after;\n@@ -175,11 +178,11 @@ TEST(FutimesatTest, InvalidNsec) {\nvoid TestUtimensat(int dirFd, std::string const& path) {\nstruct stat statbuf;\n- const struct timespec times[2] = {{1, 0}, {2, 0}};\n+ const struct timespec times[2] = {{10, 0}, {20, 0}};\nEXPECT_THAT(utimensat(dirFd, path.c_str(), times, 0), SyscallSucceeds());\nEXPECT_THAT(fstatat(dirFd, path.c_str(), &statbuf, 0), SyscallSucceeds());\n- EXPECT_EQ(1, statbuf.st_atime);\n- EXPECT_EQ(2, statbuf.st_mtime);\n+ EXPECT_EQ(10, statbuf.st_atime);\n+ EXPECT_EQ(20, statbuf.st_mtime);\n// Test setting with UTIME_NOW and UTIME_OMIT.\nstruct stat statbuf2;\n@@ -301,13 +304,13 @@ TEST(Utimensat, NullPath) {\nauto f = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\nconst FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(f.path(), O_RDWR));\nstruct stat statbuf;\n- const struct timespec times[2] = {{1, 0}, {2, 0}};\n+ const struct timespec times[2] = {{10, 0}, {20, 0}};\n// Call syscall directly.\nEXPECT_THAT(syscall(SYS_utimensat, fd.get(), NULL, times, 0),\nSyscallSucceeds());\nEXPECT_THAT(fstatat(0, f.path().c_str(), &statbuf, 0), SyscallSucceeds());\n- EXPECT_EQ(1, statbuf.st_atime);\n- EXPECT_EQ(2, statbuf.st_mtime);\n+ EXPECT_EQ(10, statbuf.st_atime);\n+ EXPECT_EQ(20, statbuf.st_mtime);\n}\n} // namespace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make utimes_test pass on VFS2.
PiperOrigin-RevId: 311657502 |
259,858 | 14.05.2020 20:21:03 | 25,200 | 4502b73d008e7696adbf035926092590f2077706 | Update Kokoro images to include newer gcloud. | [
{
"change_type": "MODIFY",
"old_path": "tools/vm/build.sh",
"new_path": "tools/vm/build.sh",
"diff": "@@ -64,7 +64,7 @@ function cleanup {\ntrap cleanup EXIT\n# Wait for the instance to become available (up to 5 minutes).\n-echo -n \"Waiting for ${INSTANCE_NAME}\"\n+echo -n \"Waiting for ${INSTANCE_NAME}\" >&2\ndeclare timeout=300\ndeclare success=0\ndeclare internal=\"\"\n@@ -81,10 +81,10 @@ while [[ \"$(date +%s)\" -lt \"${end}\" ]] && [[ \"${success}\" -lt 3 ]]; do\ndone\nif [[ \"${success}\" -eq \"0\" ]]; then\n- echo \"connect timed out after ${timeout} seconds.\"\n+ echo \"connect timed out after ${timeout} seconds.\" >&2\nexit 1\nelse\n- echo \"done.\"\n+ echo \"done.\" >&2\nfi\n# Run the install scripts provided.\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/vm/ubuntu1604/10_core.sh",
"new_path": "tools/vm/ubuntu1604/10_core.sh",
"diff": "@@ -40,4 +40,4 @@ if ! [[ -d /usr/local/go ]]; then\nfi\n# Link the Go binary from /usr/bin; replacing anything there.\n-(cd /usr/bin && rm -f go && sudo ln -fs /usr/local/go/bin/go go)\n+(cd /usr/bin && rm -f go && ln -fs /usr/local/go/bin/go go)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/vm/ubuntu1604/15_gcloud.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+set -xeo pipefail\n+\n+# Install all essential build tools.\n+while true; do\n+ if (apt-get update && apt-get install -y \\\n+ apt-transport-https \\\n+ ca-certificates \\\n+ gnupg); then\n+ break\n+ fi\n+ result=$?\n+ if [[ $result -ne 100 ]]; then\n+ exit $result\n+ fi\n+done\n+\n+# Add gcloud repositories.\n+echo \"deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main\" | \\\n+ tee -a /etc/apt/sources.list.d/google-cloud-sdk.list\n+\n+# Add the appropriate key.\n+curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | \\\n+ apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -\n+\n+# Install the gcloud SDK.\n+while true; do\n+ if (apt-get update && apt-get install -y google-cloud-sdk); then\n+ break\n+ fi\n+ result=$?\n+ if [[ $result -ne 100 ]]; then\n+ exit $result\n+ fi\n+done\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update Kokoro images to include newer gcloud.
PiperOrigin-RevId: 311658774 |
259,858 | 15.05.2020 09:29:52 | 25,200 | 1847165a8c034e82cb35a0dc23878921cab30b5d | Minor text updates and jquery ordering. | [
{
"change_type": "MODIFY",
"old_path": "g3doc/architecture_guide/README.md",
"new_path": "g3doc/architecture_guide/README.md",
"diff": "@@ -71,6 +71,9 @@ race detector. (The use of Go has its challenges too, and isn't free.)\n<a name=\"gofer\"></a> <!-- For deep linking. -->\n+Gofers mediate file system interactions, and are used to provide additional\n+isolation. For more details, see the [Platform Guide](./platforms.md).\n+\n[apparmor]: https://wiki.ubuntu.com/AppArmor\n[golang]: https://golang.org\n[kvm]: https://www.linux-kvm.org\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/quick_start/docker.md",
"new_path": "g3doc/user_guide/quick_start/docker.md",
"diff": "-# Docker\n+# Docker Quick Start\n> Note: This guide requires Docker version 17.09.0 or greater. Refer to the\n> [Docker documentation][docker] for how to install it.\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/quick_start/kubernetes.md",
"new_path": "g3doc/user_guide/quick_start/kubernetes.md",
"diff": "-# Kubernetes\n+# Kubernetes Quick Start\ngVisor can be used to run Kubernetes pods and has several integration points\nwith Kubernetes.\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/quick_start/oci.md",
"new_path": "g3doc/user_guide/quick_start/oci.md",
"diff": "-# OCI\n+# OCI Quick Start\nThis guide will quickly get you started running your first gVisor sandbox\ncontainer using the runtime directly with the default platform.\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_includes/footer.html",
"new_path": "website/_includes/footer.html",
"diff": "{% include footer-links.html %}\n</footer>\n+<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\" integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.1/js/all.min.js\" integrity=\"sha256-Z1Nvg/+y2+vRFhFgFij7Lv0r77yG3hOvWz2wI0SfTa0=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha256-U5ZEeKfGNOja007MMD3YBI0A3OSZOQbeG6z2f2Y0hu8=\" crossorigin=\"anonymous\"></script>\n-<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\" integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\" crossorigin=\"anonymous\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js\" integrity=\"sha256-hYXbQJK4qdJiAeDVjjQ9G0D6A0xLnDQ4eJI9dkm7Fpk=\" crossorigin=\"anonymous\"></script>\n{% if site.analytics %}\n"
},
{
"change_type": "MODIFY",
"old_path": "website/_layouts/docs.html",
"new_path": "website/_layouts/docs.html",
"diff": "@@ -47,7 +47,7 @@ categories:\n<h1>{{ page.title }}</h1>\n{% if page.editpath %}\n<p>\n- <a href=\"https://github.com/google/gvisor/edit/master/content/{{page.editpath}}\" target=\"_blank\"><i class=\"fa fa-edit fa-fw\"></i> Edit this page</a>\n+ <a href=\"https://github.com/google/gvisor/edit/master/{{page.editpath}}\" target=\"_blank\"><i class=\"fa fa-edit fa-fw\"></i> Edit this page</a>\n<a href=\"https://github.com/google/gvisor/issues/new?title={{page.title | url_encode}}\" target=\"_blank\"><i class=\"fab fa-github fa-fw\"></i> Create issue</a>\n</p>\n{% endif %}\n"
},
{
"change_type": "MODIFY",
"old_path": "website/index.md",
"new_path": "website/index.md",
"diff": "The pluggable platform architecture of gVisor allows it to run anywhere,\nenabling consistent security policies across multiple environments without\nhaving to rearchitect your infrastructure.</p>\n- <a class=\"button\" href=\"/docs/architecture_guide/platforms/\">Read More »</a>\n+ <a class=\"button\" href=\"/docs/user_guide/quick_start/docker/\">Get Started »</a>\n</div>\n</div>\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor text updates and jquery ordering.
PiperOrigin-RevId: 311744091 |
259,858 | 15.05.2020 10:08:31 | 25,200 | c5a939d76c69c440b89045768c3acd8ffc5246b4 | Update vm scripts to handle existing kbuilder user. | [
{
"change_type": "MODIFY",
"old_path": "tools/vm/build.sh",
"new_path": "tools/vm/build.sh",
"diff": "@@ -71,7 +71,7 @@ declare internal=\"\"\ndeclare -r start=$(date +%s)\ndeclare -r end=$((${start}+${timeout}))\nwhile [[ \"$(date +%s)\" -lt \"${end}\" ]] && [[ \"${success}\" -lt 3 ]]; do\n- echo -n \".\"\n+ echo -n \".\" >&2\nif gcloud compute ssh --zone \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- true 2>/dev/null; then\nsuccess=$((${success}+1))\nelif gcloud compute ssh --internal-ip --zone \"${ZONE}\" \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- true 2>/dev/null; then\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/vm/defs.bzl",
"new_path": "tools/vm/defs.bzl",
"diff": "@@ -60,7 +60,7 @@ def _vm_image_impl(ctx):\n# Run the builder to generate our output.\necho = ctx.actions.declare_file(ctx.label.name)\nresolved_inputs, argv, runfiles_manifests = ctx.resolve_command(\n- command = \"echo -ne \\\"#!/bin/bash\\\\necho $(%s)\\\\n\\\" > %s && chmod 0755 %s\" % (\n+ command = \"echo -ne \\\"#!/bin/bash\\\\nset -e\\\\nimage=$(%s)\\\\necho ${image}\\\\n\\\" > %s && chmod 0755 %s\" % (\nctx.files.builder[0].path,\necho.path,\necho.path,\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/vm/ubuntu1604/40_kokoro.sh",
"new_path": "tools/vm/ubuntu1604/40_kokoro.sh",
"diff": "@@ -43,14 +43,14 @@ done\n# junitparser is used to merge junit xml files.\npip install junitparser\n-# We need a kbuilder user.\n-if useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder; then\n- # User was added successfully; we add the relevant SSH keys here.\n+# We need a kbuilder user, which may already exist.\n+useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder || true\n+\n+# We need to provision appropriate keys.\nmkdir -p ~kbuilder/.ssh\n(IFS=$'\\n'; echo \"${ssh_public_keys[*]}\") > ~kbuilder/.ssh/authorized_keys\nchmod 0600 ~kbuilder/.ssh/authorized_keys\nchown -R kbuilder ~kbuilder/.ssh\n-fi\n# Give passwordless sudo access.\ncat > /etc/sudoers.d/kokoro <<EOF\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update vm scripts to handle existing kbuilder user.
PiperOrigin-RevId: 311751972 |
259,962 | 15.05.2020 15:04:33 | 25,200 | 679fd2527bdcaf2ca4dd05dad48a75ffc9400973 | Remove debug log left behind by mistake. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"new_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"diff": "@@ -16,7 +16,6 @@ package linux\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -26,7 +25,6 @@ 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- log.Infof(\"NLAC: doSplice opts: %+v\", opts)\nif opts.Length < 0 || opts.SrcStart < 0 || opts.DstStart < 0 || (opts.SrcStart+opts.Length < 0) {\nreturn 0, syserror.EINVAL\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove debug log left behind by mistake.
PiperOrigin-RevId: 311808460 |
259,858 | 18.05.2020 09:48:13 | 25,200 | c27e334f260f6d1b2a380c8f105028a8140b7acd | Fix typo a => an.
Always happens. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "## What is gVisor?\n-**gVisor** is a application kernel, written in Go, that implements a substantial\n-portion of the Linux system surface. It includes an\n+**gVisor** is an application kernel, written in Go, that implements a\n+substantial portion of the Linux system surface. It includes an\n[Open Container Initiative (OCI)][oci] runtime called `runsc` that provides an\nisolation boundary between the application and the host kernel. The `runsc`\nruntime integrates with Docker and Kubernetes, making it simple to run sandboxed\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix typo a => an.
Always happens.
PiperOrigin-RevId: 312097591 |
259,992 | 18.05.2020 10:21:43 | 25,200 | 32ab382c80306d7dab499e983af2bfaea7770d1d | Improve unsupported syscall message | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat.go",
"new_path": "runsc/boot/compat.go",
"diff": "@@ -119,7 +119,13 @@ func (c *compatEmitter) emitUnimplementedSyscall(us *spb.UnimplementedSyscall) {\n}\nif tr.shouldReport(regs) {\n- c.sink.Infof(\"Unsupported syscall: %s, regs: %+v\", c.nameMap.Name(uintptr(sysnr)), regs)\n+ name := c.nameMap.Name(uintptr(sysnr))\n+ c.sink.Infof(\"Unsupported syscall %s(%#x,%#x,%#x,%#x,%#x,%#x). It is \"+\n+ \"likely that you can safely ignore this message and that this is not \"+\n+ \"the cause of any error. Please, refer to %s/%s for more information.\",\n+ name, argVal(0, regs), argVal(1, regs), argVal(2, regs), argVal(3, regs),\n+ argVal(4, regs), argVal(5, regs), syscallLink, name)\n+\ntr.onReported(regs)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat_amd64.go",
"new_path": "runsc/boot/compat_amd64.go",
"diff": "@@ -24,8 +24,12 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/strace\"\n)\n-// reportLimit is the max number of events that should be reported per tracker.\n-const reportLimit = 100\n+const (\n+ // reportLimit is the max number of events that should be reported per\n+ // tracker.\n+ reportLimit = 100\n+ syscallLink = \"https://gvisor.dev/c/linux/amd64\"\n+)\n// newRegs create a empty Registers instance.\nfunc newRegs() *rpb.Registers {\n@@ -36,22 +40,22 @@ func newRegs() *rpb.Registers {\n}\n}\n-func argVal(argIdx int, regs *rpb.Registers) uint32 {\n+func argVal(argIdx int, regs *rpb.Registers) uint64 {\namd64Regs := regs.GetArch().(*rpb.Registers_Amd64).Amd64\nswitch argIdx {\ncase 0:\n- return uint32(amd64Regs.Rdi)\n+ return amd64Regs.Rdi\ncase 1:\n- return uint32(amd64Regs.Rsi)\n+ return amd64Regs.Rsi\ncase 2:\n- return uint32(amd64Regs.Rdx)\n+ return amd64Regs.Rdx\ncase 3:\n- return uint32(amd64Regs.R10)\n+ return amd64Regs.R10\ncase 4:\n- return uint32(amd64Regs.R8)\n+ return amd64Regs.R8\ncase 5:\n- return uint32(amd64Regs.R9)\n+ return amd64Regs.R9\n}\npanic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/compat_arm64.go",
"new_path": "runsc/boot/compat_arm64.go",
"diff": "@@ -23,8 +23,12 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/strace\"\n)\n-// reportLimit is the max number of events that should be reported per tracker.\n-const reportLimit = 100\n+const (\n+ // reportLimit is the max number of events that should be reported per\n+ // tracker.\n+ reportLimit = 100\n+ syscallLink = \"https://gvisor.dev/c/linux/arm64\"\n+)\n// newRegs create a empty Registers instance.\nfunc newRegs() *rpb.Registers {\n@@ -35,22 +39,22 @@ func newRegs() *rpb.Registers {\n}\n}\n-func argVal(argIdx int, regs *rpb.Registers) uint32 {\n+func argVal(argIdx int, regs *rpb.Registers) uint64 {\narm64Regs := regs.GetArch().(*rpb.Registers_Arm64).Arm64\nswitch argIdx {\ncase 0:\n- return uint32(arm64Regs.R0)\n+ return arm64Regs.R0\ncase 1:\n- return uint32(arm64Regs.R1)\n+ return arm64Regs.R1\ncase 2:\n- return uint32(arm64Regs.R2)\n+ return arm64Regs.R2\ncase 3:\n- return uint32(arm64Regs.R3)\n+ return arm64Regs.R3\ncase 4:\n- return uint32(arm64Regs.R4)\n+ return arm64Regs.R4\ncase 5:\n- return uint32(arm64Regs.R5)\n+ return arm64Regs.R5\n}\npanic(fmt.Sprintf(\"invalid syscall argument index %d\", argIdx))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1760,7 +1760,7 @@ func TestUserLog(t *testing.T) {\nif err != nil {\nt.Fatalf(\"error opening user log file %q: %v\", userLog, err)\n}\n- if want := \"Unsupported syscall: sched_rr_get_interval\"; !strings.Contains(string(out), want) {\n+ if want := \"Unsupported syscall sched_rr_get_interval(\"; !strings.Contains(string(out), want) {\nt.Errorf(\"user log file doesn't contain %q, out: %s\", want, string(out))\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve unsupported syscall message
PiperOrigin-RevId: 312104899 |
259,898 | 18.05.2020 11:30:04 | 25,200 | 99a18ec8b4cc98694b8bc61a35b360d5fca1a075 | Support TCP options for packetimpact | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/BUILD",
"new_path": "test/packetimpact/testbench/BUILD",
"diff": "@@ -39,6 +39,7 @@ go_test(\nlibrary = \":testbench\",\ndeps = [\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/header\",\n\"@com_github_mohae_deepcopy//:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers.go",
"new_path": "test/packetimpact/testbench/layers.go",
"diff": "@@ -689,6 +689,7 @@ type TCP struct {\nWindowSize *uint16\nChecksum *uint16\nUrgentPointer *uint16\n+ Options []byte\n}\nfunc (l *TCP) String() string {\n@@ -697,7 +698,7 @@ func (l *TCP) String() string {\n// ToBytes implements Layer.ToBytes.\nfunc (l *TCP) ToBytes() ([]byte, error) {\n- b := make([]byte, header.TCPMinimumSize)\n+ b := make([]byte, l.length())\nh := header.TCP(b)\nif l.SrcPort != nil {\nh.SetSourcePort(*l.SrcPort)\n@@ -727,6 +728,8 @@ func (l *TCP) ToBytes() ([]byte, error) {\nif l.UrgentPointer != nil {\nh.SetUrgentPoiner(*l.UrgentPointer)\n}\n+ copy(b[header.TCPMinimumSize:], l.Options)\n+ header.AddTCPOptionPadding(b[header.TCPMinimumSize:], len(l.Options))\nif l.Checksum != nil {\nh.SetChecksum(*l.Checksum)\nreturn h, nil\n@@ -811,6 +814,7 @@ func parseTCP(b []byte) (Layer, layerParser) {\nWindowSize: Uint16(h.WindowSize()),\nChecksum: Uint16(h.Checksum()),\nUrgentPointer: Uint16(h.UrgentPointer()),\n+ Options: b[header.TCPMinimumSize:h.DataOffset()],\n}\nreturn &tcp, parsePayload\n}\n@@ -821,7 +825,12 @@ func (l *TCP) match(other Layer) bool {\nfunc (l *TCP) length() int {\nif l.DataOffset == nil {\n- return header.TCPMinimumSize\n+ // TCP header including the options must end on a 32-bit\n+ // boundary; the user could potentially give us a slice\n+ // whose length is not a multiple of 4 bytes, so we have\n+ // to do the alignment here.\n+ optlen := (len(l.Options) + 3) & ^3\n+ return header.TCPMinimumSize + optlen\n}\nreturn int(*l.DataOffset)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/testbench/layers_test.go",
"new_path": "test/packetimpact/testbench/layers_test.go",
"diff": "package testbench\nimport (\n+ \"bytes\"\n+ \"net\"\n\"testing\"\n\"github.com/mohae/deepcopy\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\nfunc TestLayerMatch(t *testing.T) {\n@@ -393,3 +396,112 @@ func TestLayersDiff(t *testing.T) {\n}\n}\n}\n+\n+func TestTCPOptions(t *testing.T) {\n+ for _, tt := range []struct {\n+ description string\n+ wantBytes []byte\n+ wantLayers Layers\n+ }{\n+ {\n+ description: \"without payload\",\n+ wantBytes: []byte{\n+ // IPv4 Header\n+ 0x45, 0x00, 0x00, 0x2c, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06,\n+ 0xf9, 0x77, 0xc0, 0xa8, 0x00, 0x02, 0xc0, 0xa8, 0x00, 0x01,\n+ // TCP Header\n+ 0x30, 0x39, 0xd4, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n+ 0x00, 0x00, 0x60, 0x02, 0x20, 0x00, 0xf5, 0x1c, 0x00, 0x00,\n+ // WindowScale Option\n+ 0x03, 0x03, 0x02,\n+ // NOP Option\n+ 0x00,\n+ },\n+ wantLayers: []Layer{\n+ &IPv4{\n+ IHL: Uint8(20),\n+ TOS: Uint8(0),\n+ TotalLength: Uint16(44),\n+ ID: Uint16(1),\n+ Flags: Uint8(0),\n+ FragmentOffset: Uint16(0),\n+ TTL: Uint8(64),\n+ Protocol: Uint8(uint8(header.TCPProtocolNumber)),\n+ Checksum: Uint16(0xf977),\n+ SrcAddr: Address(tcpip.Address(net.ParseIP(\"192.168.0.2\").To4())),\n+ DstAddr: Address(tcpip.Address(net.ParseIP(\"192.168.0.1\").To4())),\n+ },\n+ &TCP{\n+ SrcPort: Uint16(12345),\n+ DstPort: Uint16(54321),\n+ SeqNum: Uint32(0),\n+ AckNum: Uint32(0),\n+ Flags: Uint8(header.TCPFlagSyn),\n+ WindowSize: Uint16(8192),\n+ Checksum: Uint16(0xf51c),\n+ UrgentPointer: Uint16(0),\n+ Options: []byte{3, 3, 2, 0},\n+ },\n+ &Payload{Bytes: nil},\n+ },\n+ },\n+ {\n+ description: \"with payload\",\n+ wantBytes: []byte{\n+ // IPv4 header\n+ 0x45, 0x00, 0x00, 0x37, 0x00, 0x01, 0x00, 0x00, 0x40, 0x06,\n+ 0xf9, 0x6c, 0xc0, 0xa8, 0x00, 0x02, 0xc0, 0xa8, 0x00, 0x01,\n+ // TCP header\n+ 0x30, 0x39, 0xd4, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n+ 0x00, 0x00, 0x60, 0x02, 0x20, 0x00, 0xe5, 0x21, 0x00, 0x00,\n+ // WindowScale Option\n+ 0x03, 0x03, 0x02,\n+ // NOP Option\n+ 0x00,\n+ // Payload: \"Sample Data\"\n+ 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x44, 0x61, 0x74, 0x61,\n+ },\n+ wantLayers: []Layer{\n+ &IPv4{\n+ IHL: Uint8(20),\n+ TOS: Uint8(0),\n+ TotalLength: Uint16(55),\n+ ID: Uint16(1),\n+ Flags: Uint8(0),\n+ FragmentOffset: Uint16(0),\n+ TTL: Uint8(64),\n+ Protocol: Uint8(uint8(header.TCPProtocolNumber)),\n+ Checksum: Uint16(0xf96c),\n+ SrcAddr: Address(tcpip.Address(net.ParseIP(\"192.168.0.2\").To4())),\n+ DstAddr: Address(tcpip.Address(net.ParseIP(\"192.168.0.1\").To4())),\n+ },\n+ &TCP{\n+ SrcPort: Uint16(12345),\n+ DstPort: Uint16(54321),\n+ SeqNum: Uint32(0),\n+ AckNum: Uint32(0),\n+ Flags: Uint8(header.TCPFlagSyn),\n+ WindowSize: Uint16(8192),\n+ Checksum: Uint16(0xe521),\n+ UrgentPointer: Uint16(0),\n+ Options: []byte{3, 3, 2, 0},\n+ },\n+ &Payload{Bytes: []byte(\"Sample Data\")},\n+ },\n+ },\n+ } {\n+ t.Run(tt.description, func(t *testing.T) {\n+ layers := parse(parseIPv4, tt.wantBytes)\n+ if !layers.match(tt.wantLayers) {\n+ t.Fatalf(\"match failed with diff: %s\", layers.diff(tt.wantLayers))\n+ }\n+ gotBytes, err := layers.ToBytes()\n+ if err != nil {\n+ t.Fatalf(\"ToBytes() failed on %s: %s\", &layers, err)\n+ }\n+ if !bytes.Equal(tt.wantBytes, gotBytes) {\n+ t.Fatalf(\"mismatching bytes, gotBytes: %x, wantBytes: %x\", gotBytes, tt.wantBytes)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support TCP options for packetimpact
PiperOrigin-RevId: 312119730 |
259,992 | 18.05.2020 14:24:47 | 25,200 | 20e6efd302746554c485028f9fc1f2fbf88b234e | Remove IfChange/ThenChange lint from VFS2
As new functionality is added to VFS2, corresponding files in VFS1
don't need to be changed. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/line_discipline.go",
"new_path": "pkg/sentry/fsimpl/devpts/line_discipline.go",
"diff": "@@ -27,8 +27,6 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// LINT.IfChange\n-\nconst (\n// canonMaxBytes is the number of bytes that fit into a single line of\n// terminal input in canonical mode. This corresponds to N_TTY_BUF_SIZE\n@@ -445,5 +443,3 @@ func (l *lineDiscipline) peek(b []byte) int {\n}\nreturn size\n}\n-\n-// LINT.ThenChange(../../fs/tty/line_discipline.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/master.go",
"new_path": "pkg/sentry/fsimpl/devpts/master.go",
"diff": "@@ -27,8 +27,6 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// LINT.IfChange\n-\n// masterInode is the inode for the master end of the Terminal.\ntype masterInode struct {\nkernfs.InodeAttrs\n@@ -222,5 +220,3 @@ func maybeEmitUnimplementedEvent(ctx context.Context, cmd uint32) {\nunimpl.EmitUnimplementedEvent(ctx)\n}\n}\n-\n-// LINT.ThenChange(../../fs/tty/master.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/queue.go",
"new_path": "pkg/sentry/fsimpl/devpts/queue.go",
"diff": "@@ -25,8 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// LINT.IfChange\n-\n// waitBufMaxBytes is the maximum size of a wait buffer. It is based on\n// TTYB_DEFAULT_MEM_LIMIT.\nconst waitBufMaxBytes = 131072\n@@ -236,5 +234,3 @@ func (q *queue) waitBufAppend(b []byte) {\nq.waitBuf = append(q.waitBuf, b)\nq.waitBufLen += uint64(len(b))\n}\n-\n-// LINT.ThenChange(../../fs/tty/queue.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/slave.go",
"new_path": "pkg/sentry/fsimpl/devpts/slave.go",
"diff": "@@ -26,8 +26,6 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n-// LINT.IfChange\n-\n// slaveInode is the inode for the slave end of the Terminal.\ntype slaveInode struct {\nkernfs.InodeAttrs\n@@ -182,5 +180,3 @@ func (sfd *slaveFileDescription) Stat(ctx context.Context, opts vfs.StatOptions)\nfs := sfd.vfsfd.VirtualDentry().Mount().Filesystem()\nreturn sfd.inode.Stat(fs, opts)\n}\n-\n-// LINT.ThenChange(../../fs/tty/slave.go)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/devpts/terminal.go",
"new_path": "pkg/sentry/fsimpl/devpts/terminal.go",
"diff": "@@ -22,8 +22,6 @@ import (\n\"gvisor.dev/gvisor/pkg/usermem\"\n)\n-// LINT.IfChanges\n-\n// Terminal is a pseudoterminal.\n//\n// +stateify savable\n@@ -120,5 +118,3 @@ func (tm *Terminal) tty(isMaster bool) *kernel.TTY {\n}\nreturn tm.slaveKTTY\n}\n-\n-// LINT.ThenChange(../../fs/tty/terminal.go)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove IfChange/ThenChange lint from VFS2
As new functionality is added to VFS2, corresponding files in VFS1
don't need to be changed.
PiperOrigin-RevId: 312153799 |
259,858 | 18.05.2020 14:34:49 | 25,200 | cbfb55869e4d00ddd1ede096ba01adf2713e08b1 | Implement Go branch updater with GitHub actions. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/go.yml",
"diff": "+name: \"Go\"\n+on:\n+ push:\n+ branches:\n+ - master\n+ pull_request:\n+ branches:\n+ - master\n+\n+jobs:\n+ generate:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - run: |\n+ jq -nc '{\"state\": \"pending\", \"context\": \"go tests\"}' | \\\n+ curl -sL -X POST -d @- \\\n+ -H \"Content-Type: application/json\" \\\n+ -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n+ \"${{ github.event.pull_request.statuses_url }}\"\n+ - uses: actions/checkout@v2\n+ with:\n+ fetch-depth: 0\n+ - uses: actions/setup-go@v2\n+ with:\n+ go-version: 1.14\n+ - uses: actions/cache@v1\n+ with:\n+ path: ~/go/pkg/mod\n+ key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}\n+ restore-keys: |\n+ ${{ runner.os }}-go-\n+ - uses: actions/cache@v1\n+ with:\n+ path: ~/.cache/bazel\n+ key: ${{ runner.os }}-bazel-${{ hashFiles('WORKSPACE') }}\n+ restore-keys: |\n+ ${{ runner.os }}-bazel-\n+ - run: make build TARGETS=\"//:gopath\"\n+ - run: tools/go_branch.sh\n+ - run: git checkout go && git clean -f\n+ - run: go build ./...\n+ - if: github.event_name == 'push'\n+ run: |\n+ # Required dedicated credentials for the Go branch, due to the way\n+ # branch protection rules are configured.\n+ git config --global credential.helper cache\n+ echo -e \"protocol=https\\nhost=github.com\\nusername=${{ secrets.GO_TOKEN }}\\npassword=x-oauth-basic\" | git credential approve\n+ git remote add upstream \"https://github.com/${{ github.repository }}\"\n+ git push upstream go:go\n+ - if: ${{ success() }}\n+ run: |\n+ jq -nc '{\"state\": \"success\", \"context\": \"go tests\"}' | \\\n+ curl -sL -X POST -d @- \\\n+ -H \"Content-Type: application/json\" \\\n+ -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n+ \"${{ github.event.pull_request.statuses_url }}\"\n+ - if: ${{ failure() }}\n+ run: |\n+ jq -nc '{\"state\": \"failure\", \"context\": \"go tests\"}' | \\\n+ curl -sL -X POST -d @- \\\n+ -H \"Content-Type: application/json\" \\\n+ -H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n+ \"${{ github.event.pull_request.statuses_url }}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_branch.sh",
"new_path": "tools/go_branch.sh",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n-set -eo pipefail\n+set -xeo pipefail\n# Discovery the package name from the go.mod file.\ndeclare -r module=$(cat go.mod | grep -E \"^module\" | cut -d' ' -f2)\n@@ -42,7 +42,8 @@ declare -r head=$(git describe --always)\n# We expect to have an existing go branch that we will use as the basis for\n# this commit. That branch may be empty, but it must exist.\n-declare -r go_branch=$(git show-ref --hash origin/go)\n+git fetch --all\n+declare -r go_branch=$(git show-ref --hash go)\n# Clone the current repository to the temporary directory, and check out the\n# current go_branch directory. We move to the new repository for convenience.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement Go branch updater with GitHub actions.
PiperOrigin-RevId: 312155686 |
259,858 | 18.05.2020 14:51:53 | 25,200 | f2f2dec7280e37696550185f291d51cf9e47e281 | Add simplified badge and Build workflow. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/build.yml",
"diff": "+name: \"Build\"\n+on:\n+ push:\n+ branches:\n+ - master\n+ pull_request:\n+ branches:\n+ - master\n+\n+jobs:\n+ default:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: actions/checkout@v2\n+ - uses: actions/cache@v1\n+ with:\n+ path: ~/.cache/bazel\n+ key: ${{ runner.os }}-bazel-${{ hashFiles('WORKSPACE') }}\n+ restore-keys: |\n+ ${{ runner.os }}-bazel-\n+ - run: make\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "\n-[](https://storage.googleapis.com/gvisor-build-badges/build.html)\n-[](https://gitter.im/gvisor/community)\n+\n## What is gVisor?\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add simplified badge and Build workflow.
PiperOrigin-RevId: 312159017 |
259,860 | 19.05.2020 13:45:23 | 25,200 | 05c89af6edde6158844d4debfe68bc598fec4418 | Implement mmap for host fs in vfs2.
In VFS1, both fs/host and fs/gofer used the same utils for host file mappings.
Refactor parts of fsimpl/gofer to create similar utils to share with
fsimpl/host (memory accounting code moved to fsutil, page rounding arithmetic
moved to usermem).
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/frame_ref_set.go",
"new_path": "pkg/sentry/fs/fsutil/frame_ref_set.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"math\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usage\"\n)\n// FrameRefSetFunctions implements segment.Functions for FrameRefSet.\n@@ -49,3 +50,42 @@ func (FrameRefSetFunctions) Merge(_ platform.FileRange, val1 uint64, _ platform.\nfunc (FrameRefSetFunctions) Split(_ platform.FileRange, val uint64, _ uint64) (uint64, uint64) {\nreturn val, val\n}\n+\n+// IncRefAndAccount adds a reference on the range fr. All newly inserted segments\n+// are accounted as host page cache memory mappings.\n+func (refs *FrameRefSet) IncRefAndAccount(fr platform.FileRange) {\n+ seg, gap := refs.Find(fr.Start)\n+ for {\n+ switch {\n+ case seg.Ok() && seg.Start() < fr.End:\n+ seg = refs.Isolate(seg, fr)\n+ seg.SetValue(seg.Value() + 1)\n+ seg, gap = seg.NextNonEmpty()\n+ case gap.Ok() && gap.Start() < fr.End:\n+ newRange := gap.Range().Intersect(fr)\n+ usage.MemoryAccounting.Inc(newRange.Length(), usage.Mapped)\n+ seg, gap = refs.InsertWithoutMerging(gap, newRange, 1).NextNonEmpty()\n+ default:\n+ refs.MergeAdjacent(fr)\n+ return\n+ }\n+ }\n+}\n+\n+// DecRefAndAccount removes a reference on the range fr and untracks segments\n+// that are removed from memory accounting.\n+func (refs *FrameRefSet) DecRefAndAccount(fr platform.FileRange) {\n+ seg := refs.FindSegment(fr.Start)\n+\n+ for seg.Ok() && seg.Start() < fr.End {\n+ seg = refs.Isolate(seg, fr)\n+ if old := seg.Value(); old == 1 {\n+ usage.MemoryAccounting.Dec(seg.Range().Length(), usage.Mapped)\n+ seg = refs.Remove(seg).NextSegment()\n+ } else {\n+ seg.SetValue(old - 1)\n+ seg = seg.NextSegment()\n+ }\n+ }\n+ refs.MergeAdjacent(fr)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/BUILD",
"new_path": "pkg/sentry/fsimpl/gofer/BUILD",
"diff": "@@ -36,7 +36,6 @@ go_library(\n\"gofer.go\",\n\"handle.go\",\n\"p9file.go\",\n- \"pagemath.go\",\n\"regular_file.go\",\n\"socket.go\",\n\"special_file.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -928,8 +928,8 @@ func (d *dentry) setStat(ctx context.Context, creds *auth.Credentials, stat *lin\n// so we can't race with Write or another truncate.)\nd.dataMu.Unlock()\nif d.size < oldSize {\n- oldpgend := pageRoundUp(oldSize)\n- newpgend := pageRoundUp(d.size)\n+ oldpgend, _ := usermem.PageRoundUp(oldSize)\n+ newpgend, _ := usermem.PageRoundUp(d.size)\nif oldpgend != newpgend {\nd.mapsMu.Lock()\nd.mappings.Invalidate(memmap.MappableRange{newpgend, oldpgend}, memmap.InvalidateOpts{\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/fsimpl/gofer/pagemath.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 gofer\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/usermem\"\n-)\n-\n-// This are equivalent to usermem.Addr.RoundDown/Up, but without the\n-// potentially truncating conversion to usermem.Addr. This is necessary because\n-// there is no way to define generic \"PageRoundDown/Up\" functions in Go.\n-\n-func pageRoundDown(x uint64) uint64 {\n- return x &^ (usermem.PageSize - 1)\n-}\n-\n-func pageRoundUp(x uint64) uint64 {\n- return pageRoundDown(x + usermem.PageSize - 1)\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/regular_file.go",
"diff": "@@ -148,9 +148,9 @@ func (fd *regularFileFD) PWrite(ctx context.Context, src usermem.IOSequence, off\nreturn 0, err\n}\n// Remove touched pages from the cache.\n- pgstart := pageRoundDown(uint64(offset))\n- pgend := pageRoundUp(uint64(offset + src.NumBytes()))\n- if pgend < pgstart {\n+ pgstart := usermem.PageRoundDown(uint64(offset))\n+ pgend, ok := usermem.PageRoundUp(uint64(offset + src.NumBytes()))\n+ if !ok {\nreturn 0, syserror.EINVAL\n}\nmr := memmap.MappableRange{pgstart, pgend}\n@@ -306,9 +306,10 @@ func (rw *dentryReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error)\nif fillCache {\n// Read into the cache, then re-enter the loop to read from the\n// cache.\n+ gapEnd, _ := usermem.PageRoundUp(gapMR.End)\nreqMR := memmap.MappableRange{\n- Start: pageRoundDown(gapMR.Start),\n- End: pageRoundUp(gapMR.End),\n+ Start: usermem.PageRoundDown(gapMR.Start),\n+ End: gapEnd,\n}\noptMR := gap.Range()\nerr := rw.d.cache.Fill(rw.ctx, reqMR, maxFillRange(reqMR, optMR), mf, usage.PageCache, rw.d.handle.readToBlocksAt)\n@@ -671,7 +672,7 @@ func (d *dentry) Translate(ctx context.Context, required, optional memmap.Mappab\n// Constrain translations to d.size (rounded up) to prevent translation to\n// pages that may be concurrently truncated.\n- pgend := pageRoundUp(d.size)\n+ pgend, _ := usermem.PageRoundUp(d.size)\nvar beyondEOF bool\nif required.End > pgend {\nif required.Start >= pgend {\n@@ -818,43 +819,15 @@ type dentryPlatformFile struct {\n// IncRef implements platform.File.IncRef.\nfunc (d *dentryPlatformFile) IncRef(fr platform.FileRange) {\nd.dataMu.Lock()\n- seg, gap := d.fdRefs.Find(fr.Start)\n- for {\n- switch {\n- case seg.Ok() && seg.Start() < fr.End:\n- seg = d.fdRefs.Isolate(seg, fr)\n- seg.SetValue(seg.Value() + 1)\n- seg, gap = seg.NextNonEmpty()\n- case gap.Ok() && gap.Start() < fr.End:\n- newRange := gap.Range().Intersect(fr)\n- usage.MemoryAccounting.Inc(newRange.Length(), usage.Mapped)\n- seg, gap = d.fdRefs.InsertWithoutMerging(gap, newRange, 1).NextNonEmpty()\n- default:\n- d.fdRefs.MergeAdjacent(fr)\n+ d.fdRefs.IncRefAndAccount(fr)\nd.dataMu.Unlock()\n- return\n- }\n- }\n}\n// DecRef implements platform.File.DecRef.\nfunc (d *dentryPlatformFile) DecRef(fr platform.FileRange) {\nd.dataMu.Lock()\n- seg := d.fdRefs.FindSegment(fr.Start)\n-\n- for seg.Ok() && seg.Start() < fr.End {\n- seg = d.fdRefs.Isolate(seg, fr)\n- if old := seg.Value(); old == 1 {\n- usage.MemoryAccounting.Dec(seg.Range().Length(), usage.Mapped)\n- seg = d.fdRefs.Remove(seg).NextSegment()\n- } else {\n- seg.SetValue(old - 1)\n- seg = seg.NextSegment()\n- }\n- }\n- d.fdRefs.MergeAdjacent(fr)\n+ d.fdRefs.DecRefAndAccount(fr)\nd.dataMu.Unlock()\n-\n}\n// MapInternal implements platform.File.MapInternal.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/BUILD",
"new_path": "pkg/sentry/fsimpl/host/BUILD",
"diff": "@@ -8,6 +8,7 @@ go_library(\n\"control.go\",\n\"host.go\",\n\"ioctl_unsafe.go\",\n+ \"mmap.go\",\n\"socket.go\",\n\"socket_iovec.go\",\n\"socket_unsafe.go\",\n@@ -23,12 +24,15 @@ go_library(\n\"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/refs\",\n+ \"//pkg/safemem\",\n\"//pkg/sentry/arch\",\n+ \"//pkg/sentry/fs/fsutil\",\n\"//pkg/sentry/fsimpl/kernfs\",\n\"//pkg/sentry/hostfd\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/memmap\",\n+ \"//pkg/sentry/platform\",\n\"//pkg/sentry/socket/control\",\n\"//pkg/sentry/socket/unix\",\n\"//pkg/sentry/socket/unix/transport\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -86,15 +86,16 @@ func NewFD(ctx context.Context, mnt *vfs.Mount, hostFD int, opts *NewFDOptions)\ni := &inode{\nhostFD: hostFD,\n- seekable: seekable,\n+ ino: fs.NextIno(),\nisTTY: opts.IsTTY,\n- canMap: canMap(uint32(fileType)),\nwouldBlock: wouldBlock(uint32(fileType)),\n- ino: fs.NextIno(),\n+ seekable: seekable,\n// For simplicity, set offset to 0. Technically, we should use the existing\n// offset on the host if the file is seekable.\noffset: 0,\n+ canMap: canMap(uint32(fileType)),\n}\n+ i.pf.inode = i\n// Non-seekable files can't be memory mapped, assert this.\nif !i.seekable && i.canMap {\n@@ -189,11 +190,15 @@ type inode struct {\n// This field is initialized at creation time and is immutable.\nhostFD int\n- // wouldBlock is true if the host FD would return EWOULDBLOCK for\n- // operations that would block.\n+ // ino is an inode number unique within this filesystem.\n//\n// This field is initialized at creation time and is immutable.\n- wouldBlock bool\n+ ino uint64\n+\n+ // isTTY is true if this file represents a TTY.\n+ //\n+ // This field is initialized at creation time and is immutable.\n+ isTTY bool\n// seekable is false if the host fd points to a file representing a stream,\n// e.g. a socket or a pipe. Such files are not seekable and can return\n@@ -202,29 +207,36 @@ type inode struct {\n// This field is initialized at creation time and is immutable.\nseekable bool\n- // isTTY is true if this file represents a TTY.\n+ // offsetMu protects offset.\n+ offsetMu sync.Mutex\n+\n+ // offset specifies the current file offset. It is only meaningful when\n+ // seekable is true.\n+ offset int64\n+\n+ // wouldBlock is true if the host FD would return EWOULDBLOCK for\n+ // operations that would block.\n//\n// This field is initialized at creation time and is immutable.\n- isTTY bool\n+ wouldBlock bool\n+\n+ // Event queue for blocking operations.\n+ queue waiter.Queue\n// canMap specifies whether we allow the file to be memory mapped.\n//\n// This field is initialized at creation time and is immutable.\ncanMap bool\n- // ino is an inode number unique within this filesystem.\n- //\n- // This field is initialized at creation time and is immutable.\n- ino uint64\n-\n- // offsetMu protects offset.\n- offsetMu sync.Mutex\n+ // mapsMu protects mappings.\n+ mapsMu sync.Mutex\n- // offset specifies the current file offset.\n- offset int64\n+ // If canMap is true, mappings tracks mappings of hostFD into\n+ // memmap.MappingSpaces.\n+ mappings memmap.MappingSet\n- // Event queue for blocking operations.\n- queue waiter.Queue\n+ // pf implements platform.File for mappings of hostFD.\n+ pf inodePlatformFile\n}\n// CheckPermissions implements kernfs.Inode.\n@@ -388,6 +400,21 @@ func (i *inode) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *auth.Cre\nif err := syscall.Ftruncate(i.hostFD, int64(s.Size)); err != nil {\nreturn err\n}\n+ oldSize := uint64(hostStat.Size)\n+ if s.Size < oldSize {\n+ oldpgend, _ := usermem.PageRoundUp(oldSize)\n+ newpgend, _ := usermem.PageRoundUp(s.Size)\n+ if oldpgend != newpgend {\n+ i.mapsMu.Lock()\n+ i.mappings.Invalidate(memmap.MappableRange{newpgend, oldpgend}, memmap.InvalidateOpts{\n+ // Compare Linux's mm/truncate.c:truncate_setsize() =>\n+ // truncate_pagecache() =>\n+ // mm/memory.c:unmap_mapping_range(evencows=1).\n+ InvalidatePrivate: true,\n+ })\n+ i.mapsMu.Unlock()\n+ }\n+ }\n}\nif m&(linux.STATX_ATIME|linux.STATX_MTIME) != 0 {\nts := [2]syscall.Timespec{\n@@ -666,8 +693,9 @@ func (f *fileDescription) ConfigureMMap(_ context.Context, opts *memmap.MMapOpts\nif !f.inode.canMap {\nreturn syserror.ENODEV\n}\n- // TODO(gvisor.dev/issue/1672): Implement ConfigureMMap and Mappable interface.\n- return syserror.ENODEV\n+ i := f.inode\n+ i.pf.fileMapperInitOnce.Do(i.pf.fileMapper.Init)\n+ return vfs.GenericConfigureMMap(&f.vfsfd, i, opts)\n}\n// EventRegister implements waiter.Waitable.EventRegister.\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fsimpl/host/mmap.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 host\n+\n+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/memmap\"\n+ \"gvisor.dev/gvisor/pkg/sentry/platform\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/usermem\"\n+)\n+\n+// inodePlatformFile implements platform.File. It exists solely because inode\n+// cannot implement both kernfs.Inode.IncRef and platform.File.IncRef.\n+//\n+// inodePlatformFile should only be used if inode.canMap is true.\n+type inodePlatformFile struct {\n+ *inode\n+\n+ // fdRefsMu protects fdRefs.\n+ fdRefsMu sync.Mutex\n+\n+ // fdRefs counts references on platform.File offsets. It is used solely for\n+ // memory accounting.\n+ fdRefs fsutil.FrameRefSet\n+\n+ // fileMapper caches mappings of the host file represented by this inode.\n+ fileMapper fsutil.HostFileMapper\n+\n+ // fileMapperInitOnce is used to lazily initialize fileMapper.\n+ fileMapperInitOnce sync.Once\n+}\n+\n+// IncRef implements platform.File.IncRef.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inodePlatformFile) IncRef(fr platform.FileRange) {\n+ i.fdRefsMu.Lock()\n+ i.fdRefs.IncRefAndAccount(fr)\n+ i.fdRefsMu.Unlock()\n+}\n+\n+// DecRef implements platform.File.DecRef.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inodePlatformFile) DecRef(fr platform.FileRange) {\n+ i.fdRefsMu.Lock()\n+ i.fdRefs.DecRefAndAccount(fr)\n+ i.fdRefsMu.Unlock()\n+}\n+\n+// MapInternal implements platform.File.MapInternal.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inodePlatformFile) MapInternal(fr platform.FileRange, at usermem.AccessType) (safemem.BlockSeq, error) {\n+ return i.fileMapper.MapInternal(fr, i.hostFD, at.Write)\n+}\n+\n+// FD implements platform.File.FD.\n+func (i *inodePlatformFile) FD() int {\n+ return i.hostFD\n+}\n+\n+// AddMapping implements memmap.Mappable.AddMapping.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inode) AddMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) error {\n+ i.mapsMu.Lock()\n+ mapped := i.mappings.AddMapping(ms, ar, offset, writable)\n+ for _, r := range mapped {\n+ i.pf.fileMapper.IncRefOn(r)\n+ }\n+ i.mapsMu.Unlock()\n+ return nil\n+}\n+\n+// RemoveMapping implements memmap.Mappable.RemoveMapping.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inode) RemoveMapping(ctx context.Context, ms memmap.MappingSpace, ar usermem.AddrRange, offset uint64, writable bool) {\n+ i.mapsMu.Lock()\n+ unmapped := i.mappings.RemoveMapping(ms, ar, offset, writable)\n+ for _, r := range unmapped {\n+ i.pf.fileMapper.DecRefOn(r)\n+ }\n+ i.mapsMu.Unlock()\n+}\n+\n+// CopyMapping implements memmap.Mappable.CopyMapping.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inode) CopyMapping(ctx context.Context, ms memmap.MappingSpace, srcAR, dstAR usermem.AddrRange, offset uint64, writable bool) error {\n+ return i.AddMapping(ctx, ms, dstAR, offset, writable)\n+}\n+\n+// Translate implements memmap.Mappable.Translate.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inode) Translate(ctx context.Context, required, optional memmap.MappableRange, at usermem.AccessType) ([]memmap.Translation, error) {\n+ mr := optional\n+ return []memmap.Translation{\n+ {\n+ Source: mr,\n+ File: &i.pf,\n+ Offset: mr.Start,\n+ Perms: usermem.AnyAccess,\n+ },\n+ }, nil\n+}\n+\n+// InvalidateUnsavable implements memmap.Mappable.InvalidateUnsavable.\n+//\n+// Precondition: i.inode.canMap must be true.\n+func (i *inode) InvalidateUnsavable(ctx context.Context) error {\n+ // We expect the same host fd across save/restore, so all translations\n+ // should be valid.\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/usermem/addr.go",
"new_path": "pkg/usermem/addr.go",
"diff": "@@ -106,3 +106,20 @@ func (ar AddrRange) IsPageAligned() bool {\nfunc (ar AddrRange) String() string {\nreturn fmt.Sprintf(\"[%#x, %#x)\", ar.Start, ar.End)\n}\n+\n+// PageRoundDown/Up are equivalent to Addr.RoundDown/Up, but without the\n+// potentially truncating conversion from uint64 to Addr. This is necessary\n+// because there is no way to define generic \"PageRoundDown/Up\" functions in Go.\n+\n+// PageRoundDown returns x rounded down to the nearest page boundary.\n+func PageRoundDown(x uint64) uint64 {\n+ return x &^ (PageSize - 1)\n+}\n+\n+// PageRoundUp returns x rounded up to the nearest page boundary.\n+// ok is true iff rounding up did not wrap around.\n+func PageRoundUp(x uint64) (addr uint64, ok bool) {\n+ addr = PageRoundDown(x + PageSize - 1)\n+ ok = addr >= x\n+ return\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement mmap for host fs in vfs2.
In VFS1, both fs/host and fs/gofer used the same utils for host file mappings.
Refactor parts of fsimpl/gofer to create similar utils to share with
fsimpl/host (memory accounting code moved to fsutil, page rounding arithmetic
moved to usermem).
Updates #1476.
PiperOrigin-RevId: 312345090 |
259,858 | 20.05.2020 11:19:04 | 25,200 | 5bf33a386348a3b07cfc60c3738bc0f9af7eabae | Unbreak permalink.
The permalink should be "linux" not "Linux. | [
{
"change_type": "MODIFY",
"old_path": "website/cmd/syscalldocs/main.go",
"new_path": "website/cmd/syscalldocs/main.go",
"diff": "@@ -46,7 +46,7 @@ type SyscallDoc struct {\n}\nvar mdTemplate = template.Must(template.New(\"out\").Parse(`---\n-title: {{.OS}}/{{.Arch}}\n+title: {{.Title}}\ndescription: Syscall Compatibility Reference Documentation for {{.OS}}/{{.Arch}}\nlayout: docs\ncategory: Compatibility\n@@ -134,6 +134,7 @@ func main() {\nweight += 10\ndata := struct {\n+ Title string\nOS string\nArch string\nWeight int\n@@ -149,7 +150,8 @@ func main() {\nURLs []string\n}\n}{\n- OS: strings.Title(osName),\n+ Title: strings.Title(osName) + \"/\" + archName,\n+ OS: osName,\nArch: archName,\nWeight: weight,\nTotal: 0,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Unbreak permalink.
The permalink should be "linux" not "Linux.
PiperOrigin-RevId: 312518858 |
259,992 | 20.05.2020 14:47:31 | 25,200 | 10abad0040c47baa9f629a01fb43888c3407d8bc | Add hugetlb and rdma cgroups to runsc
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/cgroup/cgroup.go",
"new_path": "runsc/cgroup/cgroup.go",
"diff": "@@ -19,6 +19,7 @@ package cgroup\nimport (\n\"bufio\"\n\"context\"\n+ \"errors\"\n\"fmt\"\n\"io/ioutil\"\n\"os\"\n@@ -38,21 +39,23 @@ const (\ncgroupRoot = \"/sys/fs/cgroup\"\n)\n-var controllers = map[string]controller{\n- \"blkio\": &blockIO{},\n- \"cpu\": &cpu{},\n- \"cpuset\": &cpuSet{},\n- \"memory\": &memory{},\n- \"net_cls\": &networkClass{},\n- \"net_prio\": &networkPrio{},\n- \"pids\": &pids{},\n+var controllers = map[string]config{\n+ \"blkio\": config{ctrlr: &blockIO{}},\n+ \"cpu\": config{ctrlr: &cpu{}},\n+ \"cpuset\": config{ctrlr: &cpuSet{}},\n+ \"memory\": config{ctrlr: &memory{}},\n+ \"net_cls\": config{ctrlr: &networkClass{}},\n+ \"net_prio\": config{ctrlr: &networkPrio{}},\n+ \"pids\": config{ctrlr: &pids{}},\n// These controllers either don't have anything in the OCI spec or is\n// irrelevant for a sandbox.\n- \"devices\": &noop{},\n- \"freezer\": &noop{},\n- \"perf_event\": &noop{},\n- \"systemd\": &noop{},\n+ \"devices\": config{ctrlr: &noop{}},\n+ \"freezer\": config{ctrlr: &noop{}},\n+ \"hugetlb\": config{ctrlr: &noop{}, optional: true},\n+ \"perf_event\": config{ctrlr: &noop{}},\n+ \"rdma\": config{ctrlr: &noop{}, optional: true},\n+ \"systemd\": config{ctrlr: &noop{}},\n}\nfunc setOptionalValueInt(path, name string, val *int64) error {\n@@ -196,8 +199,9 @@ func LoadPaths(pid string) (map[string]string, error) {\nreturn paths, nil\n}\n-// Cgroup represents a group inside all controllers. For example: Name='/foo/bar'\n-// maps to /sys/fs/cgroup/<controller>/foo/bar on all controllers.\n+// Cgroup represents a group inside all controllers. For example:\n+// Name='/foo/bar' maps to /sys/fs/cgroup/<controller>/foo/bar on\n+// all controllers.\ntype Cgroup struct {\nName string `json:\"name\"`\nParents map[string]string `json:\"parents\"`\n@@ -245,13 +249,17 @@ func (c *Cgroup) Install(res *specs.LinuxResources) error {\nclean := specutils.MakeCleanup(func() { _ = c.Uninstall() })\ndefer clean.Clean()\n- for key, ctrl := range controllers {\n+ for key, cfg := range controllers {\npath := c.makePath(key)\nif err := os.MkdirAll(path, 0755); err != nil {\n+ if cfg.optional && errors.Is(err, syscall.EROFS) {\n+ log.Infof(\"Skipping cgroup %q\", key)\n+ continue\n+ }\nreturn err\n}\nif res != nil {\n- if err := ctrl.set(res, path); err != nil {\n+ if err := cfg.ctrlr.set(res, path); err != nil {\nreturn err\n}\n}\n@@ -321,10 +329,13 @@ func (c *Cgroup) Join() (func(), error) {\n}\n// Now join the cgroups.\n- for key := range controllers {\n+ for key, cfg := range controllers {\npath := c.makePath(key)\nlog.Debugf(\"Joining cgroup %q\", path)\nif err := setValue(path, \"cgroup.procs\", \"0\"); err != nil {\n+ if cfg.optional && os.IsNotExist(err) {\n+ continue\n+ }\nreturn undo, err\n}\n}\n@@ -375,6 +386,11 @@ func (c *Cgroup) makePath(controllerName string) string {\nreturn filepath.Join(cgroupRoot, controllerName, path)\n}\n+type config struct {\n+ ctrlr controller\n+ optional bool\n+}\n+\ntype controller interface {\nset(*specs.LinuxResources, string) error\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add hugetlb and rdma cgroups to runsc
Updates #2713
PiperOrigin-RevId: 312559463 |
259,860 | 20.05.2020 14:49:40 | 25,200 | 76369b6480b69bb7bf680db36ce8787fb324911c | Move fsimpl/host file offset from inode to fileDescription. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/host/host.go",
"new_path": "pkg/sentry/fsimpl/host/host.go",
"diff": "@@ -90,9 +90,6 @@ func NewFD(ctx context.Context, mnt *vfs.Mount, hostFD int, opts *NewFDOptions)\nisTTY: opts.IsTTY,\nwouldBlock: wouldBlock(uint32(fileType)),\nseekable: seekable,\n- // For simplicity, set offset to 0. Technically, we should use the existing\n- // offset on the host if the file is seekable.\n- offset: 0,\ncanMap: canMap(uint32(fileType)),\n}\ni.pf.inode = i\n@@ -118,6 +115,10 @@ func NewFD(ctx context.Context, mnt *vfs.Mount, hostFD int, opts *NewFDOptions)\n// i.open will take a reference on d.\ndefer d.DecRef()\n+\n+ // For simplicity, fileDescription.offset is set to 0. Technically, we\n+ // should only set to 0 on files that are not seekable (sockets, pipes,\n+ // etc.), and use the offset from the host fd otherwise when importing.\nreturn i.open(ctx, d.VFSDentry(), mnt, flags)\n}\n@@ -207,13 +208,6 @@ type inode struct {\n// This field is initialized at creation time and is immutable.\nseekable bool\n- // offsetMu protects offset.\n- offsetMu sync.Mutex\n-\n- // offset specifies the current file offset. It is only meaningful when\n- // seekable is true.\n- offset int64\n-\n// wouldBlock is true if the host FD would return EWOULDBLOCK for\n// operations that would block.\n//\n@@ -491,9 +485,6 @@ func (i *inode) open(ctx context.Context, d *vfs.Dentry, mnt *vfs.Mount, flags u\nreturn vfsfd, nil\n}\n- // For simplicity, set offset to 0. Technically, we should\n- // only set to 0 on files that are not seekable (sockets, pipes, etc.),\n- // and use the offset from the host fd otherwise.\nfd := &fileDescription{inode: i}\nvfsfd := &fd.vfsfd\nif err := vfsfd.Init(fd, flags, mnt, d, &vfs.FileDescriptionOptions{}); err != nil {\n@@ -514,6 +505,13 @@ type fileDescription struct {\n//\n// inode is immutable after fileDescription creation.\ninode *inode\n+\n+ // offsetMu protects offset.\n+ offsetMu sync.Mutex\n+\n+ // offset specifies the current file offset. It is only meaningful when\n+ // inode.seekable is true.\n+ offset int64\n}\n// SetStat implements vfs.FileDescriptionImpl.\n@@ -559,10 +557,10 @@ func (f *fileDescription) Read(ctx context.Context, dst usermem.IOSequence, opts\nreturn n, err\n}\n// TODO(gvisor.dev/issue/1672): Cache pages, when forced to do so.\n- i.offsetMu.Lock()\n- n, err := readFromHostFD(ctx, i.hostFD, dst, i.offset, opts.Flags)\n- i.offset += n\n- i.offsetMu.Unlock()\n+ f.offsetMu.Lock()\n+ n, err := readFromHostFD(ctx, i.hostFD, dst, f.offset, opts.Flags)\n+ f.offset += n\n+ f.offsetMu.Unlock()\nreturn n, err\n}\n@@ -599,10 +597,10 @@ func (f *fileDescription) Write(ctx context.Context, src usermem.IOSequence, opt\n}\n// TODO(gvisor.dev/issue/1672): Cache pages, when forced to do so.\n// TODO(gvisor.dev/issue/1672): Write to end of file and update offset if O_APPEND is set on this file.\n- i.offsetMu.Lock()\n- n, err := writeToHostFD(ctx, i.hostFD, src, i.offset, opts.Flags)\n- i.offset += n\n- i.offsetMu.Unlock()\n+ f.offsetMu.Lock()\n+ n, err := writeToHostFD(ctx, i.hostFD, src, f.offset, opts.Flags)\n+ f.offset += n\n+ f.offsetMu.Unlock()\nreturn n, err\n}\n@@ -627,41 +625,41 @@ func (f *fileDescription) Seek(_ context.Context, offset int64, whence int32) (i\nreturn 0, syserror.ESPIPE\n}\n- i.offsetMu.Lock()\n- defer i.offsetMu.Unlock()\n+ f.offsetMu.Lock()\n+ defer f.offsetMu.Unlock()\nswitch whence {\ncase linux.SEEK_SET:\nif offset < 0 {\n- return i.offset, syserror.EINVAL\n+ return f.offset, syserror.EINVAL\n}\n- i.offset = offset\n+ f.offset = offset\ncase linux.SEEK_CUR:\n- // Check for overflow. Note that underflow cannot occur, since i.offset >= 0.\n- if offset > math.MaxInt64-i.offset {\n- return i.offset, syserror.EOVERFLOW\n+ // Check for overflow. Note that underflow cannot occur, since f.offset >= 0.\n+ if offset > math.MaxInt64-f.offset {\n+ return f.offset, syserror.EOVERFLOW\n}\n- if i.offset+offset < 0 {\n- return i.offset, syserror.EINVAL\n+ if f.offset+offset < 0 {\n+ return f.offset, syserror.EINVAL\n}\n- i.offset += offset\n+ f.offset += offset\ncase linux.SEEK_END:\nvar s syscall.Stat_t\nif err := syscall.Fstat(i.hostFD, &s); err != nil {\n- return i.offset, err\n+ return f.offset, err\n}\nsize := s.Size\n// Check for overflow. Note that underflow cannot occur, since size >= 0.\nif offset > math.MaxInt64-size {\n- return i.offset, syserror.EOVERFLOW\n+ return f.offset, syserror.EOVERFLOW\n}\nif size+offset < 0 {\n- return i.offset, syserror.EINVAL\n+ return f.offset, syserror.EINVAL\n}\n- i.offset = size + offset\n+ f.offset = size + offset\ncase linux.SEEK_DATA, linux.SEEK_HOLE:\n// Modifying the offset in the host file table should not matter, since\n@@ -670,16 +668,16 @@ func (f *fileDescription) Seek(_ context.Context, offset int64, whence int32) (i\n// For reading and writing, we always rely on our internal offset.\nn, err := unix.Seek(i.hostFD, offset, int(whence))\nif err != nil {\n- return i.offset, err\n+ return f.offset, err\n}\n- i.offset = n\n+ f.offset = n\ndefault:\n// Invalid whence.\n- return i.offset, syserror.EINVAL\n+ return f.offset, syserror.EINVAL\n}\n- return i.offset, nil\n+ return f.offset, nil\n}\n// Sync implements FileDescriptionImpl.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move fsimpl/host file offset from inode to fileDescription.
PiperOrigin-RevId: 312559861 |
259,884 | 20.05.2020 16:04:16 | 25,200 | 61e68798828b500f093c4c129cb87361c2fe4a4f | Update the Docker quickstart to use 'runsc install' | [
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/install.md",
"new_path": "g3doc/user_guide/install.md",
"diff": "@@ -150,11 +150,8 @@ users, and ensure it is executable by all users**, since `runsc` executes itself\nas user `nobody` to avoid unnecessary privileges. The `/usr/local/bin` directory\nis a good place to put the `runsc` binary.\n-After installation, the`runsc` binary comes with an `install` command that can\n-optionally automatically configure Docker:\n-\n-```bash\n-runsc install\n-```\n+After installation, try out `runsc` by following the\n+[Docker Quick Start](./quick_start/docker.md) or\n+[OCI Quick Start](./quick_start/oci.md).\n[releases]: https://github.com/google/gvisor/releases\n"
},
{
"change_type": "MODIFY",
"old_path": "g3doc/user_guide/quick_start/docker.md",
"new_path": "g3doc/user_guide/quick_start/docker.md",
"diff": "@@ -14,24 +14,28 @@ the next section and proceed straight to running a container.\n## Configuring Docker\nFirst you will need to configure Docker to use `runsc` by adding a runtime entry\n-to your Docker configuration (`/etc/docker/daemon.json`). You may have to create\n-this file if it does not exist. Also, some Docker versions also require you to\n-[specify the `storage-driver` field][storage-driver].\n-\n-In the end, the file should look something like:\n-\n-```json\n-{\n- \"runtimes\": {\n- \"runsc\": {\n- \"path\": \"/usr/local/bin/runsc\"\n- }\n- }\n-}\n+to your Docker configuration (e.g. `/etc/docker/daemon.json`). The easiest way\n+to this is via the `runsc install` command. This will install a docker runtime\n+named \"runsc\" by default.\n+\n+```bash\n+sudo runsc install\n+```\n+\n+You may also wish to install a runtime entry for debugging. The `runsc install`\n+command can accept options that will be passed to the runtime when it is invoked\n+by Docker.\n+\n+```bash\n+sudo runsc install --runtime runsc-debug -- \\\n+ --debug \\\n+ --debug-log=/tmp/runsc-debug.log \\\n+ --strace \\\n+ --log-packets\n```\n-You must restart the Docker daemon after making changes to this file, typically\n-this is done via `systemd`:\n+You must restart the Docker daemon after installing the runtime. Typically this\n+is done via `systemd`:\n```bash\nsudo systemctl restart docker\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update the Docker quickstart to use 'runsc install'
PiperOrigin-RevId: 312573487 |
259,898 | 20.05.2020 17:52:05 | 25,200 | 5f3eeb47286cf9696154f3d9569b655b84ac7d0c | Test that we have PAWS mechanism
If there is a Timestamps option in the arriving segment and SEG.TSval
< TS.Recent and if TS.Recent is valid, then treat the arriving segment
as not acceptable: Send an acknowledgement in reply as specified in
page 69 and drop the segment. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/header/tcp.go",
"new_path": "pkg/tcpip/header/tcp.go",
"diff": "@@ -66,6 +66,14 @@ const (\nTCPOptionSACK = 5\n)\n+// Option Lengths.\n+const (\n+ TCPOptionMSSLength = 4\n+ TCPOptionTSLength = 10\n+ TCPOptionWSLength = 3\n+ TCPOptionSackPermittedLength = 2\n+)\n+\n// TCPFields contains the fields of a TCP packet. It is used to describe the\n// fields of a packet that needs to be encoded.\ntype TCPFields struct {\n@@ -494,14 +502,11 @@ func ParseTCPOptions(b []byte) TCPOptions {\n// returns without encoding anything. It returns the number of bytes written to\n// the provided buffer.\nfunc EncodeMSSOption(mss uint32, b []byte) int {\n- // mssOptionSize is the number of bytes in a valid MSS option.\n- const mssOptionSize = 4\n-\n- if len(b) < mssOptionSize {\n+ if len(b) < TCPOptionMSSLength {\nreturn 0\n}\n- b[0], b[1], b[2], b[3] = TCPOptionMSS, mssOptionSize, byte(mss>>8), byte(mss)\n- return mssOptionSize\n+ b[0], b[1], b[2], b[3] = TCPOptionMSS, TCPOptionMSSLength, byte(mss>>8), byte(mss)\n+ return TCPOptionMSSLength\n}\n// EncodeWSOption encodes the WS TCP option with the WS value in the\n@@ -509,10 +514,10 @@ func EncodeMSSOption(mss uint32, b []byte) int {\n// returns without encoding anything. It returns the number of bytes written to\n// the provided buffer.\nfunc EncodeWSOption(ws int, b []byte) int {\n- if len(b) < 3 {\n+ if len(b) < TCPOptionWSLength {\nreturn 0\n}\n- b[0], b[1], b[2] = TCPOptionWS, 3, uint8(ws)\n+ b[0], b[1], b[2] = TCPOptionWS, TCPOptionWSLength, uint8(ws)\nreturn int(b[1])\n}\n@@ -521,10 +526,10 @@ func EncodeWSOption(ws int, b []byte) int {\n// just returns without encoding anything. It returns the number of bytes\n// written to the provided buffer.\nfunc EncodeTSOption(tsVal, tsEcr uint32, b []byte) int {\n- if len(b) < 10 {\n+ if len(b) < TCPOptionTSLength {\nreturn 0\n}\n- b[0], b[1] = TCPOptionTS, 10\n+ b[0], b[1] = TCPOptionTS, TCPOptionTSLength\nbinary.BigEndian.PutUint32(b[2:], tsVal)\nbinary.BigEndian.PutUint32(b[6:], tsEcr)\nreturn int(b[1])\n@@ -535,11 +540,11 @@ func EncodeTSOption(tsVal, tsEcr uint32, b []byte) int {\n// encoding anything. It returns the number of bytes written to the provided\n// buffer.\nfunc EncodeSACKPermittedOption(b []byte) int {\n- if len(b) < 2 {\n+ if len(b) < TCPOptionSackPermittedLength {\nreturn 0\n}\n- b[0], b[1] = TCPOptionSACKPermitted, 2\n+ b[0], b[1] = TCPOptionSACKPermitted, TCPOptionSackPermittedLength\nreturn int(b[1])\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/BUILD",
"new_path": "test/packetimpact/tests/BUILD",
"diff": "@@ -133,6 +133,19 @@ packetimpact_go_test(\n],\n)\n+packetimpact_go_test(\n+ name = \"tcp_paws_mechanism\",\n+ srcs = [\"tcp_paws_mechanism_test.go\"],\n+ # TODO(b/156682000): Fix netstack then remove the line below.\n+ expect_netstack_failure = True,\n+ deps = [\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/seqnum\",\n+ \"//test/packetimpact/testbench\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n+ ],\n+)\n+\npacketimpact_go_test(\nname = \"tcp_user_timeout\",\nsrcs = [\"tcp_user_timeout_test.go\"],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/packetimpact/tests/tcp_paws_mechanism_test.go",
"diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tcp_paws_mechanism_test\n+\n+import (\n+ \"encoding/hex\"\n+ \"flag\"\n+ \"testing\"\n+ \"time\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ tb \"gvisor.dev/gvisor/test/packetimpact/testbench\"\n+)\n+\n+func init() {\n+ tb.RegisterFlags(flag.CommandLine)\n+}\n+\n+func TestPAWSMechanism(t *testing.T) {\n+ dut := tb.NewDUT(t)\n+ defer dut.TearDown()\n+ listenFD, remotePort := dut.CreateListener(unix.SOCK_STREAM, unix.IPPROTO_TCP, 1)\n+ defer dut.Close(listenFD)\n+ conn := tb.NewTCPIPv4(t, tb.TCP{DstPort: &remotePort}, tb.TCP{SrcPort: &remotePort})\n+ defer conn.Close()\n+\n+ options := make([]byte, header.TCPOptionTSLength)\n+ header.EncodeTSOption(currentTS(), 0, options)\n+ conn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagSyn), Options: options})\n+ synAck, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagSyn | header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"didn't get synack during handshake: %s\", err)\n+ }\n+ parsedSynOpts := header.ParseSynOptions(synAck.Options, true)\n+ if !parsedSynOpts.TS {\n+ t.Fatalf(\"expected TSOpt from DUT, options we got:\\n%s\", hex.Dump(synAck.Options))\n+ }\n+ tsecr := parsedSynOpts.TSVal\n+ header.EncodeTSOption(currentTS(), tsecr, options)\n+ conn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck), Options: options})\n+ acceptFD, _ := dut.Accept(listenFD)\n+ defer dut.Close(acceptFD)\n+\n+ sampleData := []byte(\"Sample Data\")\n+ sentTSVal := currentTS()\n+ header.EncodeTSOption(sentTSVal, tsecr, options)\n+ // 3ms here is chosen arbitrarily to make sure we have increasing timestamps\n+ // every time we send one, it should not cause any flakiness because timestamps\n+ // only need to be non-decreasing.\n+ time.Sleep(3 * time.Millisecond)\n+ conn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck), Options: options}, &tb.Payload{Bytes: sampleData})\n+\n+ gotTCP, err := conn.Expect(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"expected an ACK but got none: %s\", err)\n+ }\n+\n+ parsedOpts := header.ParseTCPOptions(gotTCP.Options)\n+ if !parsedOpts.TS {\n+ t.Fatalf(\"expected TS option in response, options we got:\\n%s\", hex.Dump(gotTCP.Options))\n+ }\n+ if parsedOpts.TSVal < tsecr {\n+ t.Fatalf(\"TSVal should be non-decreasing, but %d < %d\", parsedOpts.TSVal, tsecr)\n+ }\n+ if parsedOpts.TSEcr != sentTSVal {\n+ t.Fatalf(\"TSEcr should match our sent TSVal, %d != %d\", parsedOpts.TSEcr, sentTSVal)\n+ }\n+ tsecr = parsedOpts.TSVal\n+ lastAckNum := gotTCP.AckNum\n+\n+ badTSVal := sentTSVal - 100\n+ header.EncodeTSOption(badTSVal, tsecr, options)\n+ // 3ms here is chosen arbitrarily and this time.Sleep() should not cause flakiness\n+ // due to the exact same reasoning discussed above.\n+ time.Sleep(3 * time.Millisecond)\n+ conn.Send(tb.TCP{Flags: tb.Uint8(header.TCPFlagAck), Options: options}, &tb.Payload{Bytes: sampleData})\n+\n+ gotTCP, err = conn.Expect(tb.TCP{AckNum: lastAckNum, Flags: tb.Uint8(header.TCPFlagAck)}, time.Second)\n+ if err != nil {\n+ t.Fatalf(\"expected segment with AckNum %d but got none: %s\", lastAckNum, err)\n+ }\n+ parsedOpts = header.ParseTCPOptions(gotTCP.Options)\n+ if !parsedOpts.TS {\n+ t.Fatalf(\"expected TS option in response, options we got:\\n%s\", hex.Dump(gotTCP.Options))\n+ }\n+ if parsedOpts.TSVal < tsecr {\n+ t.Fatalf(\"TSVal should be non-decreasing, but %d < %d\", parsedOpts.TSVal, tsecr)\n+ }\n+ if parsedOpts.TSEcr != sentTSVal {\n+ t.Fatalf(\"TSEcr should match our sent TSVal, %d != %d\", parsedOpts.TSEcr, sentTSVal)\n+ }\n+}\n+\n+func currentTS() uint32 {\n+ return uint32(time.Now().UnixNano() / 1e6)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Test that we have PAWS mechanism
If there is a Timestamps option in the arriving segment and SEG.TSval
< TS.Recent and if TS.Recent is valid, then treat the arriving segment
as not acceptable: Send an acknowledgement in reply as specified in
RFC-793 page 69 and drop the segment.
https://tools.ietf.org/html/rfc1323#page-19
PiperOrigin-RevId: 312590678 |
259,985 | 20.05.2020 18:33:51 | 25,200 | 49d2cf287db08b1f09f1246096cabf9c9a951039 | Remove implicit dependencies for leaf packages.
These packages don't actually use go_stateify or go_marshal, but end
up implicitly dependent on the respective packages due to our build
rules.
These unnecessary dependencies make them unusuable in certain contexts
due to circular dependency. | [
{
"change_type": "MODIFY",
"old_path": "pkg/linewriter/BUILD",
"new_path": "pkg/linewriter/BUILD",
"diff": "@@ -5,6 +5,8 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"linewriter\",\nsrcs = [\"linewriter.go\"],\n+ marshal = False,\n+ stateify = False,\nvisibility = [\"//visibility:public\"],\ndeps = [\"//pkg/sync\"],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/log/BUILD",
"new_path": "pkg/log/BUILD",
"diff": "@@ -10,6 +10,8 @@ go_library(\n\"json_k8s.go\",\n\"log.go\",\n],\n+ marshal = False,\n+ stateify = False,\nvisibility = [\n\"//visibility:public\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/state/BUILD",
"new_path": "pkg/state/BUILD",
"diff": "@@ -47,6 +47,7 @@ go_library(\n\"state.go\",\n\"stats.go\",\n],\n+ marshal = False,\nstateify = False,\nvisibility = [\"//:sandbox\"],\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sync/BUILD",
"new_path": "pkg/sync/BUILD",
"diff": "@@ -39,6 +39,8 @@ go_library(\n\"seqcount.go\",\n\"sync.go\",\n],\n+ marshal = False,\n+ stateify = False,\n)\ngo_test(\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove implicit dependencies for leaf packages.
These packages don't actually use go_stateify or go_marshal, but end
up implicitly dependent on the respective packages due to our build
rules.
These unnecessary dependencies make them unusuable in certain contexts
due to circular dependency.
PiperOrigin-RevId: 312595738 |
259,858 | 20.05.2020 22:22:00 | 25,200 | 8437ef752d3c8e90327edad0164f3e4d003821c8 | Normalize permissions in the go branch.
Fixes | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/go.yml",
"new_path": ".github/workflows/go.yml",
"diff": "@@ -17,6 +17,7 @@ jobs:\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n\"${{ github.event.pull_request.statuses_url }}\"\n+ if: github.event_name == 'pull_request'\n- uses: actions/checkout@v2\nwith:\nfetch-depth: 0\n@@ -47,14 +48,14 @@ jobs:\necho -e \"protocol=https\\nhost=github.com\\nusername=${{ secrets.GO_TOKEN }}\\npassword=x-oauth-basic\" | git credential approve\ngit remote add upstream \"https://github.com/${{ github.repository }}\"\ngit push upstream go:go\n- - if: ${{ success() }}\n+ - if: ${{ success() && github.event_name == 'pull_request' }}\nrun: |\njq -nc '{\"state\": \"success\", \"context\": \"go tests\"}' | \\\ncurl -sL -X POST -d @- \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: token ${{ secrets.GITHUB_TOKEN }}\" \\\n\"${{ github.event.pull_request.statuses_url }}\"\n- - if: ${{ failure() }}\n+ - if: ${{ failure() && github.event_name == 'pull_request' }}\nrun: |\njq -nc '{\"state\": \"failure\", \"context\": \"go tests\"}' | \\\ncurl -sL -X POST -d @- \\\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_branch.sh",
"new_path": "tools/go_branch.sh",
"diff": "@@ -88,6 +88,12 @@ EOF\n# because they may correspond to unused templates, etc.\ncp \"${repo_orig}\"/runsc/*.go runsc/\n+# Normalize all permissions. The way bazel constructs the :gopath tree may leave\n+# some strange permissions on files. We don't have anything in this tree that\n+# should be execution, only the Go source files, README.md, and ${othersrc}.\n+find . -type f -exec chmod 0644 {} \\;\n+find . -type d -exec chmod 0755 {} \\;\n+\n# Update the current working set and commit.\ngit add . && git commit -m \"Merge ${head} (automated)\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Normalize permissions in the go branch.
Fixes #2722 |
259,992 | 21.05.2020 10:46:45 | 25,200 | 7bde26934ae6d39649a31f6c77a4bc210277085a | Add IsRunningWithVFS1 to test util
VFS2 is adding more functionality than VFS1. In order to test
new functionality, it's required to skip some tests with VFS1.
To skip tests, use:
SKIP_IF(IsRunningWithVFS1());
The test will run in Linux and gVisor with VFS2 enabled.
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.cc",
"new_path": "test/util/test_util.cc",
"diff": "@@ -42,12 +42,13 @@ namespace testing {\n#define TEST_ON_GVISOR \"TEST_ON_GVISOR\"\n#define GVISOR_NETWORK \"GVISOR_NETWORK\"\n+#define GVISOR_VFS \"GVISOR_VFS\"\nbool IsRunningOnGvisor() { return GvisorPlatform() != Platform::kNative; }\nconst std::string GvisorPlatform() {\n// Set by runner.go.\n- char* env = getenv(TEST_ON_GVISOR);\n+ const char* env = getenv(TEST_ON_GVISOR);\nif (!env) {\nreturn Platform::kNative;\n}\n@@ -55,10 +56,19 @@ const std::string GvisorPlatform() {\n}\nbool IsRunningWithHostinet() {\n- char* env = getenv(GVISOR_NETWORK);\n+ const char* env = getenv(GVISOR_NETWORK);\nreturn env && strcmp(env, \"host\") == 0;\n}\n+bool IsRunningWithVFS1() {\n+ const char* env = getenv(GVISOR_VFS);\n+ if (env == nullptr) {\n+ // If not set, it's running on Linux.\n+ return false;\n+ }\n+ return strcmp(env, \"VFS1\") == 0;\n+}\n+\n// Inline cpuid instruction. Preserve %ebx/%rbx register. In PIC compilations\n// %ebx contains the address of the global offset table. %rbx is occasionally\n// used to address stack variables in presence of dynamic allocas.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/test_util.h",
"new_path": "test/util/test_util.h",
"diff": "@@ -220,6 +220,7 @@ constexpr char kKVM[] = \"kvm\";\nbool IsRunningOnGvisor();\nconst std::string GvisorPlatform();\nbool IsRunningWithHostinet();\n+bool IsRunningWithVFS1();\n#ifdef __linux__\nvoid SetupGvisorDeathTest();\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add IsRunningWithVFS1 to test util
VFS2 is adding more functionality than VFS1. In order to test
new functionality, it's required to skip some tests with VFS1.
To skip tests, use:
SKIP_IF(IsRunningWithVFS1());
The test will run in Linux and gVisor with VFS2 enabled.
Updates #1035
PiperOrigin-RevId: 312698616 |
259,992 | 21.05.2020 11:06:28 | 25,200 | cdf48e851670f8f333f61e7621e0aa7d495d98fe | Fix TestTmpFile
Split check for file in /tmp from working directory test.
Fix readonly case which should not fail to create working
dir. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "images/tmpfile/Dockerfile",
"diff": "+# Create file under /tmp to ensure files inside '/tmp' are not overridden.\n+FROM alpine:3.11.5\n+RUN mkdir -p /tmp/foo \\\n+ && echo 123 > /tmp/foo/file.txt\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/test/dockerutil/dockerutil.go",
"new_path": "pkg/test/dockerutil/dockerutil.go",
"diff": "@@ -162,9 +162,13 @@ type Docker struct {\n//\n// Names of containers will be unique.\nfunc MakeDocker(logger testutil.Logger) *Docker {\n+ // Slashes are not allowed in container names.\n+ name := testutil.RandomID(logger.Name())\n+ name = strings.ReplaceAll(name, \"/\", \"-\")\n+\nreturn &Docker{\nlogger: logger,\n- Name: testutil.RandomID(logger.Name()),\n+ Name: name,\nRuntime: *runtime,\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/integration_test.go",
"new_path": "test/e2e/integration_test.go",
"diff": "@@ -337,27 +337,53 @@ func TestJobControl(t *testing.T) {\n}\n}\n-// TestTmpFile checks that files inside '/tmp' are not overridden. In addition,\n-// it checks that working dir is created if it doesn't exit.\n-func TestTmpFile(t *testing.T) {\n+// TestWorkingDirCreation checks that working dir is created if it doesn't exit.\n+func TestWorkingDirCreation(t *testing.T) {\n+ for _, tc := range []struct {\n+ name string\n+ workingDir string\n+ }{\n+ {name: \"root\", workingDir: \"/foo\"},\n+ {name: \"tmp\", workingDir: \"/tmp/foo\"},\n+ } {\n+ for _, readonly := range []bool{true, false} {\n+ name := tc.name\n+ if readonly {\n+ name += \"-readonly\"\n+ }\n+ t.Run(name, func(t *testing.T) {\nd := dockerutil.MakeDocker(t)\ndefer d.CleanUp()\n- // Should work without ReadOnly\n- if _, err := d.Run(dockerutil.RunOpts{\n+ opts := dockerutil.RunOpts{\nImage: \"basic/alpine\",\n- WorkDir: \"/tmp/foo/bar\",\n- }, \"touch\", \"/tmp/foo/bar/file\"); err != nil {\n+ WorkDir: tc.workingDir,\n+ ReadOnly: readonly,\n+ }\n+ got, err := d.Run(opts, \"sh\", \"-c\", \"echo ${PWD}\")\n+ if err != nil {\nt.Fatalf(\"docker run failed: %v\", err)\n}\n+ if want := tc.workingDir + \"\\n\"; want != got {\n+ t.Errorf(\"invalid working dir, want: %q, got: %q\", want, got)\n+ }\n+ })\n+ }\n+ }\n+}\n- // Expect failure.\n- if _, err := d.Run(dockerutil.RunOpts{\n- Image: \"basic/alpine\",\n- WorkDir: \"/tmp/foo/bar\",\n- ReadOnly: true,\n- }, \"touch\", \"/tmp/foo/bar/file\"); err == nil {\n- t.Fatalf(\"docker run expected failure, but succeeded\")\n+// TestTmpFile checks that files inside '/tmp' are not overridden.\n+func TestTmpFile(t *testing.T) {\n+ d := dockerutil.MakeDocker(t)\n+ defer d.CleanUp()\n+\n+ opts := dockerutil.RunOpts{Image: \"tmpfile\"}\n+ got, err := d.Run(opts, \"cat\", \"/tmp/foo/file.txt\")\n+ if err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ }\n+ if want := \"123\\n\"; want != got {\n+ t.Errorf(\"invalid file content, want: %q, got: %q\", want, got)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix TestTmpFile
Split check for file in /tmp from working directory test.
Fix readonly case which should not fail to create working
dir.
PiperOrigin-RevId: 312702930 |
259,885 | 21.05.2020 14:01:26 | 25,200 | 198642df7689852062be9e3847a98e02d1bcbfd9 | Fix IsRunningWithVFS1() on the runsc-based test runner.
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/runner/runner.go",
"new_path": "test/runner/runner.go",
"diff": "@@ -341,11 +341,13 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\n}\n}\n- // Set environment variables that indicate we are\n- // running in gVisor with the given platform and network.\n+ // Set environment variables that indicate we are running in gVisor with\n+ // the given platform, network, and filesystem stack.\n+ // TODO(gvisor.dev/issue/1487): Update this when the runner supports VFS2.\nplatformVar := \"TEST_ON_GVISOR\"\nnetworkVar := \"GVISOR_NETWORK\"\n- env := append(os.Environ(), platformVar+\"=\"+*platform, networkVar+\"=\"+*network)\n+ vfsVar := \"GVISOR_VFS\"\n+ env := append(os.Environ(), platformVar+\"=\"+*platform, networkVar+\"=\"+*network, vfsVar+\"=VFS1\")\n// Remove env variables that cause the gunit binary to write output\n// files, since they will stomp on eachother, and on the output files\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix IsRunningWithVFS1() on the runsc-based test runner.
Updates #1035
PiperOrigin-RevId: 312736450 |
259,860 | 21.05.2020 16:31:13 | 25,200 | ba2bf9fc13c204ad05d9fbb7199b890e6faf1d76 | Skip socket tests only if running on vfs1. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket.cc",
"new_path": "test/syscalls/linux/socket.cc",
"diff": "@@ -62,9 +62,7 @@ TEST(SocketTest, ProtocolInet) {\n}\nTEST(SocketTest, UnixSocketStat) {\n- // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n- // should pass in VFS2.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nFileDescriptor bound =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n@@ -94,9 +92,7 @@ TEST(SocketTest, UnixSocketStat) {\n}\nTEST(SocketTest, UnixConnectNeedsWritePerm) {\n- // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n- // should succeed in VFS2.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nFileDescriptor bound =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n@@ -128,10 +124,7 @@ using SocketOpenTest = ::testing::TestWithParam<int>;\n// UDS cannot be opened.\nTEST_P(SocketOpenTest, Unix) {\n// FIXME(b/142001530): Open incorrectly succeeds on gVisor.\n- //\n- // TODO(gvisor.dev/issue/1624): Re-enable this test once VFS1 is deleted. It\n- // should succeed in VFS2.\n- SKIP_IF(IsRunningOnGvisor());\n+ SKIP_IF(IsRunningWithVFS1());\nFileDescriptor bound =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_UNIX, SOCK_STREAM, PF_UNIX));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip socket tests only if running on vfs1.
PiperOrigin-RevId: 312763249 |
259,869 | 23.05.2020 11:00:27 | 0 | 76d0aa47f48dfbc1bb5a9d4bd17a1de367946e22 | Fix typo in 'make tests' recipe
test_tag_filter => test_tag_filters
Ref: | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -116,7 +116,7 @@ unit-tests: ## Runs all unit tests in pkg runsc and tools.\n.PHONY: unit-tests\ntests: ## Runs all local ptrace system call tests.\n- @$(MAKE) test OPTIONS=\"--test_tag_filter runsc_ptrace test/syscalls/...\"\n+ @$(MAKE) test OPTIONS=\"--test_tag_filters runsc_ptrace test/syscalls/...\"\n.PHONY: tests\n##\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix typo in 'make tests' recipe
test_tag_filter => test_tag_filters
Ref: https://docs.bazel.build/versions/master/command-line-reference.html#flag--test_tag_filters |
259,994 | 24.05.2020 17:29:25 | 10,800 | 9e8000e9fb0c61e1ffaf455a065c527959d66932 | Add cwd option to spec cmd | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/spec.go",
"new_path": "runsc/cmd/spec.go",
"diff": "@@ -16,6 +16,7 @@ package cmd\nimport (\n\"context\"\n+ \"fmt\"\n\"io/ioutil\"\n\"os\"\n\"path/filepath\"\n@@ -24,7 +25,8 @@ import (\n\"gvisor.dev/gvisor/runsc/flag\"\n)\n-var specTemplate = []byte(`{\n+func genSpec(cwd string) []byte {\n+ var template = fmt.Sprintf(`{\n\"ociVersion\": \"1.0.0\",\n\"process\": {\n\"terminal\": true,\n@@ -39,7 +41,7 @@ var specTemplate = []byte(`{\n\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\",\n\"TERM=xterm\"\n],\n- \"cwd\": \"/\",\n+ \"cwd\": \"%s\",\n\"capabilities\": {\n\"bounding\": [\n\"CAP_AUDIT_WRITE\",\n@@ -123,11 +125,15 @@ var specTemplate = []byte(`{\n}\n]\n}\n-}`)\n+}`, cwd)\n+\n+ return []byte(template)\n+}\n// Spec implements subcommands.Command for the \"spec\" command.\ntype Spec struct {\nbundle string\n+ cwd string\n}\n// Name implements subcommands.Command.Name.\n@@ -165,6 +171,8 @@ EXAMPLE:\n// SetFlags implements subcommands.Command.SetFlags.\nfunc (s *Spec) SetFlags(f *flag.FlagSet) {\nf.StringVar(&s.bundle, \"bundle\", \".\", \"path to the root of the OCI bundle\")\n+ f.StringVar(&s.cwd, \"cwd\", \"/\", \"working directory that will be set for the executable, \"+\n+ \"this value MUST be an absolute path\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -174,7 +182,9 @@ func (s *Spec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"file %q already exists\", confPath)\n}\n- if err := ioutil.WriteFile(confPath, specTemplate, 0664); err != nil {\n+ var spec = genSpec(s.cwd)\n+\n+ if err := ioutil.WriteFile(confPath, spec, 0664); err != nil {\nFatalf(\"writing to %q: %v\", confPath, err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add cwd option to spec cmd |
259,985 | 13.05.2020 19:57:27 | 14,400 | 7938d8734870404c083379d2a73f7cd37fd2eda8 | Write initial design doc for FUSE. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/g3doc/.gitignore",
"diff": "+*.html\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/fs/g3doc/fuse.md",
"diff": "+# Foreword\n+\n+This document describes an on-going project to support FUSE filesystems within\n+the sentry. This is intended to become the final documentation for this\n+subsystem, and is therefore written in the past tense. However FUSE support is\n+currently incomplete and the document will be updated as things progress.\n+\n+# FUSE: Filesystem in Userspace\n+\n+The sentry supports dispatching filesystem operations to a FUSE server,\n+allowing FUSE filesystem to be used with a sandbox.\n+\n+## Overview\n+\n+FUSE has two main components:\n+\n+1. A client kernel driver (canonically `fuse.ko` in Linux), which forwards\n+ filesystem operations (usually initiated by syscalls) to the server.\n+\n+2. A server, which is a userspace daemon that implements the actual filesystem.\n+\n+The sentry implements the client component, which allows a server daemon\n+running within the sandbox to implement a filesystem within the sandbox.\n+\n+A FUSE filesystem is initialized with `mount(2)`, typically with the help of a\n+utility like `fusermount(1)`. Various mount options exist for establishing\n+ownership and access permissions on the filesystem, but the most important mount\n+option is a file descriptor used to establish communication between the client\n+and server.\n+\n+The FUSE device FD is obtained by opening `/dev/fuse`. During regular operation,\n+the client and server use the FUSE protocol described in `fuse(4)` to service\n+filesystem operations. See the \"Protocol\" section below for more\n+information about this protocol. The core of the sentry support for FUSE is the\n+client-side implementation of this protocol.\n+\n+## FUSE in the Sentry\n+\n+The sentry's FUSE client targets VFS2 and has the following components:\n+\n+- An implementation of `/dev/fuse`.\n+\n+- A VFS2 filesystem for mapping syscalls to FUSE ops. Since we're targeting\n+ VFS2, one point of contention may be the lack of inodes in VFS2. We can\n+ tentatively implement a kernfs-based filesystem to bridge the gap in APIs. The\n+ kernfs base functionality can serve the role of the Linux inode cache and, the\n+ filesystem can map VFS2 syscalls to kernfs inode operations; see the\n+ `kernfs.Inode` interface.\n+\n+The FUSE protocol lends itself well to marshaling with `go_marshal`. The\n+various request and response packets can be defined in the ABI package and\n+converted to and from the wire format using `go_marshal`.\n+\n+### Design Goals\n+\n+- While filesystem performance is always important, the sentry's FUSE support is\n+ primarily concerned with compatibility, with performance as a secondary\n+ concern.\n+\n+- Avoiding deadlocks from a hung server daemon.\n+\n+- Consider the potential for denial of service from a malicious server\n+ daemon. Protecting itself from userspace is already a design goal for the\n+ sentry, but needs additional consideration for FUSE. Normally, an operating\n+ system doesn't rely on userspace to make progress with filesystem\n+ operations. Since this changes with FUSE, it opens up the possibility of\n+ creating a chain of dependencies controlled by userspace, which could affect\n+ an entire sandbox. For example: a FUSE op can block a syscall, which could be\n+ holding a subsystem lock, which can then block another task goroutine.\n+\n+### Milestones\n+\n+Below are some broad goals to aim for while implementing FUSE in the sentry.\n+Many FUSE ops can be grouped into broad categories of functionality, and most\n+ops can be implemented in parallel.\n+\n+#### Minimal client that can mount a trivial FUSE filesystem.\n+\n+- Implement `/dev/fuse`.\n+\n+- Implement basic FUSE ops like `FUSE_INIT`, `FUSE_DESTROY`.\n+\n+#### Read-only mount with basic file operations\n+\n+- Implement the majority of file, directory and file descriptor FUSE ops. For\n+ this milestone, we can skip uncommon or complex operations like mmap, mknod,\n+ file locking, poll, and extended attributes. We can stub these out along with\n+ any ops that modify the filesystem. The exact list of required ops are to be\n+ determined, but the goal is to mount a real filesystem as read-only, and be\n+ able to read contents from the filesystem in the sentry.\n+\n+#### Full read-write support\n+\n+- Implement the remaining FUSE ops and decide if we can omit rarely used\n+ operations like ioctl.\n+\n+# Appendix\n+\n+## FUSE Protocol\n+\n+The FUSE protocol is a request-response protocol. All requests are initiated by\n+the client. The wire-format for the protocol is raw c structs serialized to\n+memory.\n+\n+All FUSE requests begin with the following request header:\n+\n+```c\n+struct fuse_in_header {\n+ uint32_t len; // Length of the request, including this header.\n+ uint32_t opcode; // Requested operation.\n+ uint64_t unique; // A unique identifier for this request.\n+ uint64_t nodeid; // ID of the filesystem object being operated on.\n+ uint32_t uid; // UID of the requesting process.\n+ uint32_t gid; // GID of the requesting process.\n+ uint32_t pid; // PID of the requesting process.\n+ uint32_t padding;\n+};\n+```\n+\n+The request is then followed by a payload specific to the `opcode`.\n+\n+All responses begin with this response header:\n+\n+```c\n+struct fuse_out_header {\n+ uint32_t len; // Length of the response, including this header.\n+ int32_t error; // Status of the request, 0 if success.\n+ uint64_t unique; // The unique identifier from the corresponding request.\n+};\n+```\n+\n+The response payload also depends on the request `opcode`. If `error != 0`, the\n+response payload must be empty.\n+\n+### Operations\n+\n+The following is a list of all FUSE operations used in `fuse_in_header.opcode`\n+as of Linux v4.4, and a brief description of their purpose. These are defined in\n+`uapi/linux/fuse.h`. Many of these have a corresponding request and response\n+payload struct; `fuse(4)` has details for some of these. We also note how these\n+operations map to the sentry virtual filesystem.\n+\n+#### FUSE meta-operations\n+\n+These operations are specific to FUSE and don't have a corresponding action in a\n+generic filesystem.\n+\n+- `FUSE_INIT`: This operation initializes a new FUSE filesystem, and is the\n+ first message sent by the client after mount. This is used for version and\n+ feature negotiation. This is related to `mount(2)`.\n+- `FUSE_DESTROY`: Teardown a FUSE filesystem, related to `unmount(2)`.\n+- `FUSE_INTERRUPT`: Interrupts an in-flight operation, specified by the\n+ `fuse_in_header.unique` value provided in the corresponding request\n+ header. The client can send at most one of these per request, and will enter\n+ an uninterruptible wait for a reply. The server is expected to reply promptly.\n+- `FUSE_FORGET`: A hint to the server that server should evict the indicate node\n+ from any caches. This is wired up to `(struct super_operations).evict_inode`\n+ in Linux, which is in turned hooked as the inode cache shrinker which is\n+ typically triggered by system memory pressure.\n+- `FUSE_BATCH_FORGET`: Batch version of `FUSE_FORGET`.\n+\n+#### Filesystem Syscalls\n+\n+These FUSE ops map directly to an equivalent filesystem syscall, or family of\n+syscalls. The relevant syscalls have a similar name to the operation, unless\n+otherwise noted.\n+\n+Node creation:\n+\n+- `FUSE_MKNOD`\n+- `FUSE_MKDIR`\n+- `FUSE_CREATE`: This is equivalent to `open(2)` and `creat(2)`, which\n+ atomically creates and opens a node.\n+\n+Node attributes and extended attributes:\n+\n+- `FUSE_GETATTR`\n+- `FUSE_SETATTR`\n+- `FUSE_SETXATTR`\n+- `FUSE_GETXATTR`\n+- `FUSE_LISTXATTR`\n+- `FUSE_REMOVEXATTR`\n+\n+Node link manipulation:\n+\n+- `FUSE_READLINK`\n+- `FUSE_LINK`\n+- `FUSE_SYMLINK`\n+- `FUSE_UNLINK`\n+\n+Directory operations:\n+\n+- `FUSE_RMDIR`\n+- `FUSE_RENAME`\n+- `FUSE_RENAME2`\n+- `FUSE_OPENDIR`: `open(2)` for directories.\n+- `FUSE_RELEASEDIR`: `close(2)` for directories.\n+- `FUSE_READDIR`\n+- `FUSE_READDIRPLUS`\n+- `FUSE_FSYNCDIR`: `fsync(2)` for directories.\n+- `FUSE_LOOKUP`: Establishes a unique identifier for a FS node. This is\n+ reminiscent of `VirtualFilesystem.GetDentryAt` in that it resolves a path\n+ component to a node. However the returned identifier is opaque to the\n+ client. The server must remember this mapping, as this is how the client will\n+ reference the node in the future.\n+\n+File operations:\n+\n+- `FUSE_OPEN`: `open(2)` for files.\n+- `FUSE_RELEASE`: `close(2)` for files.\n+- `FUSE_FSYNC`\n+- `FUSE_FALLOCATE`\n+- `FUSE_SETUPMAPPING`: Creates a memory map on a file for `mmap(2)`.\n+- `FUSE_REMOVEMAPPING`: Removes a memory map for `munmap(2)`.\n+\n+File locking:\n+\n+- `FUSE_GETLK`\n+- `FUSE_SETLK`\n+- `FUSE_SETLKW`\n+- `FUSE_COPY_FILE_RANGE`\n+\n+File descriptor operations:\n+\n+- `FUSE_IOCTL`\n+- `FUSE_POLL`\n+- `FUSE_LSEEK`\n+\n+Filesystem operations:\n+\n+- `FUSE_STATFS`\n+\n+#### Permissions\n+\n+- `FUSE_ACCESS` is used to check if a node is accessible, as part of many\n+ syscall implementations. Maps to `vfs.FilesystemImpl.AccessAt`\n+ in the sentry.\n+\n+#### I/O Operations\n+\n+These ops are used to read and write file pages. They're used to implement both\n+I/O syscalls like `read(2)`, `write(2)` and `mmap(2)`.\n+\n+- `FUSE_READ`\n+- `FUSE_WRITE`\n+\n+#### Miscellaneous\n+\n+- `FUSE_FLUSH`: Used by the client to indicate when a file descriptor is\n+ closed. Distinct from `FUSE_FSYNC`, which corresponds to an `fsync(2)` syscall\n+ from the user. Maps to `vfs.FileDescriptorImpl.Release` in the sentry.\n+- `FUSE_BMAP`: Old address space API for block defrag. Probably not needed.\n+- `FUSE_NOTIFY_REPLY`: [TODO: what does this do?]\n+\n+# References\n+\n+- `fuse(4)` manpage.\n+- Linux kernel FUSE documentation: https://www.kernel.org/doc/html/latest/filesystems/fuse.html\n"
}
] | Go | Apache License 2.0 | google/gvisor | Write initial design doc for FUSE. |
259,885 | 26.05.2020 22:42:54 | 25,200 | e028714a0dd390b2321c4beeac62c5b2904cd917 | Support dfltuid and dfltgid mount options in the VFS2 gofer client. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -84,12 +84,6 @@ type filesystem struct {\n// devMinor is the filesystem's minor device number. devMinor is immutable.\ndevMinor uint32\n- // uid and gid are the effective KUID and KGID of the filesystem's creator,\n- // and are used as the owner and group for files that don't specify one.\n- // uid and gid are immutable.\n- uid auth.KUID\n- gid auth.KGID\n-\n// renameMu serves two purposes:\n//\n// - It synchronizes path resolution with renaming initiated by this\n@@ -122,6 +116,8 @@ type filesystemOptions struct {\nfd int\naname string\ninterop InteropMode // derived from the \"cache\" mount option\n+ dfltuid auth.KUID\n+ dfltgid auth.KGID\nmsize uint32\nversion string\n@@ -230,6 +226,15 @@ type InternalFilesystemOptions struct {\nOpenSocketsByConnecting bool\n}\n+// _V9FS_DEFUID and _V9FS_DEFGID (from Linux's fs/9p/v9fs.h) are the default\n+// UIDs and GIDs used for files that do not provide a specific owner or group\n+// respectively.\n+const (\n+ // uint32(-2) doesn't work in Go.\n+ _V9FS_DEFUID = auth.KUID(4294967294)\n+ _V9FS_DEFGID = auth.KGID(4294967294)\n+)\n+\n// Name implements vfs.FilesystemType.Name.\nfunc (FilesystemType) Name() string {\nreturn Name\n@@ -315,6 +320,31 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n}\n}\n+ // Parse the default UID and GID.\n+ fsopts.dfltuid = _V9FS_DEFUID\n+ if dfltuidstr, ok := mopts[\"dfltuid\"]; ok {\n+ delete(mopts, \"dfltuid\")\n+ dfltuid, err := strconv.ParseUint(dfltuidstr, 10, 32)\n+ if err != nil {\n+ ctx.Warningf(\"gofer.FilesystemType.GetFilesystem: invalid default UID: dfltuid=%s\", dfltuidstr)\n+ return nil, nil, syserror.EINVAL\n+ }\n+ // In Linux, dfltuid is interpreted as a UID and is converted to a KUID\n+ // in the caller's user namespace, but goferfs isn't\n+ // application-mountable.\n+ fsopts.dfltuid = auth.KUID(dfltuid)\n+ }\n+ fsopts.dfltgid = _V9FS_DEFGID\n+ if dfltgidstr, ok := mopts[\"dfltgid\"]; ok {\n+ delete(mopts, \"dfltgid\")\n+ dfltgid, err := strconv.ParseUint(dfltgidstr, 10, 32)\n+ if err != nil {\n+ ctx.Warningf(\"gofer.FilesystemType.GetFilesystem: invalid default UID: dfltgid=%s\", dfltgidstr)\n+ return nil, nil, syserror.EINVAL\n+ }\n+ fsopts.dfltgid = auth.KGID(dfltgid)\n+ }\n+\n// Parse the 9P message size.\nfsopts.msize = 1024 * 1024 // 1M, tested to give good enough performance up to 64M\nif msizestr, ok := mopts[\"msize\"]; ok {\n@@ -422,8 +452,6 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nclient: client,\nclock: ktime.RealtimeClockFromContext(ctx),\ndevMinor: devMinor,\n- uid: creds.EffectiveKUID,\n- gid: creds.EffectiveKGID,\nsyncableDentries: make(map[*dentry]struct{}),\nspecialFileFDs: make(map[*specialFileFD]struct{}),\n}\n@@ -672,8 +700,8 @@ func (fs *filesystem) newDentry(ctx context.Context, file p9file, qid p9.QID, ma\nfile: file,\nino: qid.Path,\nmode: uint32(attr.Mode),\n- uid: uint32(fs.uid),\n- gid: uint32(fs.gid),\n+ uid: uint32(fs.opts.dfltuid),\n+ gid: uint32(fs.opts.dfltgid),\nblockSize: usermem.PageSize,\nhandle: handle{\nfd: -1,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support dfltuid and dfltgid mount options in the VFS2 gofer client.
PiperOrigin-RevId: 313332542 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.