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,880 | 10.08.2021 13:06:51 | -7,200 | f971396c6515fc71d3cc8cdfbf60845c1d1e9e03 | fix missing SIGTTOU signal in SetForegroundProcessGroup | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/thread_group.go",
"new_path": "pkg/sentry/kernel/thread_group.go",
"diff": "@@ -489,11 +489,6 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\ntg.signalHandlers.mu.Lock()\ndefer tg.signalHandlers.mu.Unlock()\n- // TODO(gvisor.dev/issue/6148): \"If tcsetpgrp() is called by a member of a\n- // background process group in its session, and the calling process is not\n- // blocking or ignoring SIGTTOU, a SIGTTOU signal is sent to all members of\n- // this background process group.\"\n-\n// tty must be the controlling terminal.\nif tg.tty != tty {\nreturn -1, linuxerr.ENOTTY\n@@ -516,6 +511,11 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\nreturn -1, linuxerr.EPERM\n}\n+ //if the calling process is a member of a background group, a SIGTTOU signal is sent to all members of this background process group.\n+ if tg.processGroup.session.foreground.id != tg.processGroup.id {\n+ tg.processGroup.SendSignal(&linux.SignalInfo{Signo: int32(linux.SIGTTOU)})\n+ }\n+\ntg.processGroup.session.foreground.id = pgid\nreturn 0, nil\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | fix missing SIGTTOU signal in SetForegroundProcessGroup |
259,907 | 11.08.2021 15:25:31 | 25,200 | c2353e4055ac77d5a205594b5e3d2697b96abd7d | [op] Fix //debian:debian. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -444,7 +444,7 @@ $(RELEASE_ARTIFACTS)/%:\n@mkdir -p $@\n@$(call copy,//runsc:runsc,$@)\n@$(call copy,//shim:containerd-shim-runsc-v1,$@)\n- @$(call copy,//debian:debian,$@)\n+ @$(call deb_copy,//debian:debian,$@)\nrelease: $(RELEASE_KEY) $(RELEASE_ARTIFACTS)/$(ARCH)\n@mkdir -p $(RELEASE_ROOT)\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -1245,8 +1245,8 @@ rbe_autoconfig(name = \"rbe_default\")\nhttp_archive(\nname = \"rules_pkg\",\n- sha256 = \"6b5969a7acd7b60c02f816773b06fcf32fbe8ba0c7919ccdc2df4f8fb923804a\",\n- url = \"https://github.com/bazelbuild/rules_pkg/releases/download/0.3.0/rules_pkg-0.3.0.tar.gz\",\n+ sha256 = \"353b20e8b093d42dd16889c7f918750fb8701c485ac6cceb69a5236500507c27\",\n+ url = \"https://github.com/bazelbuild/rules_pkg/releases/download/0.5.0/rules_pkg-0.5.0.tar.gz\",\n)\nload(\"@rules_pkg//:deps.bzl\", \"rules_pkg_dependencies\")\n"
},
{
"change_type": "MODIFY",
"old_path": "debian/BUILD",
"new_path": "debian/BUILD",
"diff": "@@ -28,12 +28,10 @@ pkg_deb(\namd64 = \"amd64\",\narm64 = \"arm64\",\n),\n- changes = \"runsc.changes\",\nconffiles = [\n\"/etc/containerd/runsc.toml\",\n],\ndata = \":debian-data\",\n- deb = \"runsc.deb\",\n# Note that the description_file will be flatten (all newlines removed),\n# and therefore it is kept to a simple one-line description. The expected\n# format for debian packages is \"short summary\\nLonger explanation of\n@@ -42,6 +40,7 @@ pkg_deb(\nhomepage = \"https://gvisor.dev/\",\nmaintainer = \"The gVisor Authors <[email protected]>\",\npackage = \"runsc\",\n+ package_file_name = \"runsc.deb\",\npostinst = \"postinst.sh\",\nversion_file = version,\nvisibility = [\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "debian/show_paths.bzl",
"diff": "+\"\"\"Formatter to extract the output files from pkg_deb.\"\"\"\n+\n+def format(target):\n+ provider_map = providers(target)\n+ return \"\\n\".join([\n+ provider_map[\"OutputGroupInfo\"].out.to_list()[0].path,\n+ provider_map[\"OutputGroupInfo\"].deb.to_list()[0].path,\n+ provider_map[\"OutputGroupInfo\"].changes.to_list()[0].path,\n+ ])\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -84,7 +84,7 @@ DOCKER_RUN_OPTIONS += -v \"$(shell readlink -m $(GCLOUD_CONFIG)):$(GCLOUD_CONFIG)\nDOCKER_RUN_OPTIONS += -v \"/tmp:/tmp\"\nDOCKER_EXEC_OPTIONS := --user $(UID):$(GID)\nDOCKER_EXEC_OPTIONS += --interactive\n-ifeq (true,$(shell test -t 0 && echo true))\n+ifeq (true,$(shell test -t 1 && echo true))\nDOCKER_EXEC_OPTIONS += --tty\nendif\n@@ -199,9 +199,17 @@ build_paths = \\\n| xargs -r -n 1 -I {} readlink -f \"{}\" \\\n| xargs -r -n 1 -I {} bash -c 'set -xeuo pipefail; $(2)')\n+debian_paths = \\\n+ (set -euo pipefail; \\\n+ $(call wrapper,$(BAZEL) build $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1)) && \\\n+ $(call wrapper,$(BAZEL) cquery $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1) --output=starlark --starlark:file=debian/show_paths.bzl) \\\n+ | xargs -r -n 1 -I {} readlink -f \"{}\" \\\n+ | xargs -r -n 1 -I {} bash -c 'set -xeuo pipefail; $(2)')\n+\nclean = $(call header,CLEAN) && $(call wrapper,$(BAZEL) clean)\nbuild = $(call header,BUILD $(1)) && $(call build_paths,$(1),echo {})\ncopy = $(call header,COPY $(1) $(2)) && $(call build_paths,$(1),cp -fa {} $(2))\n+deb_copy = $(call header,COPY $(1) $(2)) && $(call debian_paths,$(1),cp -fa {} $(2))\nrun = $(call header,RUN $(1) $(2)) && $(call build_paths,$(1),{} $(2))\nsudo = $(call header,SUDO $(1) $(2)) && $(call build_paths,$(1),sudo -E {} $(2))\ntest = $(call header,TEST $(1)) && $(call wrapper,$(BAZEL) test $(TEST_OPTIONS) $(1))\n"
}
] | Go | Apache License 2.0 | google/gvisor | [op] Fix //debian:debian.
Co-authored-by: Andrei Vagin <[email protected]>
PiperOrigin-RevId: 390232925 |
260,007 | 11.08.2021 16:18:52 | 25,200 | 23f8e8481678593b83842b58306e2e960752ff4a | Fix LinkTest.OldnameDoesNotExist
Previous, this test was the same as OldnameIsEmpty. This CL makes the test check
what happens if the old name does not exist. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/link.cc",
"new_path": "test/syscalls/linux/link.cc",
"diff": "@@ -142,7 +142,8 @@ TEST(LinkTest, OldnameIsEmpty) {\nTEST(LinkTest, OldnameDoesNotExist) {\nconst std::string oldname = NewTempAbsPath();\nconst std::string newname = NewTempAbsPath();\n- EXPECT_THAT(link(\"\", newname.c_str()), SyscallFailsWithErrno(ENOENT));\n+ EXPECT_THAT(link(oldname.c_str(), newname.c_str()),\n+ SyscallFailsWithErrno(ENOENT));\n}\nTEST(LinkTest, NewnameCannotExist) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix LinkTest.OldnameDoesNotExist
Previous, this test was the same as OldnameIsEmpty. This CL makes the test check
what happens if the old name does not exist.
PiperOrigin-RevId: 390243070 |
259,985 | 11.08.2021 16:32:51 | 25,200 | 8d84c5a8eeb6a08de2ac4920c1e6959055ccbda1 | Wrap test queues in Queue object on creation. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/msgqueue.cc",
"new_path": "test/syscalls/linux/msgqueue.cc",
"diff": "@@ -40,6 +40,10 @@ constexpr int kInterruptSignal = SIGALRM;\nclass Queue {\npublic:\nexplicit Queue(int id) : id_(id) {}\n+ Queue(const Queue&) = delete;\n+ Queue& operator=(const Queue&) = delete;\n+\n+ Queue(Queue&& other) { id_ = other.release(); }\n~Queue() {\nif (id_ >= 0) {\n@@ -59,6 +63,14 @@ class Queue {\nint id_ = -1;\n};\n+PosixErrorOr<Queue> Msgget(key_t key, int flags) {\n+ int id = msgget(key, flags);\n+ if (id == -1) {\n+ return PosixError(errno, absl::StrFormat(\"msgget(%d, %d)\", key, flags));\n+ }\n+ return Queue(id);\n+}\n+\n// Default size for messages.\nconstexpr size_t msgSize = 50;\n@@ -90,8 +102,7 @@ TEST(MsgqueueTest, MsgGet) {\nconst key_t key = ftok(keyfile.path().c_str(), 1);\nASSERT_THAT(key, SyscallSucceeds());\n- Queue queue(msgget(key, IPC_CREAT));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(key, IPC_CREAT));\nEXPECT_THAT(msgget(key, 0), SyscallSucceedsWithValue(queue.get()));\n}\n@@ -103,27 +114,20 @@ TEST(MsgqueueTest, MsgGetFail) {\nEXPECT_THAT(msgget(key, 0), SyscallFailsWithErrno(ENOENT));\n- Queue queue(msgget(key, IPC_CREAT));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(key, IPC_CREAT));\nEXPECT_THAT(msgget(key, IPC_CREAT | IPC_EXCL), SyscallFailsWithErrno(EEXIST));\n}\n// Test using msgget(2) with IPC_PRIVATE option.\nTEST(MsgqueueTest, MsgGetIpcPrivate) {\n- Queue queue1(msgget(IPC_PRIVATE, 0));\n- ASSERT_THAT(queue1.get(), SyscallSucceeds());\n-\n- Queue queue2(msgget(IPC_PRIVATE, 0));\n- ASSERT_THAT(queue2.get(), SyscallSucceeds());\n-\n+ Queue queue1 = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0));\n+ Queue queue2 = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0));\nEXPECT_NE(queue1.get(), queue2.get());\n}\n// Test simple msgsnd and msgrcv.\nTEST(MsgqueueTest, MsgOpSimple) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"A message.\"};\nmsgbuf rcv;\n@@ -138,8 +142,7 @@ TEST(MsgqueueTest, MsgOpSimple) {\n// Test msgsnd and msgrcv of an empty message.\nTEST(MsgqueueTest, MsgOpEmpty) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"\"};\nmsgbuf rcv;\n@@ -151,8 +154,7 @@ TEST(MsgqueueTest, MsgOpEmpty) {\n// Test truncation of message with MSG_NOERROR flag.\nTEST(MsgqueueTest, MsgOpTruncate) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"\"};\nmsgbuf rcv;\n@@ -166,8 +168,7 @@ TEST(MsgqueueTest, MsgOpTruncate) {\n// Test msgsnd and msgrcv using invalid arguments.\nTEST(MsgqueueTest, MsgOpInvalidArgs) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"\"};\n@@ -184,8 +185,7 @@ TEST(MsgqueueTest, MsgOpInvalidArgs) {\n// Test non-blocking msgrcv with an empty queue.\nTEST(MsgqueueTest, MsgOpNoMsg) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf rcv;\nEXPECT_THAT(msgrcv(queue.get(), &rcv, sizeof(rcv.mtext) + 1, 0, IPC_NOWAIT),\n@@ -195,8 +195,7 @@ TEST(MsgqueueTest, MsgOpNoMsg) {\n// Test non-blocking msgrcv with a non-empty queue, but no messages of wanted\n// type.\nTEST(MsgqueueTest, MsgOpNoMsgType) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"\"};\nASSERT_THAT(msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0),\n@@ -208,8 +207,7 @@ TEST(MsgqueueTest, MsgOpNoMsgType) {\n// Test msgrcv with a larger size message than wanted, and truncation disabled.\nTEST(MsgqueueTest, MsgOpTooBig) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"\"};\nASSERT_THAT(msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0),\n@@ -221,8 +219,7 @@ TEST(MsgqueueTest, MsgOpTooBig) {\n// Test receiving messages based on type.\nTEST(MsgqueueTest, MsgRcvType) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\n// Send messages in an order and receive them in reverse, based on type,\n// which shouldn't block.\n@@ -248,8 +245,7 @@ TEST(MsgqueueTest, MsgRcvType) {\n// Test using MSG_EXCEPT to receive a different-type message.\nTEST(MsgqueueTest, MsgExcept) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nstd::map<int64_t, msgbuf> typeToBuf = {\n{1, msgbuf{1, \"Message 1.\"}},\n@@ -274,8 +270,7 @@ TEST(MsgqueueTest, MsgExcept) {\n// Test msgrcv with a negative type.\nTEST(MsgqueueTest, MsgRcvTypeNegative) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\n// When msgtyp is negative, msgrcv returns the first message with mtype less\n// than or equal to the absolute value.\n@@ -298,8 +293,7 @@ TEST(MsgqueueTest, MsgRcvTypeNegative) {\nTEST(MsgqueueTest, MsgOpPermissions) {\nAutoCapability cap(CAP_IPC_OWNER, false);\n- Queue queue(msgget(IPC_PRIVATE, 0000));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0000));\nmsgbuf buf{1, \"\"};\n@@ -311,8 +305,7 @@ TEST(MsgqueueTest, MsgOpPermissions) {\n// Test limits for messages and queues.\nTEST(MsgqueueTest, MsgOpLimits) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"A message.\"};\n@@ -340,11 +333,14 @@ bool MsgCopySupported() {\n// test if errno == ENOSYS. This means that the test will always run on\n// gVisor, but may be skipped on native linux.\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n-\n+ auto maybe_id = Msgget(IPC_PRIVATE, 0600);\n+ if (!maybe_id.ok()) {\n+ return false;\n+ }\n+ Queue queue(std::move(maybe_id.ValueOrDie()));\nmsgbuf buf{1, \"Test message.\"};\n- msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0);\n+ msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0);\nreturn !(msgrcv(queue.get(), &buf, sizeof(buf.mtext) + 1, 0,\nMSG_COPY | IPC_NOWAIT) == -1 &&\nerrno == ENOSYS);\n@@ -354,9 +350,7 @@ bool MsgCopySupported() {\nTEST(MsgqueueTest, MsgCopy) {\nSKIP_IF(!MsgCopySupported());\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf bufs[5] = {\nmsgbuf{1, \"Message 1.\"}, msgbuf{2, \"Message 2.\"}, msgbuf{3, \"Message 3.\"},\nmsgbuf{4, \"Message 4.\"}, msgbuf{5, \"Message 5.\"},\n@@ -390,9 +384,7 @@ TEST(MsgqueueTest, MsgCopy) {\nTEST(MsgqueueTest, MsgCopyInvalidArgs) {\nSKIP_IF(!MsgCopySupported());\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf rcv;\nEXPECT_THAT(msgrcv(queue.get(), &rcv, msgSize, 1, MSG_COPY),\nSyscallFailsWithErrno(EINVAL));\n@@ -406,9 +398,7 @@ TEST(MsgqueueTest, MsgCopyInvalidArgs) {\nTEST(MsgqueueTest, MsgCopyInvalidIndex) {\nSKIP_IF(!MsgCopySupported());\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf rcv;\nEXPECT_THAT(msgrcv(queue.get(), &rcv, msgSize, -3, MSG_COPY | IPC_NOWAIT),\nSyscallFailsWithErrno(ENOMSG));\n@@ -419,9 +409,7 @@ TEST(MsgqueueTest, MsgCopyInvalidIndex) {\n// Test msgrcv (most probably) blocking on an empty queue.\nTEST(MsgqueueTest, MsgRcvBlocking) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf buf{1, \"A message.\"};\nScopedThread t([&] {\n@@ -441,9 +429,7 @@ TEST(MsgqueueTest, MsgRcvBlocking) {\n// Test msgrcv (most probably) waiting for a specific-type message.\nTEST(MsgqueueTest, MsgRcvTypeBlocking) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgbuf bufs[5] = {{1, \"A message.\"},\n{1, \"A message.\"},\n{1, \"A message.\"},\n@@ -471,9 +457,7 @@ TEST(MsgqueueTest, MsgRcvTypeBlocking) {\n// Test msgsnd (most probably) blocking on a full queue.\nTEST(MsgqueueTest, MsgSndBlocking) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n-\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgmax buf{1, \"\"}; // Has max amount of bytes.\nconst size_t msgCount = msgMnb / msgMax; // Number of messages that can be\n@@ -512,8 +496,7 @@ TEST(MsgqueueTest, MsgSndBlocking) {\n// Test removing a queue while a blocking msgsnd is executing.\nTEST(MsgqueueTest, MsgSndRmWhileBlocking) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\n// Number of messages that can be sent without blocking.\nconst size_t msgCount = msgMnb / msgMax;\n@@ -549,8 +532,7 @@ TEST(MsgqueueTest, MsgSndRmWhileBlocking) {\n// Test removing a queue while a blocking msgrcv is executing.\nTEST(MsgqueueTest, MsgRcvRmWhileBlocking) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nScopedThread t([&] {\n// Because we're repeating on EINTR, msgsnd may race with msgctl(IPC_RMID)\n@@ -568,8 +550,7 @@ TEST(MsgqueueTest, MsgRcvRmWhileBlocking) {\n// Test a collection of msgsnd/msgrcv operations in different processes.\nTEST(MsgqueueTest, MsgOpGeneral) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n- ASSERT_THAT(queue.get(), SyscallSucceeds());\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\n// Create multiple sending/receiving threads that send messages back and\n// forth. There's a matching recv for each send, so by the end of the test,\n@@ -625,7 +606,7 @@ TEST(MsgqueueTest, MsgOpGeneral) {\nvoid empty_sighandler(int sig, siginfo_t* info, void* context) {}\nTEST(MsgqueueTest, InterruptRecv) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nchar buf[64];\nabsl::Notification done, exit;\n@@ -663,7 +644,7 @@ TEST(MsgqueueTest, InterruptRecv) {\n}\nTEST(MsgqueueTest, InterruptSend) {\n- Queue queue(msgget(IPC_PRIVATE, 0600));\n+ Queue queue = ASSERT_NO_ERRNO_AND_VALUE(Msgget(IPC_PRIVATE, 0600));\nmsgmax buf{1, \"\"};\n// Number of messages that can be sent without blocking.\nconst size_t msgCount = msgMnb / msgMax;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Wrap test queues in Queue object on creation.
PiperOrigin-RevId: 390245901 |
260,007 | 11.08.2021 16:58:15 | 25,200 | 09b453cec07bceeb4185bc9bc951efbda366472b | Fix FSSupportsMap check
Previously, this check always failed because we did not provide MAP_SHARED
or MAP_PRIVATE. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mmap.cc",
"new_path": "test/syscalls/linux/mmap.cc",
"diff": "@@ -795,7 +795,7 @@ class MMapFileTest : public MMapTest {\nbool FSSupportsMap() const {\nbool supported = true;\n- void* ret = mmap(nullptr, 1, PROT_NONE, 0, fd_.get(), 0);\n+ void* ret = mmap(nullptr, 1, PROT_NONE, MAP_PRIVATE, fd_.get(), 0);\nif (ret == MAP_FAILED && errno != ENODEV) {\nsupported = false;\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix FSSupportsMap check
Previously, this check always failed because we did not provide MAP_SHARED
or MAP_PRIVATE.
PiperOrigin-RevId: 390251086 |
259,985 | 11.08.2021 17:18:53 | 25,200 | a50596874a4971167f97a05181363e91292a2885 | Initial cgroupfs support for subcontainers
Allow creation and management of subcontainers through cgroupfs
directory syscalls. Also add a mechanism to specify a default root
container to start new jobs in.
This implements the filesystem support for subcontainers, but doesn't
implement hierarchical resource accounting or task migration. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"new_path": "pkg/sentry/fsimpl/cgroupfs/BUILD",
"diff": "@@ -32,6 +32,7 @@ go_library(\n\"//pkg/context\",\n\"//pkg/coverage\",\n\"//pkg/errors/linuxerr\",\n+ \"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\n@@ -43,7 +44,6 @@ go_library(\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sync\",\n- \"//pkg/syserror\",\n\"//pkg/usermem\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/base.go",
"diff": "@@ -88,7 +88,6 @@ type controller interface {\n// +stateify savable\ntype cgroupInode struct {\ndir\n- fs *filesystem\n// ts is the list of tasks in this cgroup. The kernel is responsible for\n// removing tasks from this list before they're destroyed, so any tasks on\n@@ -102,9 +101,10 @@ var _ kernel.CgroupImpl = (*cgroupInode)(nil)\nfunc (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credentials) kernfs.Inode {\nc := &cgroupInode{\n- fs: fs,\n+ dir: dir{fs: fs},\nts: make(map[*kernel.Task]struct{}),\n}\n+ c.dir.cgi = c\ncontents := make(map[string]kernfs.Inode)\ncontents[\"cgroup.procs\"] = fs.newControllerFile(ctx, creds, &cgroupProcsData{c})\n@@ -115,8 +115,7 @@ func (fs *filesystem) newCgroupInode(ctx context.Context, creds *auth.Credential\n}\nc.dir.InodeAttrs.Init(ctx, creds, linux.UNNAMED_MAJOR, fs.devMinor, fs.NextIno(), linux.ModeDirectory|linux.FileMode(0555))\n- c.dir.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\n- c.dir.InitRefs()\n+ c.dir.OrderedChildren.Init(kernfs.OrderedChildrenOptions{Writable: true})\nc.dir.IncLinks(c.dir.OrderedChildren.Populate(contents))\natomic.AddUint64(&fs.numCgroups, 1)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/cgroupfs.go",
"diff": "// controllers associated with them.\n//\n// Since cgroupfs doesn't allow hardlinks, there is a unique mapping between\n-// cgroupfs dentries and inodes.\n+// cgroupfs dentries and inodes. Thus, cgroupfs inodes don't need to be ref\n+// counted and exist until they're unlinked once or the FS is destroyed.\n//\n// # Synchronization\n//\n// Lock order:\n//\n// kernel.CgroupRegistry.mu\n-// cgroupfs.filesystem.mu\n+// kernfs.filesystem.mu\n// kernel.TaskSet.mu\n// kernel.Task.mu\n// cgroupfs.filesystem.tasksMu.\n+// cgroupfs.dir.OrderedChildren.mu\npackage cgroupfs\nimport (\n@@ -63,6 +65,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -108,6 +111,7 @@ type FilesystemType struct{}\n// +stateify savable\ntype InternalData struct {\nDefaultControlValues map[string]int64\n+ InitialCgroupPath string\n}\n// filesystem implements vfs.FilesystemImpl and kernel.cgroupFS.\n@@ -134,6 +138,11 @@ type filesystem struct {\nnumCgroups uint64 // Protected by atomic ops.\nroot *kernfs.Dentry\n+ // effectiveRoot is the initial cgroup new tasks are created in. Unless\n+ // overwritten by internal mount options, root == effectiveRoot. If\n+ // effectiveRoot != root, an extra reference is held on effectiveRoot for\n+ // the lifetime of the filesystem.\n+ effectiveRoot *kernfs.Dentry\n// tasksMu serializes task membership changes across all cgroups within a\n// filesystem.\n@@ -229,6 +238,9 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nfs := vfsfs.Impl().(*filesystem)\nctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: mounting new view to hierarchy %v\", fs.hierarchyID)\nfs.root.IncRef()\n+ if fs.effectiveRoot != fs.root {\n+ fs.effectiveRoot.IncRef()\n+ }\nreturn vfsfs, fs.root.VFSDentry(), nil\n}\n@@ -245,8 +257,8 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nvar defaults map[string]int64\nif opts.InternalData != nil {\n- ctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: default control values: %v\", defaults)\ndefaults = opts.InternalData.(*InternalData).DefaultControlValues\n+ ctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: default control values: %v\", defaults)\n}\nfor _, ty := range wantControllers {\n@@ -286,6 +298,14 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nvar rootD kernfs.Dentry\nrootD.InitRoot(&fs.Filesystem, root)\nfs.root = &rootD\n+ fs.effectiveRoot = fs.root\n+\n+ if err := fs.prepareInitialCgroup(ctx, vfsObj, opts); err != nil {\n+ ctx.Warningf(\"cgroupfs.FilesystemType.GetFilesystem: failed to prepare initial cgroup: %v\", err)\n+ rootD.DecRef(ctx)\n+ fs.VFSFilesystem().DecRef(ctx)\n+ return nil, nil, err\n+ }\n// Register controllers. The registry may be modified concurrently, so if we\n// get an error, we raced with someone else who registered the same\n@@ -303,10 +323,47 @@ func (fsType FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\nreturn fs.VFSFilesystem(), rootD.VFSDentry(), nil\n}\n+// prepareInitialCgroup creates the initial cgroup according to opts. An initial\n+// cgroup is optional, and if not specified, this function is a no-op.\n+func (fs *filesystem) prepareInitialCgroup(ctx context.Context, vfsObj *vfs.VirtualFilesystem, opts vfs.GetFilesystemOptions) error {\n+ if opts.InternalData == nil {\n+ return nil\n+ }\n+ initPathStr := opts.InternalData.(*InternalData).InitialCgroupPath\n+ if initPathStr == \"\" {\n+ return nil\n+ }\n+ ctx.Debugf(\"cgroupfs.FilesystemType.GetFilesystem: initial cgroup path: %v\", initPathStr)\n+ initPath := fspath.Parse(initPathStr)\n+ if !initPath.Absolute || !initPath.HasComponents() {\n+ ctx.Warningf(\"cgroupfs.FilesystemType.GetFilesystem: initial cgroup path invalid: %+v\", initPath)\n+ return linuxerr.EINVAL\n+ }\n+\n+ // Have initial cgroup target, create the tree.\n+ cgDir := fs.root.Inode().(*cgroupInode)\n+ for pit := initPath.Begin; pit.Ok(); pit = pit.Next() {\n+ cgDirI, err := cgDir.NewDir(ctx, pit.String(), vfs.MkdirOptions{})\n+ if err != nil {\n+ return err\n+ }\n+ cgDir = cgDirI.(*cgroupInode)\n+ }\n+\n+ // Walk to target dentry.\n+ initDentry, err := fs.root.WalkDentryTree(ctx, vfsObj, initPath)\n+ if err != nil {\n+ ctx.Warningf(\"cgroupfs.FilesystemType.GetFilesystem: initial cgroup dentry not found: %v\", err)\n+ return linuxerr.ENOENT\n+ }\n+ fs.effectiveRoot = initDentry // Reference from WalkDentryTree transferred here.\n+ return nil\n+}\n+\nfunc (fs *filesystem) rootCgroup() kernel.Cgroup {\nreturn kernel.Cgroup{\n- Dentry: fs.root,\n- CgroupImpl: fs.root.Inode().(kernel.CgroupImpl),\n+ Dentry: fs.effectiveRoot,\n+ CgroupImpl: fs.effectiveRoot.Inode().(kernel.CgroupImpl),\n}\n}\n@@ -320,6 +377,10 @@ func (fs *filesystem) Release(ctx context.Context) {\nr.Unregister(fs.hierarchyID)\n}\n+ if fs.root != fs.effectiveRoot {\n+ fs.effectiveRoot.DecRef(ctx)\n+ }\n+\nfs.Filesystem.VFSFilesystem().VirtualFilesystem().PutAnonBlockDevMinor(fs.devMinor)\nfs.Filesystem.Release(ctx)\n}\n@@ -346,15 +407,18 @@ func (*implStatFS) StatFS(context.Context, *vfs.Filesystem) (linux.Statfs, error\n//\n// +stateify savable\ntype dir struct {\n- dirRefs\n+ kernfs.InodeNoopRefCount\nkernfs.InodeAlwaysValid\nkernfs.InodeAttrs\nkernfs.InodeNotSymlink\n- kernfs.InodeDirectoryNoNewChildren // TODO(b/183137098): Implement mkdir.\n+ kernfs.InodeDirectoryNoNewChildren\nkernfs.OrderedChildren\nimplStatFS\nlocks vfs.FileLocks\n+\n+ fs *filesystem // Immutable.\n+ cgi *cgroupInode // Immutable.\n}\n// Keep implements kernfs.Inode.Keep.\n@@ -378,9 +442,100 @@ func (d *dir) Open(ctx context.Context, rp *vfs.ResolvingPath, kd *kernfs.Dentry\nreturn fd.VFSFileDescription(), nil\n}\n-// DecRef implements kernfs.Inode.DecRef.\n-func (d *dir) DecRef(ctx context.Context) {\n- d.dirRefs.DecRef(func() { d.Destroy(ctx) })\n+// NewDir implements kernfs.Inode.NewDir.\n+func (d *dir) NewDir(ctx context.Context, name string, opts vfs.MkdirOptions) (kernfs.Inode, error) {\n+ // \"Do not accept '\\n' to prevent making /proc/<pid>/cgroup unparsable.\"\n+ // -- Linux, kernel/cgroup.c:cgroup_mkdir().\n+ if strings.Contains(name, \"\\n\") {\n+ return nil, linuxerr.EINVAL\n+ }\n+ return d.OrderedChildren.Inserter(name, func() kernfs.Inode {\n+ d.IncLinks(1)\n+ return d.fs.newCgroupInode(ctx, auth.CredentialsFromContext(ctx))\n+ })\n+}\n+\n+// Rename implements kernfs.Inode.Rename. Cgroupfs only allows renaming of\n+// cgroup directories, and the rename may only change the name within the same\n+// parent. See linux, kernel/cgroup.c:cgroup_rename().\n+func (d *dir) Rename(ctx context.Context, oldname, newname string, child, dst kernfs.Inode) error {\n+ if _, ok := child.(*cgroupInode); !ok {\n+ // Not a cgroup directory. Control files are backed by different types.\n+ return linuxerr.ENOTDIR\n+ }\n+\n+ dstCGInode, ok := dst.(*cgroupInode)\n+ if !ok {\n+ // Not a cgroup inode, so definitely can't be *this* inode.\n+ return linuxerr.EIO\n+ }\n+ // Note: We're intentionally comparing addresses, since two different dirs\n+ // could plausibly be identical in memory, but would occupy different\n+ // locations in memory.\n+ if d != &dstCGInode.dir {\n+ // Destination dir is a different cgroup inode. Cross directory renames\n+ // aren't allowed.\n+ return linuxerr.EIO\n+ }\n+\n+ // Rename moves oldname to newname within d. Proceed.\n+ return d.OrderedChildren.Rename(ctx, oldname, newname, child, dst)\n+}\n+\n+// Unlink implements kernfs.Inode.Unlink. Cgroupfs disallows unlink, as the only\n+// files in the filesystem are control files, which can't be deleted.\n+func (d *dir) Unlink(ctx context.Context, name string, child kernfs.Inode) error {\n+ return linuxerr.EPERM\n+}\n+\n+// hasChildrenLocked returns whether the cgroup dir contains any objects that\n+// prevent it from being deleted.\n+func (d *dir) hasChildrenLocked() bool {\n+ // Subdirs take a link on the parent, so checks if there are any direct\n+ // children cgroups. Exclude the dir's self link and the link from \".\".\n+ if d.InodeAttrs.Links()-2 > 0 {\n+ return true\n+ }\n+ return len(d.cgi.ts) > 0\n+}\n+\n+// HasChildren implements kernfs.Inode.HasChildren.\n+//\n+// The empty check for a cgroupfs directory is unlike a regular directory since\n+// a cgroupfs directory will always have control files. A cgroupfs directory can\n+// be deleted if cgroup contains no tasks and has no sub-cgroups.\n+func (d *dir) HasChildren() bool {\n+ d.fs.tasksMu.RLock()\n+ defer d.fs.tasksMu.RUnlock()\n+ return d.hasChildrenLocked()\n+}\n+\n+// RmDir implements kernfs.Inode.RmDir.\n+func (d *dir) RmDir(ctx context.Context, name string, child kernfs.Inode) error {\n+ // Unlike a normal directory, we need to recheck if d is empty again, since\n+ // vfs/kernfs can't stop tasks from entering or leaving the cgroup.\n+ d.fs.tasksMu.RLock()\n+ defer d.fs.tasksMu.RUnlock()\n+\n+ cgi, ok := child.(*cgroupInode)\n+ if !ok {\n+ return linuxerr.ENOTDIR\n+ }\n+ if cgi.dir.hasChildrenLocked() {\n+ return linuxerr.ENOTEMPTY\n+ }\n+\n+ // Disallow deletion of the effective root cgroup.\n+ if cgi == d.fs.effectiveRoot.Inode().(*cgroupInode) {\n+ ctx.Warningf(\"Cannot delete initial cgroup for new tasks %q\", d.fs.effectiveRoot.FSLocalPath())\n+ return linuxerr.EBUSY\n+ }\n+\n+ err := d.OrderedChildren.RmDir(ctx, name, child)\n+ if err == nil {\n+ d.InodeAttrs.DecLinks()\n+ }\n+ return err\n}\n// controllerFile represents a generic control file that appears within a cgroup\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"new_path": "pkg/sentry/fsimpl/kernfs/BUILD",
"diff": "@@ -137,6 +137,7 @@ go_test(\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n\"//pkg/errors/linuxerr\",\n+ \"//pkg/fspath\",\n\"//pkg/log\",\n\"//pkg/refs\",\n\"//pkg/refsvfs2\",\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": "@@ -26,7 +26,6 @@ import (\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n- \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// InodeNoopRefCount partially implements the Inode interface, specifically the\n@@ -234,6 +233,11 @@ func (a *InodeAttrs) Mode() linux.FileMode {\nreturn linux.FileMode(atomic.LoadUint32(&a.mode))\n}\n+// Links returns the link count.\n+func (a *InodeAttrs) Links() uint32 {\n+ return atomic.LoadUint32(&a.nlink)\n+}\n+\n// TouchAtime updates a.atime to the current time.\nfunc (a *InodeAttrs) TouchAtime(ctx context.Context, mnt *vfs.Mount) {\nif mnt.Flags.NoATime || mnt.ReadOnly() {\n@@ -289,7 +293,7 @@ func (a *InodeAttrs) SetStat(ctx context.Context, fs *vfs.Filesystem, creds *aut\nreturn linuxerr.EPERM\n}\nif opts.Stat.Mask&linux.STATX_SIZE != 0 && a.Mode().IsDir() {\n- return syserror.EISDIR\n+ return linuxerr.EISDIR\n}\nif err := vfs.CheckSetStat(ctx, creds, &opts, a.Mode(), auth.KUID(atomic.LoadUint32(&a.uid)), auth.KGID(atomic.LoadUint32(&a.gid))); err != nil {\nreturn err\n@@ -475,7 +479,7 @@ func (o *OrderedChildren) Lookup(ctx context.Context, name string) (Inode, error\ns, ok := o.set[name]\nif !ok {\n- return nil, syserror.ENOENT\n+ return nil, linuxerr.ENOENT\n}\ns.inode.IncRef() // This ref is passed to the dentry upon creation via Init.\n@@ -502,6 +506,30 @@ func (o *OrderedChildren) Insert(name string, child Inode) error {\nreturn o.insert(name, child, false)\n}\n+// Inserter is like Insert, but obtains the child to insert by calling\n+// makeChild. makeChild is only called if the insert will succeed. This allows\n+// the caller to atomically check and insert a child without having to\n+// clean up the child on failure.\n+func (o *OrderedChildren) Inserter(name string, makeChild func() Inode) (Inode, error) {\n+ o.mu.Lock()\n+ defer o.mu.Unlock()\n+ if _, ok := o.set[name]; ok {\n+ return nil, linuxerr.EEXIST\n+ }\n+\n+ // Note: We must not fail after we call makeChild().\n+\n+ child := makeChild()\n+ s := &slot{\n+ name: name,\n+ inode: child,\n+ static: false,\n+ }\n+ o.order.PushBack(s)\n+ o.set[name] = s\n+ return child, nil\n+}\n+\n// insert inserts child into o.\n//\n// Precondition: Caller must be holding a ref on child if static is true.\n@@ -559,7 +587,7 @@ func (o *OrderedChildren) replaceChildLocked(ctx context.Context, name string, n\nfunc (o *OrderedChildren) checkExistingLocked(name string, child Inode) error {\ns, ok := o.set[name]\nif !ok {\n- return syserror.ENOENT\n+ return linuxerr.ENOENT\n}\nif s.inode != child {\npanic(fmt.Sprintf(\"Inode doesn't match what kernfs thinks! OrderedChild: %+v, kernfs: %+v\", s.inode, child))\n@@ -746,5 +774,5 @@ type InodeNoStatFS struct{}\n// StatFS implements Inode.StatFS.\nfunc (*InodeNoStatFS) StatFS(context.Context, *vfs.Filesystem) (linux.Statfs, error) {\n- return linux.Statfs{}, syserror.ENOSYS\n+ return linux.Statfs{}, linuxerr.ENOSYS\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go",
"diff": "@@ -66,6 +66,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n)\n// Filesystem mostly implements vfs.FilesystemImpl for a generic in-memory\n@@ -542,6 +543,63 @@ func (d *Dentry) FSLocalPath() string {\nreturn b.String()\n}\n+// WalkDentryTree traverses p in the dentry tree for this filesystem. Note that\n+// this only traverses the dentry tree and is not a general path traversal. No\n+// symlinks and dynamic children are resolved, and no permission checks are\n+// performed. The caller is responsible for ensuring the returned Dentry exists\n+// for an appropriate lifetime.\n+//\n+// p is interpreted starting at d, and may be absolute or relative (absolute vs\n+// relative paths both refer to the same target here, since p is absolute from\n+// d). p may contain \".\" and \"..\", but will not allow traversal above d (similar\n+// to \"..\" at the root dentry).\n+//\n+// This is useful for filesystem internals, where the filesystem may not be\n+// mounted yet. For a mounted filesystem, use GetDentryAt.\n+func (d *Dentry) WalkDentryTree(ctx context.Context, vfsObj *vfs.VirtualFilesystem, p fspath.Path) (*Dentry, error) {\n+ d.fs.mu.RLock()\n+ defer d.fs.processDeferredDecRefs(ctx)\n+ defer d.fs.mu.RUnlock()\n+\n+ target := d\n+\n+ for pit := p.Begin; pit.Ok(); pit = pit.Next() {\n+ pc := pit.String()\n+\n+ switch {\n+ case target == nil:\n+ return nil, syserror.ENOENT\n+ case pc == \".\":\n+ // No-op, consume component and continue.\n+ case pc == \"..\":\n+ if target == d {\n+ // Don't let .. traverse above the start point of the walk.\n+ continue\n+ }\n+ target = target.parent\n+ // Parent doesn't need revalidation since we revalidated it on the\n+ // way to the child, and we're still holding fs.mu.\n+ default:\n+ var err error\n+\n+ d.dirMu.Lock()\n+ target, err = d.fs.revalidateChildLocked(ctx, vfsObj, target, pc, target.children[pc])\n+ d.dirMu.Unlock()\n+\n+ if err != nil {\n+ return nil, err\n+ }\n+ }\n+ }\n+\n+ if target == nil {\n+ return nil, syserror.ENOENT\n+ }\n+\n+ target.IncRef()\n+ return target, nil\n+}\n+\n// The Inode interface maps filesystem-level operations that operate on paths to\n// equivalent operations on specific filesystem nodes.\n//\n@@ -667,12 +725,15 @@ type inodeDirectory interface {\n// RmDir removes an empty child directory from this directory\n// inode. Implementations must update the parent directory's link count,\n// if required. Implementations are not responsible for checking that child\n- // is a directory, checking for an empty directory.\n+ // is a directory, or checking for an empty directory.\nRmDir(ctx context.Context, name string, child Inode) error\n// Rename is called on the source directory containing an inode being\n- // renamed. child should point to the resolved child in the source\n- // directory.\n+ // renamed. child points to the resolved child in the source directory.\n+ // dstDir is guaranteed to be a directory inode.\n+ //\n+ // On a successful call to Rename, the caller updates the dentry tree to\n+ // reflect the name change.\n//\n// Precondition: Caller must serialize concurrent calls to Rename.\nRename(ctx context.Context, oldname, newname string, child, dstDir Inode) error\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n@@ -346,3 +347,63 @@ func TestDirFDIterDirents(t *testing.T) {\n\"file1\": linux.DT_REG,\n})\n}\n+\n+func TestDirWalkDentryTree(t *testing.T) {\n+ sys := newTestSystem(t, func(ctx context.Context, creds *auth.Credentials, fs *filesystem) kernfs.Inode {\n+ return fs.newDir(ctx, creds, 0755, map[string]kernfs.Inode{\n+ \"dir1\": fs.newDir(ctx, creds, 0755, nil),\n+ \"dir2\": fs.newDir(ctx, creds, 0755, map[string]kernfs.Inode{\n+ \"file1\": fs.newFile(ctx, creds, staticFileContent),\n+ \"dir3\": fs.newDir(ctx, creds, 0755, nil),\n+ }),\n+ })\n+ })\n+ defer sys.Destroy()\n+\n+ testWalk := func(from *kernfs.Dentry, getDentryPath, walkPath string, expectedErr error) {\n+ var d *kernfs.Dentry\n+ if getDentryPath != \"\" {\n+ pop := sys.PathOpAtRoot(getDentryPath)\n+ vd := sys.GetDentryOrDie(pop)\n+ defer vd.DecRef(sys.Ctx)\n+ d = vd.Dentry().Impl().(*kernfs.Dentry)\n+ }\n+\n+ match, err := from.WalkDentryTree(sys.Ctx, sys.VFS, fspath.Parse(walkPath))\n+ if err == nil {\n+ defer match.DecRef(sys.Ctx)\n+ }\n+\n+ if err != expectedErr {\n+ t.Fatalf(\"WalkDentryTree from %q to %q (with expected error: %v) unexpected error, want: %v, got: %v\", from.FSLocalPath(), walkPath, expectedErr, expectedErr, err)\n+ }\n+ if expectedErr != nil {\n+ return\n+ }\n+\n+ if d != match {\n+ t.Fatalf(\"WalkDentryTree from %q to %q (with expected error: %v) found unexpected dentry; want: %v, got: %v\", from.FSLocalPath(), walkPath, expectedErr, d, match)\n+ }\n+ }\n+\n+ rootD := sys.Root.Dentry().Impl().(*kernfs.Dentry)\n+\n+ testWalk(rootD, \"dir1\", \"/dir1\", nil)\n+ testWalk(rootD, \"\", \"/dir-non-existent\", linuxerr.ENOENT)\n+ testWalk(rootD, \"\", \"/dir1/child-non-existent\", linuxerr.ENOENT)\n+ testWalk(rootD, \"\", \"/dir2/inner-non-existent/dir3\", linuxerr.ENOENT)\n+\n+ testWalk(rootD, \"dir2/dir3\", \"/dir2/../dir2/dir3\", nil)\n+ testWalk(rootD, \"dir2/dir3\", \"/dir2/././dir3\", nil)\n+ testWalk(rootD, \"dir2/dir3\", \"/dir2/././dir3/.././dir3\", nil)\n+\n+ pop := sys.PathOpAtRoot(\"dir2\")\n+ dir2VD := sys.GetDentryOrDie(pop)\n+ defer dir2VD.DecRef(sys.Ctx)\n+ dir2D := dir2VD.Dentry().Impl().(*kernfs.Dentry)\n+\n+ testWalk(dir2D, \"dir2/dir3\", \"/dir3\", nil)\n+ testWalk(dir2D, \"dir2/dir3\", \"/../../../dir3\", nil)\n+ testWalk(dir2D, \"dir2/file1\", \"/file1\", nil)\n+ testWalk(dir2D, \"dir2/file1\", \"file1\", nil)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/cgroup.go",
"new_path": "pkg/sentry/kernel/cgroup.go",
"diff": "@@ -196,6 +196,7 @@ func (r *CgroupRegistry) FindHierarchy(ctypes []CgroupControllerType) *vfs.Files\n// uniqueness of controllers enforced by Register, drop the\n// dying hierarchy now. The eventual unregister by the FS\n// teardown will become a no-op.\n+ r.unregisterLocked(h.id)\nreturn nil\n}\nreturn h.fs\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/cgroup.cc",
"new_path": "test/syscalls/linux/cgroup.cc",
"diff": "@@ -279,6 +279,23 @@ TEST(Cgroup, UnmountRepeated) {\nEXPECT_THAT(umount(c.Path().c_str()), SyscallFailsWithErrno(EINVAL));\n}\n+TEST(Cgroup, Create) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"\"));\n+ ASSERT_NO_ERRNO(c.CreateChild(\"child1\"));\n+ EXPECT_TRUE(ASSERT_NO_ERRNO_AND_VALUE(Exists(c.Path())));\n+}\n+\n+TEST(Cgroup, SubcontainerInitiallyEmpty) {\n+ SKIP_IF(!CgroupsAvailable());\n+ Mounter m(ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()));\n+ Cgroup c = ASSERT_NO_ERRNO_AND_VALUE(m.MountCgroupfs(\"\"));\n+ Cgroup child = ASSERT_NO_ERRNO_AND_VALUE(c.CreateChild(\"child1\"));\n+ auto procs = ASSERT_NO_ERRNO_AND_VALUE(child.Procs());\n+ EXPECT_TRUE(procs.empty());\n+}\n+\nTEST(MemoryCgroup, MemoryUsageInBytes) {\nSKIP_IF(!CgroupsAvailable());\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/cgroup_util.cc",
"new_path": "test/util/cgroup_util.cc",
"diff": "namespace gvisor {\nnamespace testing {\n-Cgroup::Cgroup(std::string_view path) : cgroup_path_(path) {\n+Cgroup::Cgroup(absl::string_view path) : cgroup_path_(path) {\nid_ = ++Cgroup::next_id_;\nstd::cerr << absl::StreamFormat(\"[cg#%d] <= %s\", id_, cgroup_path_)\n<< std::endl;\n}\n+PosixErrorOr<Cgroup> Cgroup::RecursivelyCreate(absl::string_view path) {\n+ RETURN_IF_ERRNO(RecursivelyCreateDir(path));\n+ return Cgroup(path);\n+}\n+\n+PosixErrorOr<Cgroup> Cgroup::Create(absl::string_view path) {\n+ RETURN_IF_ERRNO(Mkdir(path));\n+ return Cgroup(path);\n+}\n+\n+PosixErrorOr<Cgroup> Cgroup::CreateChild(absl::string_view name) const {\n+ return Cgroup::Create(JoinPath(Path(), name));\n+}\n+\nPosixErrorOr<std::string> Cgroup::ReadControlFile(\nabsl::string_view name) const {\nstd::string buf;\n@@ -93,7 +107,7 @@ PosixErrorOr<absl::flat_hash_set<pid_t>> Cgroup::ParsePIDList(\nabsl::string_view data) const {\nabsl::flat_hash_set<pid_t> res;\nstd::vector<absl::string_view> lines = absl::StrSplit(data, '\\n');\n- for (const std::string_view& line : lines) {\n+ for (const absl::string_view& line : lines) {\nif (line.empty()) {\ncontinue;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/cgroup_util.h",
"new_path": "test/util/cgroup_util.h",
"diff": "@@ -34,8 +34,20 @@ class Cgroup {\nuint64_t id() const { return id_; }\n+ // RecursivelyCreate creates cgroup specified by path, including all\n+ // components leading up to path. Path should end inside a cgroupfs mount. If\n+ // path already exists, RecursivelyCreate does nothing and silently succeeds.\n+ static PosixErrorOr<Cgroup> RecursivelyCreate(std::string_view path);\n+\n+ // Creates a new cgroup at path. The parent directory must exist and be a\n+ // cgroupfs directory.\n+ static PosixErrorOr<Cgroup> Create(std::string_view path);\n+\nconst std::string& Path() const { return cgroup_path_; }\n+ // Creates a child cgroup under this cgroup with the given name.\n+ PosixErrorOr<Cgroup> CreateChild(std::string_view name) const;\n+\nstd::string Relpath(absl::string_view leaf) const {\nreturn JoinPath(cgroup_path_, leaf);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/fs_util.cc",
"new_path": "test/util/fs_util.cc",
"diff": "@@ -201,7 +201,8 @@ PosixError UnlinkAt(const FileDescriptor& dfd, absl::string_view path,\nPosixError Mkdir(absl::string_view path, int mode) {\nint res = mkdir(std::string(path).c_str(), mode);\nif (res < 0) {\n- return PosixError(errno, absl::StrCat(\"mkdir \", path, \" mode \", mode));\n+ return PosixError(errno,\n+ absl::StrFormat(\"mkdir \\\"%s\\\" mode %#o\", path, mode));\n}\nreturn NoError();\n"
}
] | Go | Apache License 2.0 | google/gvisor | Initial cgroupfs support for subcontainers
Allow creation and management of subcontainers through cgroupfs
directory syscalls. Also add a mechanism to specify a default root
container to start new jobs in.
This implements the filesystem support for subcontainers, but doesn't
implement hierarchical resource accounting or task migration.
PiperOrigin-RevId: 390254870 |
260,004 | 11.08.2021 18:18:36 | 25,200 | d51bc877f40d2acbf5b83895f636186c87463ab1 | Run packet socket tests on Fuchsia
+ Do not check for CAP_NET_RAW on Fuchsia
Fuchsia does not support capabilities the same way Linux does. Instead
emulate the check for CAP_NET_RAW by checking if a packet socket may
be created. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -7,6 +7,8 @@ package(\nexports_files(\n[\n+ \"packet_socket.cc\",\n+ \"packet_socket_raw.cc\",\n\"raw_socket.cc\",\n\"raw_socket_hdrincl.cc\",\n\"raw_socket_icmp.cc\",\n@@ -1446,6 +1448,7 @@ cc_binary(\ndeps = [\n\":unix_domain_socket_test_util\",\n\"//test/util:capability_util\",\n+ \"//test/util:cleanup\",\n\"//test/util:file_descriptor\",\n\"//test/util:socket_util\",\n\"@com_google_absl//absl/base:core_headers\",\n@@ -1464,6 +1467,7 @@ cc_binary(\ndeps = [\n\":unix_domain_socket_test_util\",\n\"//test/util:capability_util\",\n+ \"//test/util:cleanup\",\n\"//test/util:file_descriptor\",\n\"//test/util:socket_util\",\n\"@com_google_absl//absl/base:core_headers\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "#include <arpa/inet.h>\n#include <ifaddrs.h>\n-#include <linux/capability.h>\n-#include <linux/if_arp.h>\n-#include <linux/if_packet.h>\n#include <net/ethernet.h>\n+#include <net/if.h>\n+#include <net/if_arp.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/udp.h>\n+#include <netpacket/packet.h>\n#include <poll.h>\n#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include \"absl/base/internal/endian.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/socket_util.h\"\n#include \"test/util/test_util.h\"\n@@ -85,7 +86,7 @@ void SendUDPMessage(int sock) {\n// Send an IP packet and make sure ETH_P_<something else> doesn't pick it up.\nTEST(BasicCookedPacketTest, WrongType) {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, ETH_P_PUP),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -123,7 +124,7 @@ class CookedPacketTest : public ::testing::TestWithParam<int> {\n};\nvoid CookedPacketTest::SetUp() {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -149,7 +150,7 @@ void CookedPacketTest::SetUp() {\nvoid CookedPacketTest::TearDown() {\n// TearDown will be run even if we skip the test.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_raw.cc",
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "// limitations under the License.\n#include <arpa/inet.h>\n-#include <linux/capability.h>\n-#include <linux/filter.h>\n-#include <linux/if_arp.h>\n-#include <linux/if_packet.h>\n#include <net/ethernet.h>\n+#include <net/if.h>\n+#include <net/if_arp.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/udp.h>\n+#include <netpacket/packet.h>\n#include <poll.h>\n#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include \"absl/base/internal/endian.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/cleanup.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/socket_util.h\"\n#include \"test/util/test_util.h\"\n@@ -100,7 +100,7 @@ class RawPacketTest : public ::testing::TestWithParam<int> {\n};\nvoid RawPacketTest::SetUp() {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nASSERT_THAT(socket(AF_PACKET, SOCK_RAW, htons(GetParam())),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -150,7 +150,7 @@ void RawPacketTest::SetUp() {\nvoid RawPacketTest::TearDown() {\n// TearDown will be run even if we skip the test.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n}\n}\n@@ -340,7 +340,7 @@ TEST_P(RawPacketTest, Send) {\n// Check that setting SO_RCVBUF below min is clamped to the minimum\n// receive buffer size.\nTEST_P(RawPacketTest, SetSocketRecvBufBelowMin) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\n// Discover minimum receive buf size by trying to set it to zero.\n// See:\n@@ -373,7 +373,7 @@ TEST_P(RawPacketTest, SetSocketRecvBufBelowMin) {\n// Check that setting SO_RCVBUF above max is clamped to the maximum\n// receive buffer size.\nTEST_P(RawPacketTest, SetSocketRecvBufAboveMax) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\n// Discover max buf size by trying to set the largest possible buffer size.\nconstexpr int kRcvBufSz = 0xffffffff;\n@@ -400,7 +400,7 @@ TEST_P(RawPacketTest, SetSocketRecvBufAboveMax) {\n// Check that setting SO_RCVBUF min <= kRcvBufSz <= max is honored.\nTEST_P(RawPacketTest, SetSocketRecvBuf) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint max = 0;\nint min = 0;\n@@ -449,7 +449,7 @@ TEST_P(RawPacketTest, SetSocketRecvBuf) {\n// Check that setting SO_SNDBUF below min is clamped to the minimum\n// receive buffer size.\nTEST_P(RawPacketTest, SetSocketSendBufBelowMin) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\n// Discover minimum buffer size by trying to set it to zero.\nconstexpr int kSndBufSz = 0;\n@@ -480,7 +480,7 @@ TEST_P(RawPacketTest, SetSocketSendBufBelowMin) {\n// Check that setting SO_SNDBUF above max is clamped to the maximum\n// send buffer size.\nTEST_P(RawPacketTest, SetSocketSendBufAboveMax) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\n// Discover maximum buffer size by trying to set it to a large value.\nconstexpr int kSndBufSz = 0xffffffff;\n@@ -507,7 +507,7 @@ TEST_P(RawPacketTest, SetSocketSendBufAboveMax) {\n// Check that setting SO_SNDBUF min <= kSndBufSz <= max is honored.\nTEST_P(RawPacketTest, SetSocketSendBuf) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint max = 0;\nint min = 0;\n@@ -551,7 +551,7 @@ TEST_P(RawPacketTest, SetSocketSendBuf) {\n}\nTEST_P(RawPacketTest, GetSocketError) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint val = 0;\nsocklen_t val_len = sizeof(val);\n@@ -561,7 +561,7 @@ TEST_P(RawPacketTest, GetSocketError) {\n}\nTEST_P(RawPacketTest, GetSocketErrorBind) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\n{\n// Bind to the loopback device.\n@@ -627,7 +627,7 @@ TEST_P(RawPacketTest, SetSocketDetachFilterNoInstalledFilter) {\n}\nTEST_P(RawPacketTest, GetSocketDetachFilter) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint val = 0;\nsocklen_t val_len = sizeof(val);\n@@ -636,7 +636,7 @@ TEST_P(RawPacketTest, GetSocketDetachFilter) {\n}\nTEST_P(RawPacketTest, SetAndGetSocketLinger) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint level = SOL_SOCKET;\nint type = SO_LINGER;\n@@ -657,7 +657,7 @@ TEST_P(RawPacketTest, SetAndGetSocketLinger) {\n}\nTEST_P(RawPacketTest, GetSocketAcceptConn) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nint got = -1;\nsocklen_t length = sizeof(got);\n@@ -673,7 +673,7 @@ INSTANTIATE_TEST_SUITE_P(AllInetTests, RawPacketTest,\nclass RawPacketMsgSizeTest : public ::testing::TestWithParam<TestAddress> {};\nTEST_P(RawPacketMsgSizeTest, SendTooLong) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nTestAddress addr = GetParam().WithPort(kPort);\n@@ -690,8 +690,11 @@ TEST_P(RawPacketMsgSizeTest, SendTooLong) {\nSyscallFailsWithErrno(EMSGSIZE));\n}\n+// TODO(https://fxbug.dev/76957): Run this test on Fuchsia once splice is\n+// available.\n+#ifndef __Fuchsia__\nTEST_P(RawPacketMsgSizeTest, SpliceTooLong) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability()));\nconst char buf[65536] = {};\nint fds[2];\n@@ -718,6 +721,7 @@ TEST_P(RawPacketMsgSizeTest, SpliceTooLong) {\nEXPECT_THAT(n, SyscallSucceedsWithValue(sizeof(buf)));\n}\n}\n+#endif // __Fuchsia__\nINSTANTIATE_TEST_SUITE_P(AllRawPacketMsgSizeTest, RawPacketMsgSizeTest,\n::testing::Values(V4Loopback(), V6Loopback()));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket.cc",
"new_path": "test/syscalls/linux/raw_socket.cc",
"diff": "@@ -97,7 +97,7 @@ class RawSocketTest : public ::testing::TestWithParam<std::tuple<int, int>> {\n};\nvoid RawSocketTest::SetUp() {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nASSERT_THAT(socket(Family(), SOCK_RAW, Protocol()),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -121,7 +121,7 @@ void RawSocketTest::SetUp() {\nvoid RawSocketTest::TearDown() {\n// TearDown will be run even if we skip the test.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n}\n}\n@@ -130,7 +130,7 @@ void RawSocketTest::TearDown() {\n// BasicRawSocket::Setup creates the first one, so we only have to create one\n// more here.\nTEST_P(RawSocketTest, MultipleCreation) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint s2;\nASSERT_THAT(s2 = socket(Family(), SOCK_RAW, Protocol()), SyscallSucceeds());\n@@ -140,7 +140,7 @@ TEST_P(RawSocketTest, MultipleCreation) {\n// Test that shutting down an unconnected socket fails.\nTEST_P(RawSocketTest, FailShutdownWithoutConnect) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(shutdown(s_, SHUT_WR), SyscallFailsWithErrno(ENOTCONN));\nASSERT_THAT(shutdown(s_, SHUT_RD), SyscallFailsWithErrno(ENOTCONN));\n@@ -148,7 +148,7 @@ TEST_P(RawSocketTest, FailShutdownWithoutConnect) {\n// Shutdown is a no-op for raw sockets (and datagram sockets in general).\nTEST_P(RawSocketTest, ShutdownWriteNoop) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -163,7 +163,7 @@ TEST_P(RawSocketTest, ShutdownWriteNoop) {\n// Shutdown is a no-op for raw sockets (and datagram sockets in general).\nTEST_P(RawSocketTest, ShutdownReadNoop) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -180,14 +180,14 @@ TEST_P(RawSocketTest, ShutdownReadNoop) {\n// Test that listen() fails.\nTEST_P(RawSocketTest, FailListen) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(listen(s_, 1), SyscallFailsWithErrno(ENOTSUP));\n}\n// Test that accept() fails.\nTEST_P(RawSocketTest, FailAccept) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr saddr;\nsocklen_t addrlen;\n@@ -195,7 +195,7 @@ TEST_P(RawSocketTest, FailAccept) {\n}\nTEST_P(RawSocketTest, BindThenGetSockName) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&addr_);\nASSERT_THAT(bind(s_, addr, AddrLen()), SyscallSucceeds());\n@@ -219,7 +219,7 @@ TEST_P(RawSocketTest, BindThenGetSockName) {\n}\nTEST_P(RawSocketTest, ConnectThenGetSockName) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr* addr = reinterpret_cast<struct sockaddr*>(&addr_);\nASSERT_THAT(connect(s_, addr, AddrLen()), SyscallSucceeds());\n@@ -244,7 +244,7 @@ TEST_P(RawSocketTest, ConnectThenGetSockName) {\n// Test that getpeername() returns nothing before connect().\nTEST_P(RawSocketTest, FailGetPeerNameBeforeConnect) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr saddr;\nsocklen_t addrlen = sizeof(saddr);\n@@ -254,7 +254,7 @@ TEST_P(RawSocketTest, FailGetPeerNameBeforeConnect) {\n// Test that getpeername() returns something after connect().\nTEST_P(RawSocketTest, GetPeerName) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -268,7 +268,7 @@ TEST_P(RawSocketTest, GetPeerName) {\n// Test that the socket is writable immediately.\nTEST_P(RawSocketTest, PollWritableImmediately) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct pollfd pfd = {};\npfd.fd = s_;\n@@ -278,7 +278,7 @@ TEST_P(RawSocketTest, PollWritableImmediately) {\n// Test that the socket isn't readable before receiving anything.\nTEST_P(RawSocketTest, PollNotReadableInitially) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Try to receive data with MSG_DONTWAIT, which returns immediately if there's\n// nothing to be read.\n@@ -289,7 +289,7 @@ TEST_P(RawSocketTest, PollNotReadableInitially) {\n// Test that the socket becomes readable once something is written to it.\nTEST_P(RawSocketTest, PollTriggeredOnWrite) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Write something so that there's data to be read.\n// Arbitrary.\n@@ -304,7 +304,7 @@ TEST_P(RawSocketTest, PollTriggeredOnWrite) {\n// Test that we can connect() to a valid IP (loopback).\nTEST_P(RawSocketTest, ConnectToLoopback) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -313,7 +313,7 @@ TEST_P(RawSocketTest, ConnectToLoopback) {\n// Test that calling send() without connect() fails.\nTEST_P(RawSocketTest, SendWithoutConnectFails) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Arbitrary.\nconstexpr char kBuf[] = \"Endgame was good\";\n@@ -323,7 +323,7 @@ TEST_P(RawSocketTest, SendWithoutConnectFails) {\n// Wildcard Bind.\nTEST_P(RawSocketTest, BindToWildcard) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr_storage addr;\naddr = {};\n@@ -344,16 +344,15 @@ TEST_P(RawSocketTest, BindToWildcard) {\n// Bind to localhost.\nTEST_P(RawSocketTest, BindToLocalhost) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n- ASSERT_THAT(\n- bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n+ ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\nSyscallSucceeds());\n}\n// Bind to a different address.\nTEST_P(RawSocketTest, BindToInvalid) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nstruct sockaddr_storage bind_addr = addr_;\nif (Family() == AF_INET) {\n@@ -365,13 +364,14 @@ TEST_P(RawSocketTest, BindToInvalid) {\nmemset(&sin6->sin6_addr.s6_addr, 0, sizeof(sin6->sin6_addr.s6_addr));\nsin6->sin6_addr.s6_addr[0] = 1; // 1: - An address that we can't bind to.\n}\n- ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&bind_addr),\n- AddrLen()), SyscallFailsWithErrno(EADDRNOTAVAIL));\n+ ASSERT_THAT(\n+ bind(s_, reinterpret_cast<struct sockaddr*>(&bind_addr), AddrLen()),\n+ SyscallFailsWithErrno(EADDRNOTAVAIL));\n}\n// Send and receive an packet.\nTEST_P(RawSocketTest, SendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Arbitrary.\nconstexpr char kBuf[] = \"TB12\";\n@@ -386,7 +386,7 @@ TEST_P(RawSocketTest, SendAndReceive) {\n// We should be able to create multiple raw sockets for the same protocol and\n// receive the same packet on both.\nTEST_P(RawSocketTest, MultipleSocketReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint s2;\nASSERT_THAT(s2 = socket(Family(), SOCK_RAW, Protocol()), SyscallSucceeds());\n@@ -401,11 +401,11 @@ TEST_P(RawSocketTest, MultipleSocketReceive) {\n// Receive it on socket 2.\nstd::vector<char> recv_buf2(sizeof(kBuf) + HdrLen());\n- ASSERT_NO_FATAL_FAILURE(ReceiveBufFrom(s2, recv_buf2.data(),\n- recv_buf2.size()));\n+ ASSERT_NO_FATAL_FAILURE(\n+ ReceiveBufFrom(s2, recv_buf2.data(), recv_buf2.size()));\n- EXPECT_EQ(memcmp(recv_buf1.data() + HdrLen(),\n- recv_buf2.data() + HdrLen(), sizeof(kBuf)),\n+ EXPECT_EQ(memcmp(recv_buf1.data() + HdrLen(), recv_buf2.data() + HdrLen(),\n+ sizeof(kBuf)),\n0);\nASSERT_THAT(close(s2), SyscallSucceeds());\n@@ -413,7 +413,7 @@ TEST_P(RawSocketTest, MultipleSocketReceive) {\n// Test that connect sends packets to the right place.\nTEST_P(RawSocketTest, SendAndReceiveViaConnect) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -432,10 +432,9 @@ TEST_P(RawSocketTest, SendAndReceiveViaConnect) {\n// Bind to localhost, then send and receive packets.\nTEST_P(RawSocketTest, BindSendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n- ASSERT_THAT(\n- bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n+ ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\nSyscallSucceeds());\n// Arbitrary.\n@@ -450,10 +449,9 @@ TEST_P(RawSocketTest, BindSendAndReceive) {\n// Bind and connect to localhost and send/receive packets.\nTEST_P(RawSocketTest, BindConnectSendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n- ASSERT_THAT(\n- bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n+ ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\nSyscallSucceeds());\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -472,7 +470,7 @@ TEST_P(RawSocketTest, BindConnectSendAndReceive) {\n// Check that setting SO_RCVBUF below min is clamped to the minimum\n// receive buffer size.\nTEST_P(RawSocketTest, SetSocketRecvBufBelowMin) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Discover minimum receive buf size by trying to set it to zero.\n// See:\n@@ -505,7 +503,7 @@ TEST_P(RawSocketTest, SetSocketRecvBufBelowMin) {\n// Check that setting SO_RCVBUF above max is clamped to the maximum\n// receive buffer size.\nTEST_P(RawSocketTest, SetSocketRecvBufAboveMax) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Discover max buf size by trying to set the largest possible buffer size.\nconstexpr int kRcvBufSz = 0xffffffff;\n@@ -532,7 +530,7 @@ TEST_P(RawSocketTest, SetSocketRecvBufAboveMax) {\n// Check that setting SO_RCVBUF min <= kRcvBufSz <= max is honored.\nTEST_P(RawSocketTest, SetSocketRecvBuf) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint max = 0;\nint min = 0;\n@@ -582,7 +580,7 @@ TEST_P(RawSocketTest, SetSocketRecvBuf) {\n// Check that setting SO_SNDBUF below min is clamped to the minimum\n// receive buffer size.\nTEST_P(RawSocketTest, SetSocketSendBufBelowMin) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Discover minimum buffer size by trying to set it to zero.\nconstexpr int kSndBufSz = 0;\n@@ -613,7 +611,7 @@ TEST_P(RawSocketTest, SetSocketSendBufBelowMin) {\n// Check that setting SO_SNDBUF above max is clamped to the maximum\n// send buffer size.\nTEST_P(RawSocketTest, SetSocketSendBufAboveMax) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Discover maximum buffer size by trying to set it to a large value.\nconstexpr int kSndBufSz = 0xffffffff;\n@@ -640,7 +638,7 @@ TEST_P(RawSocketTest, SetSocketSendBufAboveMax) {\n// Check that setting SO_SNDBUF min <= kSndBufSz <= max is honored.\nTEST_P(RawSocketTest, SetSocketSendBuf) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint max = 0;\nint min = 0;\n@@ -686,10 +684,9 @@ TEST_P(RawSocketTest, SetSocketSendBuf) {\n// Test that receive buffer limits are not enforced when the recv buffer is\n// empty.\nTEST_P(RawSocketTest, RecvBufLimitsEmptyRecvBuffer) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n- ASSERT_THAT(\n- bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n+ ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\nSyscallSucceeds());\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -717,9 +714,7 @@ TEST_P(RawSocketTest, RecvBufLimitsEmptyRecvBuffer) {\n// Receive the packet and make sure it's identical.\nstd::vector<char> recv_buf(buf.size() + HdrLen());\nASSERT_NO_FATAL_FAILURE(ReceiveBuf(recv_buf.data(), recv_buf.size()));\n- EXPECT_EQ(\n- memcmp(recv_buf.data() + HdrLen(), buf.data(), buf.size()),\n- 0);\n+ EXPECT_EQ(memcmp(recv_buf.data() + HdrLen(), buf.data(), buf.size()), 0);\n}\n{\n@@ -732,9 +727,7 @@ TEST_P(RawSocketTest, RecvBufLimitsEmptyRecvBuffer) {\n// Receive the packet and make sure it's identical.\nstd::vector<char> recv_buf(buf.size() + HdrLen());\nASSERT_NO_FATAL_FAILURE(ReceiveBuf(recv_buf.data(), recv_buf.size()));\n- EXPECT_EQ(\n- memcmp(recv_buf.data() + HdrLen(), buf.data(), buf.size()),\n- 0);\n+ EXPECT_EQ(memcmp(recv_buf.data() + HdrLen(), buf.data(), buf.size()), 0);\n}\n}\n@@ -748,10 +741,9 @@ TEST_P(RawSocketTest, RecvBufLimits) {\nif (Protocol() == IPPROTO_TCP) {\nreturn;\n}\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n- ASSERT_THAT(\n- bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n+ ASSERT_THAT(bind(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\nSyscallSucceeds());\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), AddrLen()),\n@@ -812,9 +804,7 @@ TEST_P(RawSocketTest, RecvBufLimits) {\n// Receive the packet and make sure it's identical.\nstd::vector<char> recv_buf(buf.size() + HdrLen());\nASSERT_NO_FATAL_FAILURE(ReceiveBuf(recv_buf.data(), recv_buf.size()));\n- EXPECT_EQ(memcmp(recv_buf.data() + HdrLen(), buf.data(),\n- buf.size()),\n- 0);\n+ EXPECT_EQ(memcmp(recv_buf.data() + HdrLen(), buf.data(), buf.size()), 0);\n}\n// Assert that the last packet is dropped because the receive buffer should\n@@ -883,7 +873,7 @@ TEST_P(RawSocketTest, GetSocketDetachFilter) {\n// AF_INET6+SOCK_RAW+IPPROTO_RAW sockets can be created, but not written to.\nTEST(RawSocketTest, IPv6ProtoRaw) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint sock;\nASSERT_THAT(sock = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW),\n@@ -900,7 +890,7 @@ TEST(RawSocketTest, IPv6ProtoRaw) {\n}\nTEST(RawSocketTest, IPv6SendMsg) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint sock;\nASSERT_THAT(sock = socket(AF_INET6, SOCK_RAW, IPPROTO_TCP),\n@@ -928,7 +918,7 @@ TEST(RawSocketTest, IPv6SendMsg) {\n}\nTEST_P(RawSocketTest, ConnectOnIPv6Socket) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint sock;\nASSERT_THAT(sock = socket(AF_INET6, SOCK_RAW, IPPROTO_TCP),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_hdrincl.cc",
"new_path": "test/syscalls/linux/raw_socket_hdrincl.cc",
"diff": "@@ -62,7 +62,7 @@ class RawHDRINCL : public ::testing::Test {\n};\nvoid RawHDRINCL::SetUp() {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nASSERT_THAT(socket(AF_INET, SOCK_RAW, IPPROTO_RAW),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -80,7 +80,7 @@ void RawHDRINCL::SetUp() {\nvoid RawHDRINCL::TearDown() {\n// TearDown will be run even if we skip the test.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_icmp.cc",
"new_path": "test/syscalls/linux/raw_socket_icmp.cc",
"diff": "@@ -76,7 +76,7 @@ class RawSocketICMPTest : public ::testing::Test {\n};\nvoid RawSocketICMPTest::SetUp() {\n- if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nASSERT_THAT(socket(AF_INET, SOCK_RAW, IPPROTO_ICMP),\nSyscallFailsWithErrno(EPERM));\nGTEST_SKIP();\n@@ -94,7 +94,7 @@ void RawSocketICMPTest::SetUp() {\nvoid RawSocketICMPTest::TearDown() {\n// TearDown will be run even if we skip the test.\n- if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability())) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n}\n}\n@@ -102,7 +102,7 @@ void RawSocketICMPTest::TearDown() {\n// We'll only read an echo in this case, as the kernel won't respond to the\n// malformed ICMP checksum.\nTEST_F(RawSocketICMPTest, SendAndReceiveBadChecksum) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Prepare and send an ICMP packet. Use arbitrary junk for checksum, sequence,\n// and ID. None of that should matter for raw sockets - the kernel should\n@@ -131,7 +131,7 @@ TEST_F(RawSocketICMPTest, SendAndReceiveBadChecksum) {\n// Send and receive an ICMP packet.\nTEST_F(RawSocketICMPTest, SendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n// Prepare and send an ICMP packet. Use arbitrary junk for sequence and ID.\n// None of that should matter for raw sockets - the kernel should still give\n@@ -151,7 +151,7 @@ TEST_F(RawSocketICMPTest, SendAndReceive) {\n// We should be able to create multiple raw sockets for the same protocol and\n// receive the same packet on both.\nTEST_F(RawSocketICMPTest, MultipleSocketReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nFileDescriptor s2 =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP));\n@@ -214,7 +214,7 @@ TEST_F(RawSocketICMPTest, MultipleSocketReceive) {\n// A raw ICMP socket and ping socket should both receive the ICMP packets\n// intended for the ping socket.\nTEST_F(RawSocketICMPTest, RawAndPingSockets) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nFileDescriptor ping_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP));\n@@ -264,7 +264,7 @@ TEST_F(RawSocketICMPTest, RawAndPingSockets) {\n// while a ping socket should not. Neither should be able to receieve a short\n// malformed packet.\nTEST_F(RawSocketICMPTest, ShortEchoRawAndPingSockets) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nFileDescriptor ping_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP));\n@@ -305,7 +305,7 @@ TEST_F(RawSocketICMPTest, ShortEchoRawAndPingSockets) {\n// while ping socket should not.\n// Neither should be able to receieve a short malformed packet.\nTEST_F(RawSocketICMPTest, ShortEchoReplyRawAndPingSockets) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nFileDescriptor ping_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP));\n@@ -344,7 +344,7 @@ TEST_F(RawSocketICMPTest, ShortEchoReplyRawAndPingSockets) {\n// Test that connect() sends packets to the right place.\nTEST_F(RawSocketICMPTest, SendAndReceiveViaConnect) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nconnect(s_, reinterpret_cast<struct sockaddr*>(&addr_), sizeof(addr_)),\n@@ -368,7 +368,7 @@ TEST_F(RawSocketICMPTest, SendAndReceiveViaConnect) {\n// Bind to localhost, then send and receive packets.\nTEST_F(RawSocketICMPTest, BindSendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nbind(s_, reinterpret_cast<struct sockaddr*>(&addr_), sizeof(addr_)),\n@@ -391,7 +391,7 @@ TEST_F(RawSocketICMPTest, BindSendAndReceive) {\n// Bind and connect to localhost and send/receive packets.\nTEST_F(RawSocketICMPTest, BindConnectSendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nASSERT_THAT(\nbind(s_, reinterpret_cast<struct sockaddr*>(&addr_), sizeof(addr_)),\n@@ -417,7 +417,7 @@ TEST_F(RawSocketICMPTest, BindConnectSendAndReceive) {\n// Set and get SO_LINGER.\nTEST_F(RawSocketICMPTest, SetAndGetSocketLinger) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint level = SOL_SOCKET;\nint type = SO_LINGER;\n@@ -439,7 +439,7 @@ TEST_F(RawSocketICMPTest, SetAndGetSocketLinger) {\n// Test getsockopt for SO_ACCEPTCONN.\nTEST_F(RawSocketICMPTest, GetSocketAcceptConn) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\nint got = -1;\nsocklen_t length = sizeof(got);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -14,7 +14,6 @@ cc_library(\n],\nhdrs = [\n\"capability_util.h\",\n- \"fuchsia_capability_util.h\",\n\"linux_capability_util.h\",\n],\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/capability_util.h",
"new_path": "test/util/capability_util.h",
"diff": "#define GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_\n#if defined(__Fuchsia__)\n-#include \"test/util/fuchsia_capability_util.h\"\n+// Nothing to include.\n#elif defined(__linux__)\n#include \"test/util/linux_capability_util.h\"\n#else\n#error \"Unhandled platform\"\n#endif\n+namespace gvisor {\n+namespace testing {\n+\n+// HaveRawIPSocketCapability returns whether or not the process has access to\n+// raw IP sockets.\n+//\n+// Returns an error when raw IP socket access cannot be determined.\n+PosixErrorOr<bool> HaveRawIPSocketCapability();\n+\n+// HavePacketSocketCapability returns whether or not the process has access to\n+// packet sockets.\n+//\n+// Returns an error when packet socket access cannot be determined.\n+PosixErrorOr<bool> HavePacketSocketCapability();\n+\n+} // namespace testing\n+} // namespace gvisor\n+\n#endif // GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/fuchsia_capability_util.cc",
"new_path": "test/util/fuchsia_capability_util.cc",
"diff": "#ifdef __Fuchsia__\n-#include \"test/util/fuchsia_capability_util.h\"\n-\n+#include <netinet/if_ether.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\nnamespace gvisor {\nnamespace testing {\n-PosixErrorOr<bool> HaveCapability(int cap) {\n- if (cap == CAP_NET_RAW) {\n- auto s = Socket(AF_INET, SOCK_RAW, IPPROTO_UDP);\n+// On Linux, access to raw IP and packet socket is controlled by a single\n+// capability (CAP_NET_RAW). However on Fuchsia, access to raw IP and packet\n+// sockets are controlled by separate capabilities/protocols.\n+\n+namespace {\n+\n+PosixErrorOr<bool> HaveSocketCapability(int domain, int type, int protocol) {\n+ // Fuchsia does not have a platform supported way to check the protocols made\n+ // available to a sandbox. As a workaround, simply try to create the specified\n+ // socket and assume no access if we get a no permissions error.\n+ auto s = Socket(domain, type, protocol);\nif (s.ok()) {\nreturn true;\n}\n@@ -36,7 +43,28 @@ PosixErrorOr<bool> HaveCapability(int cap) {\nreturn s.error();\n}\n- return false;\n+} // namespace\n+\n+PosixErrorOr<bool> HaveRawIPSocketCapability() {\n+ static PosixErrorOr<bool> result(false);\n+ static std::once_flag once;\n+\n+ std::call_once(once, [&]() {\n+ result = HaveSocketCapability(AF_INET, SOCK_RAW, IPPROTO_UDP);\n+ });\n+\n+ return result;\n+}\n+\n+PosixErrorOr<bool> HavePacketSocketCapability() {\n+ static PosixErrorOr<bool> result(false);\n+ static std::once_flag once;\n+\n+ std::call_once(once, [&]() {\n+ result = HaveSocketCapability(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));\n+ });\n+\n+ return result;\n}\n} // namespace testing\n"
},
{
"change_type": "DELETE",
"old_path": "test/util/fuchsia_capability_util.h",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-// Utilities for testing capabilities on Fuchsia.\n-\n-#ifndef GVISOR_TEST_UTIL_FUCHSIA_CAPABILITY_UTIL_H_\n-#define GVISOR_TEST_UTIL_FUCHSIA_CAPABILITY_UTIL_H_\n-\n-#ifdef __Fuchsia__\n-\n-#include \"test/util/posix_error.h\"\n-\n-#ifdef CAP_NET_RAW\n-#error \"Fuchsia should not define CAP_NET_RAW\"\n-#endif // CAP_NET_RAW\n-#define CAP_NET_RAW 0\n-\n-namespace gvisor {\n-namespace testing {\n-\n-// HaveCapability returns true if the process has the specified EFFECTIVE\n-// capability.\n-PosixErrorOr<bool> HaveCapability(int cap);\n-\n-} // namespace testing\n-} // namespace gvisor\n-\n-#endif // __Fuchsia__\n-\n-#endif // GVISOR_TEST_UTIL_FUCHSIA_CAPABILITY_UTIL_H_\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/linux_capability_util.cc",
"new_path": "test/util/linux_capability_util.cc",
"diff": "namespace gvisor {\nnamespace testing {\n+PosixErrorOr<bool> HaveRawIPSocketCapability() {\n+ return HaveCapability(CAP_NET_RAW);\n+}\n+\n+PosixErrorOr<bool> HavePacketSocketCapability() {\n+ return HaveCapability(CAP_NET_RAW);\n+}\n+\nPosixErrorOr<bool> CanCreateUserNamespace() {\n// The most reliable way to determine if userns creation is possible is by\n// trying to create one; see below.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run packet socket tests on Fuchsia
+ Do not check for CAP_NET_RAW on Fuchsia
Fuchsia does not support capabilities the same way Linux does. Instead
emulate the check for CAP_NET_RAW by checking if a packet socket may
be created.
Bug: https://fxbug.dev/79016, https://fxbug.dev/81592
PiperOrigin-RevId: 390263666 |
260,001 | 11.08.2021 20:09:11 | 25,200 | 4249ba85068e7a398187af6c87daca2172ed25e5 | Do not clear merkle files when creating dentry
The dentry for each file/directory can be created/destroyed multiple
times during sandbox lifetime. We should not clear the Merkle file each
time a dentry is created. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -595,23 +595,6 @@ func (fs *filesystem) lookupAndVerifyLocked(ctx context.Context, parent *dentry,\n}\n}\n- // Clear the Merkle tree file if they are to be generated at runtime.\n- // TODO(b/182315468): Optimize the Merkle tree generate process to\n- // allow only updating certain files/directories.\n- if fs.allowRuntimeEnable {\n- childMerkleFD, err := vfsObj.OpenAt(ctx, fs.creds, &vfs.PathOperation{\n- Root: childMerkleVD,\n- Start: childMerkleVD,\n- }, &vfs.OpenOptions{\n- Flags: linux.O_RDWR | linux.O_TRUNC,\n- Mode: 0644,\n- })\n- if err != nil {\n- return nil, err\n- }\n- childMerkleFD.DecRef(ctx)\n- }\n-\n// The dentry needs to be cleaned up if any error occurs. IncRef will be\n// called if a verity child dentry is successfully created.\ndefer childMerkleVD.DecRef(ctx)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not clear merkle files when creating dentry
The dentry for each file/directory can be created/destroyed multiple
times during sandbox lifetime. We should not clear the Merkle file each
time a dentry is created.
PiperOrigin-RevId: 390277107 |
260,001 | 11.08.2021 21:14:28 | 25,200 | 01cfe5952883524b185f60f60485dbc25f988cad | Add verity stat benchmark test | [
{
"change_type": "MODIFY",
"old_path": "test/perf/BUILD",
"new_path": "test/perf/BUILD",
"diff": "@@ -174,3 +174,10 @@ syscall_test(\ntest = \"//test/perf/linux:verity_open_read_close_benchmark\",\nvfs1 = False,\n)\n+\n+syscall_test(\n+ size = \"large\",\n+ debug = False,\n+ test = \"//test/perf/linux:verity_stat_benchmark\",\n+ vfs1 = False,\n+)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/perf/linux/BUILD",
"new_path": "test/perf/linux/BUILD",
"diff": "@@ -462,3 +462,23 @@ cc_binary(\n\"//test/util:verity_util\",\n],\n)\n+\n+cc_binary(\n+ name = \"verity_stat_benchmark\",\n+ testonly = 1,\n+ srcs = [\n+ \"verity_stat_benchmark.cc\",\n+ ],\n+ deps = [\n+ gbenchmark,\n+ gtest,\n+ \"//test/util:capability_util\",\n+ \"//test/util:fs_util\",\n+ \"//test/util:logging\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"//test/util:verity_util\",\n+ \"@com_google_absl//absl/strings\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/perf/linux/verity_stat_benchmark.cc",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <sys/mount.h>\n+#include <sys/stat.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <algorithm>\n+#include <vector>\n+\n+#include \"gtest/gtest.h\"\n+#include \"absl/strings/str_cat.h\"\n+#include \"benchmark/benchmark.h\"\n+#include \"test/util/fs_util.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+#include \"test/util/verity_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+// Creates a file in a nested directory hierarchy at least `depth` directories\n+// deep, and stats that file multiple times.\n+void BM_VerityStat(benchmark::State& state) {\n+ // Create nested directories with given depth.\n+ int depth = state.range(0);\n+\n+ // Mount a tmpfs file system to be wrapped by a verity fs.\n+ TempPath top_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TEST_CHECK(mount(\"\", top_dir.path().c_str(), \"tmpfs\", 0, \"\") == 0);\n+ std::string dir_path = top_dir.path();\n+ std::string child_path = \"\";\n+ std::vector<EnableTarget> targets;\n+\n+ while (depth-- > 0) {\n+ // Don't use TempPath because it will make paths too long to use.\n+ //\n+ // The top_dir destructor will clean up this whole tree.\n+ dir_path = JoinPath(dir_path, absl::StrCat(depth));\n+ ASSERT_NO_ERRNO(Mkdir(dir_path, 0755));\n+ child_path = JoinPath(child_path, Basename(dir_path));\n+ targets.emplace_back(EnableTarget(child_path, O_RDONLY));\n+ }\n+\n+ // Create the file that will be stat'd.\n+ const TempPath file =\n+ ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileIn(dir_path));\n+\n+ targets.emplace_back(\n+ EnableTarget(JoinPath(child_path, Basename(file.path())), O_RDONLY));\n+\n+ // Reverse the targets because verity should be enabled from the lowest level.\n+ std::reverse(targets.begin(), targets.end());\n+\n+ std::string verity_dir =\n+ TEST_CHECK_NO_ERRNO_AND_VALUE(MountVerity(top_dir.path(), targets));\n+\n+ struct stat st;\n+ for (auto _ : state) {\n+ ASSERT_THAT(stat(JoinPath(verity_dir, targets[0].path).c_str(), &st),\n+ SyscallSucceeds());\n+ }\n+}\n+\n+BENCHMARK(BM_VerityStat)->Range(1, 100)->UseRealTime();\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add verity stat benchmark test
PiperOrigin-RevId: 390284683 |
259,853 | 12.08.2021 10:11:21 | 25,200 | f06b1fe862be23698539ca0b0dae5f9d5e4f7e51 | test/pipe: use futex() for sync with the signal hander | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pipe.cc",
"new_path": "test/syscalls/linux/pipe.cc",
"diff": "// limitations under the License.\n#include <fcntl.h> /* Obtain O_* constant definitions */\n+#include <linux/futex.h>\n#include <linux/magic.h>\n#include <signal.h>\n#include <sys/ioctl.h>\n#include <sys/statfs.h>\n#include <sys/uio.h>\n+#include <syscall.h>\n#include <unistd.h>\n#include <vector>\n@@ -50,6 +52,9 @@ std::atomic<int> global_num_signals_received = 0;\nvoid SigRecordingHandler(int signum, siginfo_t* siginfo,\nvoid* unused_ucontext) {\nglobal_num_signals_received++;\n+ ASSERT_THAT(syscall(SYS_futex, &global_num_signals_received,\n+ FUTEX_WAKE | FUTEX_PRIVATE_FLAG, INT_MAX, 0, 0, 0),\n+ SyscallSucceeds());\n}\nPosixErrorOr<Cleanup> RegisterSignalHandler(int signum) {\n@@ -61,11 +66,14 @@ PosixErrorOr<Cleanup> RegisterSignalHandler(int signum) {\nreturn ScopedSigaction(signum, handler);\n}\n-void WaitForSignalDelivery(absl::Duration timeout, int max_expected) {\n- absl::Time wait_start = absl::Now();\n- while (global_num_signals_received < max_expected &&\n- absl::Now() - wait_start < timeout) {\n- absl::SleepFor(absl::Milliseconds(10));\n+void WaitForSignalDelivery(int expected) {\n+ while (1) {\n+ int v = global_num_signals_received;\n+ if (v >= expected) {\n+ break;\n+ }\n+ RetryEINTR(syscall)(SYS_futex, &global_num_signals_received,\n+ FUTEX_WAIT | FUTEX_PRIVATE_FLAG, v, 0, 0, 0);\n}\n}\n@@ -371,7 +379,7 @@ TEST_P(PipeTest, ReaderSideCloses) {\nEXPECT_THAT(write(wfd_.get(), &buf, sizeof(buf)),\nSyscallFailsWithErrno(EPIPE));\n- WaitForSignalDelivery(absl::Seconds(1), 1);\n+ WaitForSignalDelivery(1);\nASSERT_EQ(global_num_signals_received, 1);\n}\n@@ -411,7 +419,7 @@ TEST_P(PipeTest, BlockWriteClosed) {\nnotify.WaitForNotification();\nASSERT_THAT(close(rfd_.release()), SyscallSucceeds());\n- WaitForSignalDelivery(absl::Seconds(1), 1);\n+ WaitForSignalDelivery(1);\nASSERT_EQ(global_num_signals_received, 1);\nt.Join();\n@@ -443,7 +451,7 @@ TEST_P(PipeTest, BlockPartialWriteClosed) {\n// Unblock the above.\nASSERT_THAT(close(rfd_.release()), SyscallSucceeds());\n- WaitForSignalDelivery(absl::Seconds(1), 2);\n+ WaitForSignalDelivery(2);\nASSERT_EQ(global_num_signals_received, 2);\nt.Join();\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/pipe: use futex() for sync with the signal hander
PiperOrigin-RevId: 390399815 |
260,001 | 12.08.2021 14:59:27 | 25,200 | 5f132ae1f889829e57ef6b2117342247b0f75b3a | Clear Merkle files before measuring verity fs | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/verity_prepare.go",
"new_path": "runsc/cmd/verity_prepare.go",
"diff": "@@ -82,7 +82,7 @@ func (c *VerityPrepare) Execute(_ context.Context, f *flag.FlagSet, args ...inte\n},\nProcess: &specs.Process{\nCwd: absRoot,\n- Args: []string{c.tool, \"--path\", \"/verityroot\"},\n+ Args: []string{c.tool, \"--path\", \"/verityroot\", \"--rawpath\", \"/rawroot\"},\nEnv: os.Environ(),\nCapabilities: specutils.AllCapabilities(),\n},\n@@ -94,6 +94,11 @@ func (c *VerityPrepare) Execute(_ context.Context, f *flag.FlagSet, args ...inte\nType: \"bind\",\nOptions: []string{\"verity.roothash=\"},\n},\n+ {\n+ Source: c.dir,\n+ Destination: \"/rawroot\",\n+ Type: \"bind\",\n+ },\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/verity/measure_tool.go",
"new_path": "tools/verity/measure_tool.go",
"diff": "@@ -21,12 +21,14 @@ import (\n\"io/ioutil\"\n\"log\"\n\"os\"\n+ \"strings\"\n\"syscall\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n)\nvar path = flag.String(\"path\", \"\", \"path to the verity file system.\")\n+var rawpath = flag.String(\"rawpath\", \"\", \"path to the raw file system.\")\nconst maxDigestSize = 64\n@@ -40,6 +42,14 @@ func main() {\nif *path == \"\" {\nlog.Fatalf(\"no path provided\")\n}\n+ if *rawpath == \"\" {\n+ log.Fatalf(\"no rawpath provided\")\n+ }\n+ // TODO(b/182315468): Optimize the Merkle tree generate process to\n+ // allow only updating certain files/directories.\n+ if err := clearMerkle(*rawpath); err != nil {\n+ log.Fatalf(\"Failed to clear merkle files in %s: %v\", *rawpath, err)\n+ }\nif err := enableDir(*path); err != nil {\nlog.Fatalf(\"Failed to enable file system %s: %v\", *path, err)\n}\n@@ -49,6 +59,26 @@ func main() {\n}\n}\n+func clearMerkle(path string) error {\n+ files, err := ioutil.ReadDir(path)\n+ if err != nil {\n+ return err\n+ }\n+\n+ for _, file := range files {\n+ if file.IsDir() {\n+ if err := clearMerkle(path + \"/\" + file.Name()); err != nil {\n+ return err\n+ }\n+ } else if strings.HasPrefix(file.Name(), \".merkle.verity\") {\n+ if err := os.Remove(path + \"/\" + file.Name()); err != nil {\n+ return err\n+ }\n+ }\n+ }\n+ return nil\n+}\n+\n// enableDir enables verity features on all the files and sub-directories within\n// path.\nfunc enableDir(path string) error {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Clear Merkle files before measuring verity fs
PiperOrigin-RevId: 390467957 |
260,001 | 12.08.2021 18:29:40 | 25,200 | ddcf884e9d396930095ab1fde51b14201e8cf718 | Add Usage controls
Add Usage controls and implement "usage/usagefd" commands. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/BUILD",
"new_path": "pkg/sentry/control/BUILD",
"diff": "@@ -12,6 +12,7 @@ go_library(\n\"pprof.go\",\n\"proc.go\",\n\"state.go\",\n+ \"usage.go\",\n],\nvisibility = [\n\"//:sandbox\",\n@@ -39,6 +40,7 @@ go_library(\n\"//pkg/tcpip/link/sniffer\",\n\"//pkg/urpc\",\n\"//pkg/usermem\",\n+ \"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/control/usage.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package control\n+\n+import (\n+ \"fmt\"\n+ \"os\"\n+ \"runtime\"\n+\n+ \"golang.org/x/sys/unix\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usage\"\n+ \"gvisor.dev/gvisor/pkg/urpc\"\n+)\n+\n+// Usage includes usage-related RPC stubs.\n+type Usage struct {\n+ Kernel *kernel.Kernel\n+}\n+\n+// MemoryUsageOpts contains usage options.\n+type MemoryUsageOpts struct {\n+ // Full indicates that a full accounting should be done. If Full is not\n+ // specified, then a partial accounting will be done, and Unknown will\n+ // contain a majority of memory. See Collect for more information.\n+ Full bool `json:\"Full\"`\n+}\n+\n+// MemoryUsage is a memory usage structure.\n+type MemoryUsage struct {\n+ Unknown uint64 `json:\"Unknown\"`\n+ System uint64 `json:\"System\"`\n+ Anonymous uint64 `json:\"Anonymous\"`\n+ PageCache uint64 `json:\"PageCache\"`\n+ Mapped uint64 `json:\"Mapped\"`\n+ Tmpfs uint64 `json:\"Tmpfs\"`\n+ Ramdiskfs uint64 `json:\"Ramdiskfs\"`\n+ Total uint64 `json:\"Total\"`\n+}\n+\n+// MemoryUsageFileOpts contains usage file options.\n+type MemoryUsageFileOpts struct {\n+ // Version is used to ensure both sides agree on the format of the\n+ // shared memory buffer.\n+ Version uint64 `json:\"Version\"`\n+}\n+\n+// MemoryUsageFile contains the file handle to the usage file.\n+type MemoryUsageFile struct {\n+ urpc.FilePayload\n+}\n+\n+// UsageFD returns the file that tracks the memory usage of the application.\n+func (u *Usage) UsageFD(opts *MemoryUsageFileOpts, out *MemoryUsageFile) error {\n+ // Only support version 1 for now.\n+ if opts.Version != 1 {\n+ return fmt.Errorf(\"unsupported version requested: %d\", opts.Version)\n+ }\n+\n+ mf := u.Kernel.MemoryFile()\n+ *out = MemoryUsageFile{\n+ FilePayload: urpc.FilePayload{\n+ Files: []*os.File{\n+ usage.MemoryAccounting.File,\n+ mf.File(),\n+ },\n+ },\n+ }\n+\n+ return nil\n+}\n+\n+// Collect returns memory used by the sandboxed application.\n+func (u *Usage) Collect(opts *MemoryUsageOpts, out *MemoryUsage) error {\n+ if opts.Full {\n+ // Ensure everything is up to date.\n+ if err := u.Kernel.MemoryFile().UpdateUsage(); err != nil {\n+ return err\n+ }\n+\n+ // Copy out a snapshot.\n+ snapshot, total := usage.MemoryAccounting.Copy()\n+ *out = MemoryUsage{\n+ System: snapshot.System,\n+ Anonymous: snapshot.Anonymous,\n+ PageCache: snapshot.PageCache,\n+ Mapped: snapshot.Mapped,\n+ Tmpfs: snapshot.Tmpfs,\n+ Ramdiskfs: snapshot.Ramdiskfs,\n+ Total: total,\n+ }\n+ } else {\n+ // Get total usage from the MemoryFile implementation.\n+ total, err := u.Kernel.MemoryFile().TotalUsage()\n+ if err != nil {\n+ return err\n+ }\n+\n+ // The memory accounting is guaranteed to be accurate only when\n+ // UpdateUsage is called. If UpdateUsage is not called, then only Mapped\n+ // will be up-to-date.\n+ snapshot, _ := usage.MemoryAccounting.Copy()\n+ *out = MemoryUsage{\n+ Unknown: total,\n+ Mapped: snapshot.Mapped,\n+ Total: total + snapshot.Mapped,\n+ }\n+\n+ }\n+\n+ return nil\n+}\n+\n+// UsageReduceOpts contains options to Usage.Reduce().\n+type UsageReduceOpts struct {\n+ // If Wait is true, Reduce blocks until all activity initiated by\n+ // Usage.Reduce() has completed.\n+ Wait bool `json:\"wait\"`\n+}\n+\n+// UsageReduceOutput contains output from Usage.Reduce().\n+type UsageReduceOutput struct{}\n+\n+// Reduce requests that the sentry attempt to reduce its memory usage.\n+func (u *Usage) Reduce(opts *UsageReduceOpts, out *UsageReduceOutput) error {\n+ mf := u.Kernel.MemoryFile()\n+ mf.StartEvictions()\n+ if opts.Wait {\n+ mf.WaitForEvictions()\n+ }\n+ return nil\n+}\n+\n+// MemoryUsageRecord contains the mapping and platform memory file.\n+type MemoryUsageRecord struct {\n+ mmap uintptr\n+ stats *usage.RTMemoryStats\n+ mf os.File\n+}\n+\n+// NewMemoryUsageRecord creates a new MemoryUsageRecord from usageFile and\n+// platformFile.\n+func NewMemoryUsageRecord(usageFile, platformFile os.File) (*MemoryUsageRecord, error) {\n+ mmap, _, e := unix.RawSyscall6(unix.SYS_MMAP, 0, usage.RTMemoryStatsSize, unix.PROT_READ, unix.MAP_SHARED, usageFile.Fd(), 0)\n+ if e != 0 {\n+ return nil, fmt.Errorf(\"mmap returned %d, want 0\", e)\n+ }\n+\n+ m := MemoryUsageRecord{\n+ mmap: mmap,\n+ stats: usage.RTMemoryStatsPointer(mmap),\n+ mf: platformFile,\n+ }\n+\n+ runtime.SetFinalizer(&m, finalizer)\n+ return &m, nil\n+}\n+\n+func finalizer(m *MemoryUsageRecord) {\n+ unix.RawSyscall(unix.SYS_MUNMAP, m.mmap, usage.RTMemoryStatsSize, 0)\n+}\n+\n+// Fetch fetches the usage info from a MemoryUsageRecord.\n+func (m *MemoryUsageRecord) Fetch() (mapped, unknown, total uint64, err error) {\n+ var stat unix.Stat_t\n+ if err := unix.Fstat(int(m.mf.Fd()), &stat); err != nil {\n+ return 0, 0, 0, err\n+ }\n+ fmem := uint64(stat.Blocks) * 512\n+ return m.stats.RTMapped, fmem, m.stats.RTMapped + fmem, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -114,6 +114,13 @@ const (\nFsCat = \"Fs.Cat\"\n)\n+// Usage related commands (see usage.go for more details).\n+const (\n+ UsageCollect = \"Usage.Collect\"\n+ UsageUsageFD = \"Usage.UsageFD\"\n+ UsageReduce = \"Usage.Reduce\"\n+)\n+\n// ControlSocketAddr generates an abstract unix socket name for the given ID.\nfunc ControlSocketAddr(id string) string {\nreturn fmt.Sprintf(\"\\x00runsc-sandbox.%s\", id)\n@@ -157,6 +164,7 @@ func newController(fd int, l *Loader) (*controller, error) {\nctrl.srv.Register(&control.Logging{})\nctrl.srv.Register(&control.Lifecycle{l.k})\nctrl.srv.Register(&control.Fs{l.k})\n+ ctrl.srv.Register(&control.Usage{l.k})\nif l.root.conf.ProfileEnable {\nctrl.srv.Register(control.NewProfile(l.k))\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/BUILD",
"new_path": "runsc/cmd/BUILD",
"diff": "@@ -36,6 +36,7 @@ go_library(\n\"statefile.go\",\n\"symbolize.go\",\n\"syscalls.go\",\n+ \"usage.go\",\n\"verity_prepare.go\",\n\"wait.go\",\n],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "runsc/cmd/usage.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package cmd\n+\n+import (\n+ \"context\"\n+ \"encoding/json\"\n+ \"fmt\"\n+ \"os\"\n+\n+ \"github.com/google/subcommands\"\n+ \"gvisor.dev/gvisor/runsc/config\"\n+ \"gvisor.dev/gvisor/runsc/container\"\n+ \"gvisor.dev/gvisor/runsc/flag\"\n+)\n+\n+// Usage implements subcommands.Command for the \"usage\" command.\n+type Usage struct {\n+ full bool\n+ fd bool\n+}\n+\n+// Name implements subcommands.Command.Name.\n+func (*Usage) Name() string {\n+ return \"usage\"\n+}\n+\n+// Synopsis implements subcommands.Command.Synopsis.\n+func (*Usage) Synopsis() string {\n+ return \"Usage shows application memory usage across various categories in bytes.\"\n+}\n+\n+// Usage implements subcommands.Command.Usage.\n+func (*Usage) Usage() string {\n+ return `usage [flags] <container id> - print memory usages to standard output.`\n+}\n+\n+// SetFlags implements subcommands.Command.SetFlags.\n+func (u *Usage) SetFlags(f *flag.FlagSet) {\n+ f.BoolVar(&u.full, \"full\", false, \"enumerate all usage by categories\")\n+ f.BoolVar(&u.fd, \"fd\", false, \"retrieves a subset of usage through the established usage FD\")\n+}\n+\n+// Execute implements subcommands.Command.Execute.\n+func (u *Usage) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+ if f.NArg() < 1 {\n+ f.Usage()\n+ return subcommands.ExitUsageError\n+ }\n+\n+ id := f.Arg(0)\n+ conf := args[0].(*config.Config)\n+\n+ cont, err := container.Load(conf.RootDir, container.FullID{ContainerID: id}, container.LoadOpts{})\n+ if err != nil {\n+ Fatalf(\"loading container: %v\", err)\n+ }\n+\n+ if !u.fd {\n+ m, err := cont.Usage(u.full)\n+ if err != nil {\n+ Fatalf(\"usage failed: %v\", err)\n+ }\n+ if err := json.NewEncoder(os.Stdout).Encode(m); err != nil {\n+ Fatalf(\"Encode MemoryUsage failed: %v\", err)\n+ }\n+ } else {\n+ m, err := cont.UsageFD()\n+ if err != nil {\n+ Fatalf(\"usagefd failed: %v\", err)\n+ }\n+\n+ mapped, unknown, total, err := m.Fetch()\n+ if err != nil {\n+ Fatalf(\"Fetch memory usage failed: %v\", err)\n+ }\n+\n+ fmt.Printf(\"Mapped %v, Unknown %v, Total %v\\n\", mapped, unknown, total)\n+ }\n+ return subcommands.ExitSuccess\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -652,6 +652,24 @@ func (c *Container) Cat(files []string, out *os.File) error {\nreturn c.Sandbox.Cat(c.ID, files, out)\n}\n+// Usage displays memory used by the application.\n+func (c *Container) Usage(full bool) (control.MemoryUsage, error) {\n+ log.Debugf(\"Usage in container, cid: %s, full: %v\", c.ID, full)\n+ return c.Sandbox.Usage(c.ID, full)\n+}\n+\n+// UsageFD shows application memory usage using two donated FDs.\n+func (c *Container) UsageFD() (*control.MemoryUsageRecord, error) {\n+ log.Debugf(\"UsageFD in container, cid: %s\", c.ID)\n+ return c.Sandbox.UsageFD(c.ID)\n+}\n+\n+// Reduce requests that the sentry attempt to reduce its memory usage.\n+func (c *Container) Reduce(wait bool) error {\n+ log.Debugf(\"Reduce in container, cid: %s\", c.ID)\n+ return c.Sandbox.Reduce(c.ID, wait)\n+}\n+\n// State returns the metadata of the container.\nfunc (c *Container) State() specs.State {\nreturn specs.State{\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -2655,3 +2655,127 @@ func TestCat(t *testing.T) {\nt.Errorf(\"out got %s, want include %s\", buf, want)\n}\n}\n+\n+// TestUsage checks that usage generates the expected memory usage.\n+func TestUsage(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"Creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"starting container: %v\", err)\n+ }\n+\n+ for _, full := range []bool{false, true} {\n+ m, err := cont.Usage(full)\n+ if err != nil {\n+ t.Fatalf(\"error usage from container: %v\", err)\n+ }\n+ if m.Mapped == 0 {\n+ t.Errorf(\"Usage mapped got zero\")\n+ }\n+ if m.Total == 0 {\n+ t.Errorf(\"Usage total got zero\")\n+ }\n+ if full {\n+ if m.System == 0 {\n+ t.Errorf(\"Usage system got zero\")\n+ }\n+ if m.Anonymous == 0 {\n+ t.Errorf(\"Usage anonymous got zero\")\n+ }\n+ }\n+ }\n+}\n+\n+// TestUsageFD checks that usagefd generates the expected memory usage.\n+func TestUsageFD(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"Creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"starting container: %v\", err)\n+ }\n+\n+ m, err := cont.UsageFD()\n+ if err != nil {\n+ t.Fatalf(\"error usageFD from container: %v\", err)\n+ }\n+\n+ mapped, unknown, total, err := m.Fetch()\n+ if err != nil {\n+ t.Fatalf(\"error Fetch memory usage: %v\", err)\n+ }\n+\n+ if mapped == 0 {\n+ t.Errorf(\"UsageFD Mapped got zero\")\n+ }\n+ if unknown == 0 {\n+ t.Errorf(\"UsageFD unknown got zero\")\n+ }\n+ if total == 0 {\n+ t.Errorf(\"UsageFD total got zero\")\n+ }\n+}\n+\n+// TestReduce checks that reduce call succeeds.\n+func TestReduce(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"Creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"starting container: %v\", err)\n+ }\n+\n+ if err := cont.Reduce(false); err != nil {\n+ t.Fatalf(\"error reduce from container: %v\", err)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -1020,6 +1020,59 @@ func (s *Sandbox) Cat(cid string, files []string, out *os.File) error {\nreturn nil\n}\n+// Usage sends the collect call for a container in the sandbox.\n+func (s *Sandbox) Usage(cid string, Full bool) (control.MemoryUsage, error) {\n+ log.Debugf(\"Usage sandbox %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return control.MemoryUsage{}, err\n+ }\n+ defer conn.Close()\n+\n+ var m control.MemoryUsage\n+ err = conn.Call(boot.UsageCollect, &control.MemoryUsageOpts{\n+ Full: Full,\n+ }, &m)\n+ return m, err\n+}\n+\n+// UsageFD sends the usagefd call for a container in the sandbox.\n+func (s *Sandbox) UsageFD(cid string) (*control.MemoryUsageRecord, error) {\n+ log.Debugf(\"Usage sandbox %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return nil, err\n+ }\n+ defer conn.Close()\n+\n+ var m control.MemoryUsageFile\n+ if err := conn.Call(boot.UsageUsageFD, &control.MemoryUsageFileOpts{\n+ Version: 1,\n+ }, &m); err != nil {\n+ return nil, fmt.Errorf(\"UsageFD failed: %v\", err)\n+ }\n+\n+ if len(m.FilePayload.Files) != 2 {\n+ return nil, fmt.Errorf(\"wants exactly two fds\")\n+ }\n+\n+ return control.NewMemoryUsageRecord(*m.FilePayload.Files[0], *m.FilePayload.Files[1])\n+}\n+\n+// Reduce sends the reduce call for a container in the sandbox.\n+func (s *Sandbox) Reduce(cid string, wait bool) error {\n+ log.Debugf(\"Reduce sandbox %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return err\n+ }\n+ defer conn.Close()\n+\n+ return conn.Call(boot.UsageReduce, &control.UsageReduceOpts{\n+ Wait: wait,\n+ }, nil)\n+}\n+\n// IsRunning returns true if the sandbox or gofer process is running.\nfunc (s *Sandbox) IsRunning() bool {\nif s.Pid != 0 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Usage controls
Add Usage controls and implement "usage/usagefd" commands.
PiperOrigin-RevId: 390507423 |
260,004 | 13.08.2021 07:39:19 | 25,200 | eb0f24c6c48ea5301c5136b53333e189d0dc4c58 | Free multicastMemberships on UDP endpoint close
tcpip.Endpoint.Close is documented to free all resources associated
with an endpoint so we don't need to create an empty map to clear
the multicast memberships. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -266,7 +266,7 @@ func (e *endpoint) Close() {\nfor mem := range e.multicastMemberships {\ne.stack.LeaveGroup(e.NetProto, mem.nicID, mem.multicastAddr)\n}\n- e.multicastMemberships = make(map[multicastMembership]struct{})\n+ e.multicastMemberships = nil\n// Close the receive list and drain it.\ne.rcvMu.Lock()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Free multicastMemberships on UDP endpoint close
tcpip.Endpoint.Close is documented to free all resources associated
with an endpoint so we don't need to create an empty map to clear
the multicast memberships.
PiperOrigin-RevId: 390609826 |
259,881 | 13.08.2021 10:41:10 | 25,200 | 8f2b11a87e0c8fc89636617c9161caee9f8f1fb5 | Update `core` allowed dependencies
This list has gotten a little out-of-date. Note that `clockwork` used to be
used but was removed in gvisor.dev/pr/5384. | [
{
"change_type": "MODIFY",
"old_path": "CONTRIBUTING.md",
"new_path": "CONTRIBUTING.md",
"diff": "@@ -69,6 +69,10 @@ Rules:\nbinary). Use `//pkg/unet` instead.\n* `@org_golang_x_sys//unix:go_default_library` (Go import\n`golang.org/x/sys/unix`).\n+ * `@org_golang_x_time//rate:go_default_library` (Go import\n+ `golang.org/x/time/rate`).\n+ * `@com_github_google_btree//:go_default_library\"` (Go import\n+ `github.com/google/btree`).\n* Generated Go protobuf packages.\n* `@org_golang_google_protobuf//proto:go_default_library` (Go import\n`google.golang.org/protobuf`).\n"
},
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -669,13 +669,6 @@ go_repository(\nversion = \"v0.0.0-20160803190731-bd40a432e4c7\",\n)\n-go_repository(\n- name = \"com_github_jonboulle_clockwork\",\n- importpath = \"github.com/jonboulle/clockwork\",\n- sum = \"h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo=\",\n- version = \"v0.1.0\",\n-)\n-\ngo_repository(\nname = \"com_github_jtolds_gls\",\nimportpath = \"github.com/jtolds/gls\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update `core` allowed dependencies
This list has gotten a little out-of-date. Note that `clockwork` used to be
used but was removed in gvisor.dev/pr/5384.
PiperOrigin-RevId: 390644841 |
260,001 | 13.08.2021 14:17:56 | 25,200 | 6eb8596f72f3c889de3f826b82319d41ac655829 | Add Event controls
Add Event controls and implement "stream" commands. | [
{
"change_type": "MODIFY",
"old_path": "pkg/eventchannel/BUILD",
"new_path": "pkg/eventchannel/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nsrcs = [\n\"event.go\",\n\"event_any.go\",\n+ \"processor.go\",\n\"rate.go\",\n],\nvisibility = [\"//:sandbox\"],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/eventchannel/event_any.go",
"new_path": "pkg/eventchannel/event_any.go",
"diff": "@@ -26,3 +26,8 @@ import (\nfunc newAny(m proto.Message) (*anypb.Any, error) {\nreturn anypb.New(m)\n}\n+\n+func emptyAny() *anypb.Any {\n+ var any anypb.Any\n+ return &any\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/eventchannel/processor.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package eventchannel\n+\n+import (\n+ \"encoding/binary\"\n+ \"fmt\"\n+ \"io\"\n+ \"os\"\n+ \"time\"\n+\n+ \"google.golang.org/protobuf/proto\"\n+ pb \"gvisor.dev/gvisor/pkg/eventchannel/eventchannel_go_proto\"\n+)\n+\n+// eventProcessor carries display state across multiple events.\n+type eventProcessor struct {\n+ filtering bool\n+ // filtered is the number of events omitted since printing the last matching\n+ // event. Only meaningful when filtering == true.\n+ filtered uint64\n+ // allowlist is the set of event names to display. If empty, all events are\n+ // displayed.\n+ allowlist map[string]bool\n+}\n+\n+// newEventProcessor creates a new EventProcessor with filters.\n+func newEventProcessor(filters []string) *eventProcessor {\n+ e := &eventProcessor{\n+ filtering: len(filters) > 0,\n+ allowlist: make(map[string]bool),\n+ }\n+ for _, f := range filters {\n+ e.allowlist[f] = true\n+ }\n+ return e\n+}\n+\n+// processOne reads, parses and displays a single event from the event channel.\n+//\n+// The event channel is a stream of (msglen, payload) packets; this function\n+// processes a single such packet. The msglen is a uvarint-encoded length for\n+// the associated payload. The payload is a binary-encoded 'Any' protobuf, which\n+// in turn encodes an arbitrary event protobuf.\n+func (e *eventProcessor) processOne(src io.Reader, out *os.File) error {\n+ // Read and parse the msglen.\n+ lenbuf := make([]byte, binary.MaxVarintLen64)\n+ if _, err := io.ReadFull(src, lenbuf); err != nil {\n+ return err\n+ }\n+ msglen, consumed := binary.Uvarint(lenbuf)\n+ if consumed <= 0 {\n+ return fmt.Errorf(\"couldn't parse the message length\")\n+ }\n+\n+ // Read the payload.\n+ buf := make([]byte, msglen)\n+ // Copy any unused bytes from the len buffer into the payload buffer. These\n+ // bytes are actually part of the payload.\n+ extraBytes := copy(buf, lenbuf[consumed:])\n+ if _, err := io.ReadFull(src, buf[extraBytes:]); err != nil {\n+ return err\n+ }\n+\n+ // Unmarshal the payload into an \"Any\" protobuf, which encodes the actual\n+ // event.\n+ encodedEv := emptyAny()\n+ if err := proto.Unmarshal(buf, encodedEv); err != nil {\n+ return fmt.Errorf(\"failed to unmarshal 'any' protobuf message: %v\", err)\n+ }\n+\n+ var ev pb.DebugEvent\n+ if err := (encodedEv).UnmarshalTo(&ev); err != nil {\n+ return fmt.Errorf(\"failed to decode 'any' protobuf message: %v\", err)\n+ }\n+\n+ if e.filtering && e.allowlist[ev.Name] {\n+ e.filtered++\n+ return nil\n+ }\n+\n+ if e.filtering && e.filtered > 0 {\n+ if e.filtered == 1 {\n+ fmt.Fprintf(out, \"... filtered %d event ...\\n\\n\", e.filtered)\n+ } else {\n+ fmt.Fprintf(out, \"... filtered %d events ...\\n\\n\", e.filtered)\n+ }\n+ e.filtered = 0\n+ }\n+\n+ // Extract the inner event and display it. Example:\n+ //\n+ // 2017-10-04 14:35:05.316180374 -0700 PDT m=+1.132485846\n+ // cloud_gvisor.MemoryUsage {\n+ // total: 23822336\n+ // }\n+ fmt.Fprintf(out, \"%v\\n%v {\\n\", time.Now(), ev.Name)\n+ fmt.Fprintf(out, \"%v\", ev.Text)\n+ fmt.Fprintf(out, \"}\\n\\n\")\n+\n+ return nil\n+}\n+\n+// ProcessAll reads, parses and displays all events from src. The events are\n+// displayed to out.\n+func ProcessAll(src io.Reader, filters []string, out *os.File) error {\n+ ep := newEventProcessor(filters)\n+ for {\n+ switch err := ep.processOne(src, out); err {\n+ case nil:\n+ continue\n+ case io.EOF:\n+ return nil\n+ default:\n+ return err\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/BUILD",
"new_path": "pkg/sentry/control/BUILD",
"diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"control\",\nsrcs = [\n\"control.go\",\n+ \"events.go\",\n\"fs.go\",\n\"lifecycle.go\",\n\"logging.go\",\n@@ -20,6 +21,7 @@ go_library(\ndeps = [\n\"//pkg/abi/linux\",\n\"//pkg/context\",\n+ \"//pkg/eventchannel\",\n\"//pkg/fd\",\n\"//pkg/log\",\n\"//pkg/sentry/fdimport\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/control/events.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package control\n+\n+import (\n+ \"errors\"\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/eventchannel\"\n+ \"gvisor.dev/gvisor/pkg/urpc\"\n+)\n+\n+// EventsOpts are the arguments for eventchannel-related commands.\n+type EventsOpts struct {\n+ urpc.FilePayload\n+}\n+\n+// Events is the control server state for eventchannel-related commands.\n+type Events struct {\n+ emitter eventchannel.Emitter\n+}\n+\n+// AttachDebugEmitter receives a connected unix domain socket FD from the client\n+// and establishes it as a new emitter for the sentry eventchannel. Any existing\n+// emitters are replaced on a subsequent attach.\n+func (e *Events) AttachDebugEmitter(o *EventsOpts, _ *struct{}) error {\n+ if len(o.FilePayload.Files) < 1 {\n+ return errors.New(\"no output writer provided\")\n+ }\n+\n+ sock, err := o.ReleaseFD(0)\n+ if err != nil {\n+ return err\n+ }\n+ sockFD := sock.Release()\n+\n+ // SocketEmitter takes ownership of sockFD.\n+ emitter, err := eventchannel.SocketEmitter(sockFD)\n+ if err != nil {\n+ return fmt.Errorf(\"failed to create SocketEmitter for FD %d: %v\", sockFD, err)\n+ }\n+\n+ // If there is already a debug emitter, close the old one.\n+ if e.emitter != nil {\n+ e.emitter.Close()\n+ }\n+\n+ e.emitter = eventchannel.DebugEmitterFrom(emitter)\n+\n+ // Register the new stream destination.\n+ eventchannel.AddEmitter(e.emitter)\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -121,6 +121,11 @@ const (\nUsageReduce = \"Usage.Reduce\"\n)\n+// Events related commands (see events.go for more details).\n+const (\n+ EventsAttachDebugEmitter = \"Events.AttachDebugEmitter\"\n+)\n+\n// ControlSocketAddr generates an abstract unix socket name for the given ID.\nfunc ControlSocketAddr(id string) string {\nreturn fmt.Sprintf(\"\\x00runsc-sandbox.%s\", id)\n@@ -161,6 +166,7 @@ func newController(fd int, l *Loader) (*controller, error) {\n}\nctrl.srv.Register(&debug{})\n+ ctrl.srv.Register(&control.Events{})\nctrl.srv.Register(&control.Logging{})\nctrl.srv.Register(&control.Lifecycle{l.k})\nctrl.srv.Register(&control.Fs{l.k})\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/strace.go",
"new_path": "runsc/boot/strace.go",
"diff": "@@ -35,9 +35,14 @@ func enableStrace(conf *config.Config) error {\n}\nstrace.LogMaximumSize = max\n+ sink := strace.SinkTypeLog\n+ if conf.StraceEvent {\n+ sink = strace.SinkTypeEvent\n+ }\n+\nif len(conf.StraceSyscalls) == 0 {\n- strace.EnableAll(strace.SinkTypeLog)\n+ strace.EnableAll(sink)\nreturn nil\n}\n- return strace.Enable(strings.Split(conf.StraceSyscalls, \",\"), strace.SinkTypeLog)\n+ return strace.Enable(strings.Split(conf.StraceSyscalls, \",\"), sink)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/events.go",
"new_path": "runsc/cmd/events.go",
"diff": "@@ -33,6 +33,10 @@ type Events struct {\nintervalSec int\n// If true, events will print a single group of stats and exit.\nstats bool\n+ // If true, events will dump all filtered events to stdout.\n+ stream bool\n+ // filters for streamed events.\n+ filters stringSlice\n}\n// Name implements subcommands.Command.Name.\n@@ -62,6 +66,8 @@ OPTIONS:\nfunc (evs *Events) SetFlags(f *flag.FlagSet) {\nf.IntVar(&evs.intervalSec, \"interval\", 5, \"set the stats collection interval, in seconds\")\nf.BoolVar(&evs.stats, \"stats\", false, \"display the container's stats then exit\")\n+ f.BoolVar(&evs.stream, \"stream\", false, \"dump all filtered events to stdout\")\n+ f.Var(&evs.filters, \"filters\", \"only display matching events\")\n}\n// Execute implements subcommands.Command.Execute.\n@@ -79,6 +85,13 @@ func (evs *Events) Execute(ctx context.Context, f *flag.FlagSet, args ...interfa\nFatalf(\"loading sandbox: %v\", err)\n}\n+ if evs.stream {\n+ if err := c.Stream(evs.filters, os.Stdout); err != nil {\n+ Fatalf(\"Stream failed: %v\", err)\n+ }\n+ return subcommands.ExitSuccess\n+ }\n+\n// Repeatedly get stats from the container.\nfor {\n// Get the event and print it as JSON.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -117,6 +117,10 @@ type Config struct {\n// StraceLogSize is the max size of data blobs to display.\nStraceLogSize uint `flag:\"strace-log-size\"`\n+ // StraceEvent indicates sending strace to events if true. Strace is\n+ // sent to log if false.\n+ StraceEvent bool `flag:\"strace-event\"`\n+\n// DisableSeccomp indicates whether seccomp syscall filters should be\n// disabled. Pardon the double negation, but default to enabled is important.\nDisableSeccomp bool\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -56,6 +56,7 @@ func RegisterFlags() {\nflag.Bool(\"strace\", false, \"enable strace.\")\nflag.String(\"strace-syscalls\", \"\", \"comma-separated list of syscalls to trace. If --strace is true and this list is empty, then all syscalls will be traced.\")\nflag.Uint(\"strace-log-size\", 1024, \"default size (in bytes) to log data argument blobs.\")\n+ flag.Bool(\"strace-event\", false, \"send strace to event.\")\n// Flags that control sandbox runtime behavior.\nflag.String(\"platform\", \"ptrace\", \"specifies which platform to use: ptrace (default), kvm.\")\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -670,6 +670,12 @@ func (c *Container) Reduce(wait bool) error {\nreturn c.Sandbox.Reduce(c.ID, wait)\n}\n+// Stream dumps all events to out.\n+func (c *Container) Stream(filters []string, out *os.File) error {\n+ log.Debugf(\"Stream in container, cid: %s\", c.ID)\n+ return c.Sandbox.Stream(c.ID, filters, out)\n+}\n+\n// State returns the metadata of the container.\nfunc (c *Container) State() specs.State {\nreturn specs.State{\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -2779,3 +2779,53 @@ func TestReduce(t *testing.T) {\nt.Fatalf(\"error reduce from container: %v\", err)\n}\n}\n+\n+// TestStream checks that Stream dumps expected events.\n+func TestStream(t *testing.T) {\n+ spec, conf := sleepSpecConf(t)\n+ conf.Strace = true\n+ conf.StraceEvent = true\n+ conf.StraceSyscalls = \"\"\n+\n+ _, bundleDir, cleanup, err := testutil.SetupContainer(spec, conf)\n+ if err != nil {\n+ t.Fatalf(\"error setting up container: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ args := Args{\n+ ID: testutil.RandomContainerID(),\n+ Spec: spec,\n+ BundleDir: bundleDir,\n+ }\n+\n+ cont, err := New(conf, args)\n+ if err != nil {\n+ t.Fatalf(\"Creating container: %v\", err)\n+ }\n+ defer cont.Destroy()\n+\n+ if err := cont.Start(conf); err != nil {\n+ t.Fatalf(\"starting container: %v\", err)\n+ }\n+\n+ r, w, err := os.Pipe()\n+ if err != nil {\n+ t.Fatalf(\"os.Create(): %v\", err)\n+ }\n+\n+ // Spawn a new thread to Stream events as it blocks indefinitely.\n+ go func() {\n+ cont.Stream(nil, w)\n+ }()\n+\n+ buf := make([]byte, 1024)\n+ if _, err := r.Read(buf); err != nil {\n+ t.Fatalf(\"Read out: %v\", err)\n+ }\n+\n+ // A syscall strace event includes \"Strace\".\n+ if got, want := string(buf), \"Strace\"; !strings.Contains(got, want) {\n+ t.Errorf(\"out got %s, want include %s\", buf, want)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/BUILD",
"new_path": "runsc/sandbox/BUILD",
"diff": "@@ -17,12 +17,14 @@ go_library(\n\"//pkg/control/client\",\n\"//pkg/control/server\",\n\"//pkg/coverage\",\n+ \"//pkg/eventchannel\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n\"//pkg/sentry/platform\",\n\"//pkg/sync\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/unet\",\n\"//pkg/urpc\",\n\"//runsc/boot\",\n\"//runsc/boot/platforms\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -35,10 +35,12 @@ import (\n\"gvisor.dev/gvisor/pkg/control/client\"\n\"gvisor.dev/gvisor/pkg/control/server\"\n\"gvisor.dev/gvisor/pkg/coverage\"\n+ \"gvisor.dev/gvisor/pkg/eventchannel\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n\"gvisor.dev/gvisor/pkg/sync\"\n+ \"gvisor.dev/gvisor/pkg/unet\"\n\"gvisor.dev/gvisor/pkg/urpc\"\n\"gvisor.dev/gvisor/runsc/boot\"\n\"gvisor.dev/gvisor/runsc/boot/platforms\"\n@@ -1073,6 +1075,37 @@ func (s *Sandbox) Reduce(cid string, wait bool) error {\n}, nil)\n}\n+// Stream sends the AttachDebugEmitter call for a container in the sandbox, and\n+// dumps filtered events to out.\n+func (s *Sandbox) Stream(cid string, filters []string, out *os.File) error {\n+ log.Debugf(\"Stream sandbox %q\", s.ID)\n+ conn, err := s.sandboxConnect()\n+ if err != nil {\n+ return err\n+ }\n+ defer conn.Close()\n+\n+ r, w, err := unet.SocketPair(false)\n+ if err != nil {\n+ return err\n+ }\n+\n+ wfd, err := w.Release()\n+ if err != nil {\n+ return fmt.Errorf(\"failed to release write socket FD: %v\", err)\n+ }\n+\n+ if err := conn.Call(boot.EventsAttachDebugEmitter, &control.EventsOpts{\n+ FilePayload: urpc.FilePayload{Files: []*os.File{\n+ os.NewFile(uintptr(wfd), \"event sink\"),\n+ }},\n+ }, nil); err != nil {\n+ return fmt.Errorf(\"AttachDebugEmitter failed: %v\", err)\n+ }\n+\n+ return eventchannel.ProcessAll(r, filters, out)\n+}\n+\n// IsRunning returns true if the sandbox or gofer process is running.\nfunc (s *Sandbox) IsRunning() bool {\nif s.Pid != 0 {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Event controls
Add Event controls and implement "stream" commands.
PiperOrigin-RevId: 390691702 |
259,880 | 16.08.2021 16:33:57 | -7,200 | 7c5ab794f140dda031ba015d79892a79dd523d50 | fix sending of SIGTTOU signal in SetForegroundProcessGroup
Changed sendSignal to sendSignalLocked because tg.pidns.owner.mu and tg.signalHandlers.mu
are already locked in SetForegroundProcess
Added a control to verify whether the calling process is ignoring SIGTTOU
before sending the signal | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/thread_group.go",
"new_path": "pkg/sentry/kernel/thread_group.go",
"diff": "@@ -511,9 +511,11 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\nreturn -1, linuxerr.EPERM\n}\n- //if the calling process is a member of a background group, a SIGTTOU signal is sent to all members of this background process group.\n- if tg.processGroup.session.foreground.id != tg.processGroup.id {\n- tg.processGroup.SendSignal(&linux.SignalInfo{Signo: int32(linux.SIGTTOU)})\n+ sa:= tg.signalHandlers.actions[linux.SIGTTOU]\n+ //if the calling process is a member of a background group, a SIGTTOU\n+ //signal is sent to all members of this background process group.\n+ if tg.processGroup.id != tg.processGroup.session.foreground.id && sa.Handler!=linux.SIG_IGN{\n+ tg.leader.sendSignalLocked(SignalInfoPriv(linux.SIGTTOU),true)\n}\ntg.processGroup.session.foreground.id = pgid\n"
}
] | Go | Apache License 2.0 | google/gvisor | fix sending of SIGTTOU signal in SetForegroundProcessGroup
Changed sendSignal to sendSignalLocked because tg.pidns.owner.mu and tg.signalHandlers.mu
are already locked in SetForegroundProcess
Added a control to verify whether the calling process is ignoring SIGTTOU
before sending the signal |
259,853 | 16.08.2021 15:50:30 | 25,200 | bb13d015a4ffcedac42cce05ec9f1ff4728d12d7 | imges/syzkaller: add --allow-releaseinfo-change to apt update
Otherwise, it fails with this error:
Get:3 buster/updates InRelease
Reading package lists...
E: Repository 'http://deb.debian.org/debian buster InRelease' changed its
'Suite' value from 'stable' to 'oldstable' | [
{
"change_type": "MODIFY",
"old_path": "images/syzkaller/Dockerfile",
"new_path": "images/syzkaller/Dockerfile",
"diff": "@@ -2,7 +2,7 @@ FROM gcr.io/syzkaller/env\n# This image is mostly for investigating syzkaller crashes, so let's install\n# developer tools.\n-RUN apt update && apt install -y git vim strace gdb procps\n+RUN apt update --allow-releaseinfo-change && DEBIAN_FRONTEND=noninteractive apt install -y git vim strace gdb procps\nWORKDIR /syzkaller/gopath/src/github.com/google/syzkaller\n"
}
] | Go | Apache License 2.0 | google/gvisor | imges/syzkaller: add --allow-releaseinfo-change to apt update
Otherwise, it fails with this error:
Get:3 http://security.debian.org/debian-security buster/updates InRelease
Reading package lists...
E: Repository 'http://deb.debian.org/debian buster InRelease' changed its
'Suite' value from 'stable' to 'oldstable'
PiperOrigin-RevId: 391155532 |
259,954 | 05.08.2021 09:49:09 | 21,600 | 0f62f21527b9014653de07fa366fb5b0f48fb16c | Support runtime options type used in containerd v1.5 | [
{
"change_type": "MODIFY",
"old_path": "pkg/shim/runtimeoptions/runtimeoptions.go",
"new_path": "pkg/shim/runtimeoptions/runtimeoptions.go",
"diff": "// Package runtimeoptions contains the runtimeoptions proto.\npackage runtimeoptions\n+\n+import proto \"github.com/gogo/protobuf/proto\"\n+\n+func init() {\n+ // TODO(gvisor.dev/issue/6449): Upgrade runtimeoptions.proto after upgrading to containerd 1.5\n+ proto.RegisterType((*Options)(nil), \"runtimeoptions.v1.Options\")\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support runtime options type used in containerd v1.5 |
259,853 | 16.08.2021 23:12:12 | 25,200 | 6294a7a6ec6d0e4666f5413df6e59738d02fc12e | test/syscalls/proc_net: /proc/net/snmp can contain system-wide statistics
This is a new kernel feature that are controlled by the net.core.mibs_allocation
sysctl. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net.cc",
"new_path": "test/syscalls/linux/proc_net.cc",
"diff": "@@ -152,6 +152,22 @@ TEST(ProcNetDev, Format) {\nEXPECT_GT(entries.size(), 0);\n}\n+// GetMibsAllocationSysctl retuns a value of the net.core.mibs_allocation\n+// sysctl./proc/sys/net/core/mibs_allocation\n+//\n+// When mibs_allocation is unset, a netns creation inherits MIB from init\n+// network namespace. Otherwise, MIBS is allocated for each namespace.\n+int GetMibsAllocationSysctl() {\n+ auto ret = GetContents(\"/proc/sys/net/core/mibs_allocation\");\n+ if (!ret.ok()) {\n+ // The current kernel doesn't support mibs_allocation.\n+ return 1;\n+ }\n+ int32_t val;\n+ EXPECT_TRUE(absl::SimpleAtoi(ret.ValueOrDie(), &val));\n+ return val;\n+}\n+\nPosixErrorOr<uint64_t> GetSNMPMetricFromProc(const std::string snmp,\nconst std::string& type,\nconst std::string& item) {\n@@ -226,12 +242,21 @@ TEST(ProcNetSnmp, TcpReset) {\nnewAttemptFails = ASSERT_NO_ERRNO_AND_VALUE(\nGetSNMPMetricFromProc(snmp, \"Tcp\", \"AttemptFails\"));\n+ if (GetMibsAllocationSysctl()) {\nEXPECT_EQ(oldActiveOpens, newActiveOpens - 1);\nEXPECT_EQ(oldOutRsts, newOutRsts - 1);\nEXPECT_EQ(oldAttemptFails, newAttemptFails - 1);\n+ } else {\n+ // System-wide statistics can have some noise.\n+ EXPECT_LE(oldOutRsts, newOutRsts - 1);\n+ EXPECT_LE(oldAttemptFails, newAttemptFails - 1);\n+ }\n}\nTEST(ProcNetSnmp, TcpEstab) {\n+ // System-wide statistics can have some noise.\n+ SKIP_IF(GetMibsAllocationSysctl() == 0);\n+\n// TODO(gvisor.dev/issue/866): epsocket metrics are not savable.\nDisableSave ds;\n@@ -355,8 +380,14 @@ TEST(ProcNetSnmp, UdpNoPorts) {\nnewNoPorts =\nASSERT_NO_ERRNO_AND_VALUE(GetSNMPMetricFromProc(snmp, \"Udp\", \"NoPorts\"));\n+ if (GetMibsAllocationSysctl()) {\nEXPECT_EQ(oldOutDatagrams, newOutDatagrams - 1);\nEXPECT_EQ(oldNoPorts, newNoPorts - 1);\n+ } else {\n+ // System-wide statistics can have some noise.\n+ EXPECT_LE(oldOutDatagrams, newOutDatagrams - 1);\n+ EXPECT_LE(oldNoPorts, newNoPorts - 1);\n+ }\n}\nTEST(ProcNetSnmp, UdpIn) {\n@@ -405,8 +436,14 @@ TEST(ProcNetSnmp, UdpIn) {\nnewInDatagrams = ASSERT_NO_ERRNO_AND_VALUE(\nGetSNMPMetricFromProc(snmp, \"Udp\", \"InDatagrams\"));\n+ if (GetMibsAllocationSysctl()) {\nEXPECT_EQ(oldOutDatagrams, newOutDatagrams - 1);\nEXPECT_EQ(oldInDatagrams, newInDatagrams - 1);\n+ } else {\n+ // System-wide statistics can have some noise.\n+ EXPECT_LE(oldOutDatagrams, newOutDatagrams - 1);\n+ EXPECT_LE(oldInDatagrams, newInDatagrams - 1);\n+ }\n}\nTEST(ProcNetSnmp, CheckNetStat) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | test/syscalls/proc_net: /proc/net/snmp can contain system-wide statistics
This is a new kernel feature that are controlled by the net.core.mibs_allocation
sysctl.
PiperOrigin-RevId: 391215784 |
259,853 | 17.08.2021 12:55:41 | 25,200 | 8f6c54c8c023d551d6d09b5428ac59fb704c7067 | Deflake test/perf:randread_benchmark
The test expects that pread reads the full buffer, it means that the pread
offset has to be equal or less than file_size - buffer_size. | [
{
"change_type": "MODIFY",
"old_path": "test/perf/linux/randread_benchmark.cc",
"new_path": "test/perf/linux/randread_benchmark.cc",
"diff": "@@ -85,7 +85,7 @@ void BM_RandRead(benchmark::State& state) {\nunsigned int seed = 1;\nfor (auto _ : state) {\nTEST_CHECK(PreadFd(fd.get(), buf.data(), buf.size(),\n- rand_r(&seed) % kFileSize) == size);\n+ rand_r(&seed) % (kFileSize - buf.size())) == size);\n}\nstate.SetBytesProcessed(static_cast<int64_t>(size) *\n"
}
] | Go | Apache License 2.0 | google/gvisor | Deflake test/perf:randread_benchmark
The test expects that pread reads the full buffer, it means that the pread
offset has to be equal or less than file_size - buffer_size.
PiperOrigin-RevId: 391356863 |
259,880 | 16.08.2021 16:37:00 | -7,200 | a5f2ef66d3c7e5ed1fd90cc8670b3e3891ad8af9 | added two system call tests for setForegroundProcessGroup
Test the correct sending of the SIGTTOU in setForegroundProcess | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1640,6 +1640,57 @@ TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroup) {\nASSERT_NO_ERRNO(res);\n}\n+// This test verify if a SIGTTOU signal is sent to the calling process'group\n+// when tcsetpgrp is called by a background process\n+TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBackground) {\n+ auto res = RunInChild([=]() {\n+ setsid();\n+ TEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n+ pid_t grandchild = fork();\n+ if (!grandchild) {\n+ //assign a different pgid to the child so it will result as\n+ //a background process\n+ setpgid(grandchild, getpid());\n+ tcsetpgrp(replica_.get(), getpgid(0));\n+ // We should never reach this.\n+ _exit(1);\n+ }\n+ int wstatus;\n+ TEST_PCHECK(waitpid(grandchild, &wstatus, WSTOPPED) == grandchild);\n+ TEST_PCHECK(WSTOPSIG(wstatus)==SIGTTOU);\n+ });\n+ ASSERT_NO_ERRNO(res);\n+}\n+\n+// This test verify that a SIGTTOU signal is not delivered to\n+// a background process which calls tcsetpgrp and is ignoring SIGTTOU\n+TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUIgnored) {\n+ auto res = RunInChild([=]() {\n+ setsid();\n+ TEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n+ pid_t grandchild = fork();\n+ if (!grandchild) {\n+ // ignore SIGTTOU so the child in background won't\n+ // be stopped when it will call tcsetpgrp\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\n+ sa.sa_flags = 0;\n+ sigemptyset(&sa.sa_mask);\n+ sigaction(SIGTTOU, &sa, NULL);\n+ //assign a different pgid to the child so it will result as\n+ //a background process\n+ setpgid(grandchild, getpid());\n+ tcsetpgrp(replica_.get(), getpgid(0));\n+ _exit(0);\n+ }\n+ int wstatus;\n+ TEST_PCHECK(waitpid(grandchild, &wstatus, WSTOPPED) == grandchild);\n+ TEST_PCHECK(WSTOPSIG(wstatus)!=SIGTTOU);\n+ TEST_PCHECK(WIFEXITED(wstatus));\n+ });\n+ ASSERT_NO_ERRNO(res);\n+}\n+\nTEST_F(JobControlTest, SetForegroundProcessGroupWrongTTY) {\npid_t pid = getpid();\nASSERT_THAT(ioctl(replica_.get(), TIOCSPGRP, &pid),\n"
}
] | Go | Apache License 2.0 | google/gvisor | added two system call tests for setForegroundProcessGroup
Test the correct sending of the SIGTTOU in setForegroundProcess |
259,880 | 17.08.2021 22:57:39 | -7,200 | 482de52b60d9ac0bc40f264c82c8eb094401a119 | Added a SIGTTOU block check in SetForegroundProcessGroup | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/thread_group.go",
"new_path": "pkg/sentry/kernel/thread_group.go",
"diff": "@@ -511,10 +511,13 @@ func (tg *ThreadGroup) SetForegroundProcessGroup(tty *TTY, pgid ProcessGroupID)\nreturn -1, linuxerr.EPERM\n}\n- sa:= tg.signalHandlers.actions[linux.SIGTTOU]\n- //if the calling process is a member of a background group, a SIGTTOU\n+ signalAction:= tg.signalHandlers.actions[linux.SIGTTOU]\n+ // If the calling process is a member of a background group, a SIGTTOU\n// signal is sent to all members of this background process group.\n- if tg.processGroup.id != tg.processGroup.session.foreground.id && sa.Handler!=linux.SIG_IGN{\n+ // We need also need to check whether it is ignoring or blocking SIGTTOU.\n+ ignored:= signalAction.Handler == linux.SIG_IGN\n+ blocked:= tg.leader.signalMask == linux.SignalSetOf(linux.SIGTTOU)\n+ if tg.processGroup.id != tg.processGroup.session.foreground.id && !ignored && !blocked{\ntg.leader.sendSignalLocked(SignalInfoPriv(linux.SIGTTOU),true)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added a SIGTTOU block check in SetForegroundProcessGroup |
260,001 | 18.08.2021 13:11:36 | 25,200 | 75b5a4f455c2e81bb38dcf786c788089ad1aebf7 | Add control configs
Also plumber the controls through runsc | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/control/BUILD",
"new_path": "pkg/sentry/control/BUILD",
"diff": "-load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools:defs.bzl\", \"go_library\", \"go_test\", \"proto_library\")\npackage(licenses = [\"notice\"])\n+proto_library(\n+ name = \"control\",\n+ srcs = [\"control.proto\"],\n+ visibility = [\"//visibility:public\"],\n+)\n+\ngo_library(\nname = \"control\",\nsrcs = [\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/control/control.proto",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+syntax = \"proto3\";\n+\n+package gvisor;\n+\n+// ControlConfig configures the permission of controls.\n+message ControlConfig {\n+ // Names for individual control URPC service objects.\n+ // Any new service object that should be given conditional access should be\n+ // named here and conditionally added based on presence in allowed_controls.\n+ enum Endpoint {\n+ UNKNOWN = 0;\n+ EVENTS = 1;\n+ FS = 2;\n+ LIFECYCLE = 3;\n+ LOGGING = 4;\n+ PROFILE = 5;\n+ USAGE = 6;\n+ PROC = 7;\n+ STATE = 8;\n+ DEBUG = 9;\n+ }\n+\n+ // allowed_controls represents which endpoints may be registered to the\n+ // server.\n+ repeated Endpoint allowed_controls = 1;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -45,6 +45,7 @@ go_library(\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/arch:registers_go_proto\",\n\"//pkg/sentry/control\",\n+ \"//pkg/sentry/control:control_go_proto\",\n\"//pkg/sentry/devices/memdev\",\n\"//pkg/sentry/devices/ttydev\",\n\"//pkg/sentry/devices/tundev\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/controller.go",
"new_path": "runsc/boot/controller.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/fd\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n+ controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netstack\"\n@@ -165,16 +166,32 @@ func newController(fd int, l *Loader) (*controller, error) {\nctrl.srv.Register(net)\n}\n- ctrl.srv.Register(&debug{})\n+ if l.root.conf.Controls.Controls != nil {\n+ for _, c := range l.root.conf.Controls.Controls.AllowedControls {\n+ switch c {\n+ case controlpb.ControlConfig_EVENTS:\nctrl.srv.Register(&control.Events{})\n+ case controlpb.ControlConfig_FS:\n+ ctrl.srv.Register(&control.Fs{Kernel: l.k})\n+ case controlpb.ControlConfig_LIFECYCLE:\n+ ctrl.srv.Register(&control.Lifecycle{Kernel: l.k})\n+ case controlpb.ControlConfig_LOGGING:\nctrl.srv.Register(&control.Logging{})\n- ctrl.srv.Register(&control.Lifecycle{l.k})\n- ctrl.srv.Register(&control.Fs{l.k})\n- ctrl.srv.Register(&control.Usage{l.k})\n-\n+ case controlpb.ControlConfig_PROFILE:\nif l.root.conf.ProfileEnable {\nctrl.srv.Register(control.NewProfile(l.k))\n}\n+ case controlpb.ControlConfig_USAGE:\n+ ctrl.srv.Register(&control.Usage{Kernel: l.k})\n+ case controlpb.ControlConfig_PROC:\n+ ctrl.srv.Register(&control.Proc{Kernel: l.k})\n+ case controlpb.ControlConfig_STATE:\n+ ctrl.srv.Register(&control.State{Kernel: l.k})\n+ case controlpb.ControlConfig_DEBUG:\n+ ctrl.srv.Register(&debug{})\n+ }\n+ }\n+ }\nreturn ctrl, nil\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/BUILD",
"new_path": "runsc/config/BUILD",
"diff": "@@ -11,6 +11,7 @@ go_library(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/refs\",\n+ \"//pkg/sentry/control:control_go_proto\",\n\"//pkg/sentry/watchdog\",\n\"//pkg/sync\",\n\"//runsc/flag\",\n@@ -24,5 +25,8 @@ go_test(\n\"config_test.go\",\n],\nlibrary = \":config\",\n- deps = [\"//runsc/flag\"],\n+ deps = [\n+ \"//pkg/sentry/control:control_go_proto\",\n+ \"//runsc/flag\",\n+ ],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -19,8 +19,10 @@ package config\nimport (\n\"fmt\"\n+ \"strings\"\n\"gvisor.dev/gvisor/pkg/refs\"\n+ controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n)\n@@ -135,6 +137,9 @@ type Config struct {\n// ProfileEnable is set to prepare the sandbox to be profiled.\nProfileEnable bool `flag:\"profile\"`\n+ // Controls defines the controls that may be enabled.\n+ Controls controlConfig `flag:\"controls\"`\n+\n// RestoreFile is the path to the saved container image\nRestoreFile string\n@@ -351,6 +356,96 @@ func (q QueueingDiscipline) String() string {\npanic(fmt.Sprintf(\"Invalid qdisc %d\", q))\n}\n+// controlConfig represents control endpoints.\n+type controlConfig struct {\n+ Controls *controlpb.ControlConfig\n+}\n+\n+// Set implements flag.Value.\n+func (c *controlConfig) Set(v string) error {\n+ controls := strings.Split(v, \",\")\n+ var controlList []controlpb.ControlConfig_Endpoint\n+ for _, control := range controls {\n+ switch control {\n+ case \"EVENTS\":\n+ controlList = append(controlList, controlpb.ControlConfig_EVENTS)\n+ case \"FS\":\n+ controlList = append(controlList, controlpb.ControlConfig_FS)\n+ case \"LIFECYCLE\":\n+ controlList = append(controlList, controlpb.ControlConfig_LIFECYCLE)\n+ case \"LOGGING\":\n+ controlList = append(controlList, controlpb.ControlConfig_LOGGING)\n+ case \"PROFILE\":\n+ controlList = append(controlList, controlpb.ControlConfig_PROFILE)\n+ case \"USAGE\":\n+ controlList = append(controlList, controlpb.ControlConfig_USAGE)\n+ case \"PROC\":\n+ controlList = append(controlList, controlpb.ControlConfig_PROC)\n+ case \"STATE\":\n+ controlList = append(controlList, controlpb.ControlConfig_STATE)\n+ case \"DEBUG\":\n+ controlList = append(controlList, controlpb.ControlConfig_DEBUG)\n+ default:\n+ return fmt.Errorf(\"invalid control %q\", control)\n+ }\n+ }\n+ c.Controls.AllowedControls = controlList\n+ return nil\n+}\n+\n+// Get implements flag.Value.\n+func (c *controlConfig) Get() interface{} {\n+ return *c\n+}\n+\n+// String implements flag.Value.\n+func (c *controlConfig) String() string {\n+ v := \"\"\n+ for _, control := range c.Controls.AllowedControls {\n+ if len(v) > 0 {\n+ v += \",\"\n+ }\n+ switch control {\n+ case controlpb.ControlConfig_EVENTS:\n+ v += \"EVENTS\"\n+ case controlpb.ControlConfig_FS:\n+ v += \"FS\"\n+ case controlpb.ControlConfig_LIFECYCLE:\n+ v += \"LIFECYCLE\"\n+ case controlpb.ControlConfig_LOGGING:\n+ v += \"LOGGING\"\n+ case controlpb.ControlConfig_PROFILE:\n+ v += \"PROFILE\"\n+ case controlpb.ControlConfig_USAGE:\n+ v += \"USAGE\"\n+ case controlpb.ControlConfig_PROC:\n+ v += \"PROC\"\n+ case controlpb.ControlConfig_STATE:\n+ v += \"STATE\"\n+ case controlpb.ControlConfig_DEBUG:\n+ v += \"DEBUG\"\n+ default:\n+ panic(fmt.Sprintf(\"Invalid control %d\", control))\n+ }\n+ }\n+ return v\n+}\n+\n+func defaultControlConfig() *controlConfig {\n+ c := controlConfig{}\n+ c.Controls = &controlpb.ControlConfig{}\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_EVENTS)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_FS)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_LIFECYCLE)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_LOGGING)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_PROFILE)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_USAGE)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_PROC)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_STATE)\n+ c.Controls.AllowedControls = append(c.Controls.AllowedControls, controlpb.ControlConfig_DEBUG)\n+ return &c\n+}\n+\nfunc leakModePtr(v refs.LeakMode) *refs.LeakMode {\nreturn &v\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/config_test.go",
"new_path": "runsc/config/config_test.go",
"diff": "@@ -18,6 +18,7 @@ import (\n\"strings\"\n\"testing\"\n+ controlpb \"gvisor.dev/gvisor/pkg/sentry/control/control_go_proto\"\n\"gvisor.dev/gvisor/runsc/flag\"\n)\n@@ -59,6 +60,9 @@ func TestFromFlags(t *testing.T) {\nif err := flag.CommandLine.Lookup(\"network\").Value.Set(\"none\"); err != nil {\nt.Errorf(\"Flag set: %v\", err)\n}\n+ if err := flag.CommandLine.Lookup(\"controls\").Value.Set(\"EVENTS,FS\"); err != nil {\n+ t.Errorf(\"Flag set: %v\", err)\n+ }\ndefer func() {\nif err := setDefault(\"root\"); err != nil {\nt.Errorf(\"Flag set: %v\", err)\n@@ -72,6 +76,9 @@ func TestFromFlags(t *testing.T) {\nif err := setDefault(\"network\"); err != nil {\nt.Errorf(\"Flag set: %v\", err)\n}\n+ if err := setDefault(\"controls\"); err != nil {\n+ t.Errorf(\"Flag set: %v\", err)\n+ }\n}()\nc, err := NewFromFlags()\n@@ -90,6 +97,12 @@ func TestFromFlags(t *testing.T) {\nif want := NetworkNone; c.Network != want {\nt.Errorf(\"Network=%v, want: %v\", c.Network, want)\n}\n+ wants := []controlpb.ControlConfig_Endpoint{controlpb.ControlConfig_EVENTS, controlpb.ControlConfig_FS}\n+ for i, want := range wants {\n+ if c.Controls.Controls.AllowedControls[i] != want {\n+ t.Errorf(\"Controls.Controls.AllowedControls[%d]=%v, want: %v\", i, c.Controls.Controls.AllowedControls[i], want)\n+ }\n+ }\n}\nfunc TestToFlags(t *testing.T) {\n@@ -101,10 +114,15 @@ func TestToFlags(t *testing.T) {\nc.Debug = true\nc.NumNetworkChannels = 123\nc.Network = NetworkNone\n+ c.Controls = controlConfig{\n+ Controls: &controlpb.ControlConfig{\n+ AllowedControls: []controlpb.ControlConfig_Endpoint{controlpb.ControlConfig_EVENTS, controlpb.ControlConfig_FS},\n+ },\n+ }\nflags := c.ToFlags()\n- if len(flags) != 4 {\n- t.Errorf(\"wrong number of flags set, want: 4, got: %d: %s\", len(flags), flags)\n+ if len(flags) != 5 {\n+ t.Errorf(\"wrong number of flags set, want: 5, got: %d: %s\", len(flags), flags)\n}\nt.Logf(\"Flags: %s\", flags)\nfm := map[string]string{}\n@@ -117,6 +135,7 @@ func TestToFlags(t *testing.T) {\n\"--debug\": \"true\",\n\"--num-network-channels\": \"123\",\n\"--network\": \"none\",\n+ \"--controls\": \"EVENTS,FS\",\n} {\nif got, ok := fm[name]; ok {\nif got != want {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/config/flags.go",
"new_path": "runsc/config/flags.go",
"diff": "@@ -67,6 +67,7 @@ func RegisterFlags() {\nflag.Var(leakModePtr(refs.NoLeakChecking), \"ref-leak-mode\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\nflag.Bool(\"cpu-num-from-quota\", false, \"set cpu number to cpu quota (least integer greater or equal to quota value, but not less than 2)\")\nflag.Bool(\"oci-seccomp\", false, \"Enables loading OCI seccomp filters inside the sandbox.\")\n+ flag.Var(defaultControlConfig(), \"controls\", \"Sentry control endpoints.\")\n// Flags that control sandbox runtime behavior: FS related.\nflag.Var(fileAccessTypePtr(FileAccessExclusive), \"file-access\", \"specifies which filesystem validation to use for the root mount: exclusive (default), shared.\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add control configs
Also plumber the controls through runsc
PiperOrigin-RevId: 391594318 |
259,880 | 17.08.2021 23:25:47 | -7,200 | ce4e54186e7c4a59bcdd9a74d89c5d4c2a7174f9 | Added a system call test for SetForegroundProcessGroup
Added a test to check if the process in background is blocking SIGTTOU
Some minor formatting fixes | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1640,18 +1640,18 @@ TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroup) {\nASSERT_NO_ERRNO(res);\n}\n-// This test verify if a SIGTTOU signal is sent to the calling process'group\n+// This test verifies if a SIGTTOU signal is sent to the calling process's group\n// when tcsetpgrp is called by a background process\nTEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBackground) {\nauto res = RunInChild([=]() {\n- setsid();\n+ TEST_PCHECK(setsid() >= 0);\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\npid_t grandchild = fork();\nif (!grandchild) {\n- //assign a different pgid to the child so it will result as\n- //a background process\n- setpgid(grandchild, getpid());\n- tcsetpgrp(replica_.get(), getpgid(0));\n+ // Assign a different pgid to the child so it will result as\n+ // a background process.\n+ TEST_PCHECK(!setpgid(grandchild, getpid()));\n+ TEST_PCHECK(!tcsetpgrp(replica_.get(), getpgid(0)));\n// We should never reach this.\n_exit(1);\n}\n@@ -1662,25 +1662,25 @@ TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBackground) {\nASSERT_NO_ERRNO(res);\n}\n-// This test verify that a SIGTTOU signal is not delivered to\n+// This test verifies that a SIGTTOU signal is not delivered to\n// a background process which calls tcsetpgrp and is ignoring SIGTTOU\nTEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUIgnored) {\nauto res = RunInChild([=]() {\n- setsid();\n+ TEST_PCHECK(setsid() >= 0);\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\npid_t grandchild = fork();\nif (!grandchild) {\n- // ignore SIGTTOU so the child in background won't\n+ // Ignore SIGTTOU so the child in background won't\n// be stopped when it will call tcsetpgrp\nstruct sigaction sa = {};\nsa.sa_handler = SIG_IGN;\nsa.sa_flags = 0;\nsigemptyset(&sa.sa_mask);\nsigaction(SIGTTOU, &sa, NULL);\n- //assign a different pgid to the child so it will result as\n- //a background process\n- setpgid(grandchild, getpid());\n- tcsetpgrp(replica_.get(), getpgid(0));\n+ // Assign a different pgid to the child so it will result as\n+ // a background process.\n+ TEST_PCHECK(!setpgid(grandchild, getpid()));\n+ TEST_PCHECK(!tcsetpgrp(replica_.get(), getpgid(0)));\n_exit(0);\n}\nint wstatus;\n@@ -1691,6 +1691,33 @@ TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUIgnored) {\nASSERT_NO_ERRNO(res);\n}\n+// This test verifies that a SIGTTOU signal is not delivered to\n+// a background process which calls tcsetpgrp and is blocking SIGTTOU\n+TEST_F(JobControlTest, SetForegroundProcessGroupSIGTTOUBlocked) {\n+ auto res = RunInChild([=]() {\n+ TEST_PCHECK(setsid() >= 0);\n+ TEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n+ pid_t grandchild = fork();\n+ if (!grandchild) {\n+ // Block SIGTTOU so the child in background won't\n+ // be stopped when it will call tcsetpgrp\n+ sigset_t signal_set;\n+ sigemptyset(&signal_set);\n+ sigaddset(&signal_set, SIGTTOU);\n+ sigprocmask(SIG_BLOCK, &signal_set, NULL);\n+ // Assign a different pgid to the child so it will result as\n+ // a background process.\n+ TEST_PCHECK(!setpgid(grandchild, getpid()));\n+ TEST_PCHECK(!tcsetpgrp(replica_.get(), getpgid(0)));\n+ _exit(0);\n+ }\n+ int wstatus;\n+ TEST_PCHECK(waitpid(grandchild, &wstatus, WSTOPPED) == grandchild);\n+ TEST_PCHECK(WSTOPSIG(wstatus) != SIGTTOU);\n+ });\n+ ASSERT_NO_ERRNO(res);\n+}\n+\nTEST_F(JobControlTest, SetForegroundProcessGroupWrongTTY) {\npid_t pid = getpid();\nASSERT_THAT(ioctl(replica_.get(), TIOCSPGRP, &pid),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added a system call test for SetForegroundProcessGroup
-Added a test to check if the process in background is blocking SIGTTOU
-Some minor formatting fixes |
259,898 | 18.08.2021 16:56:40 | 25,200 | a4ae5fed32c09d5c09b4d540b9d5faa8fcd5dda1 | Split TCP secrets from Stack to tcp.protocol
Use different secrets for different purposes (port picking,
ISN generation, tsOffset generation) and moved the secrets
from stack.Stack to tcp.protocol. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -119,8 +119,7 @@ type Stack struct {\n// by the stack.\nicmpRateLimiter *ICMPRateLimiter\n- // seed is a one-time random value initialized at stack startup\n- // and is used to seed the TCP port picking on active connections\n+ // seed is a one-time random value initialized at stack startup.\n//\n// TODO(gvisor.dev/issue/940): S/R this field.\nseed uint32\n@@ -1819,14 +1818,6 @@ func (s *Stack) SetNUDConfigurations(id tcpip.NICID, proto tcpip.NetworkProtocol\nreturn nic.setNUDConfigs(proto, c)\n}\n-// Seed returns a 32 bit value that can be used as a seed value for port\n-// picking, ISN generation etc.\n-//\n-// NOTE: The seed is generated once during stack initialization only.\n-func (s *Stack) Seed() uint32 {\n- return s.seed\n-}\n-\n// Rand returns a reference to a pseudo random generator that can be used\n// to generate random numbers as required.\nfunc (s *Stack) Rand() *rand.Rand {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_demuxer.go",
"new_path": "pkg/tcpip/stack/transport_demuxer.go",
"diff": "@@ -479,7 +479,7 @@ func (d *transportDemuxer) singleRegisterEndpoint(netProto tcpip.NetworkProtocol\nif !ok {\nepsByNIC = &endpointsByNIC{\nendpoints: make(map[tcpip.NICID]*multiPortEndpoint),\n- seed: d.stack.Seed(),\n+ seed: d.stack.seed,\n}\n}\nif err := epsByNIC.registerEndpoint(d, netProto, protocol, ep, flags, bindToDevice); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -73,6 +73,7 @@ func encodeMSS(mss uint16) uint32 {\n// may mutate the stored objects.\ntype listenContext struct {\nstack *stack.Stack\n+ protocol *protocol\n// rcvWnd is the receive window that is sent by this listening context\n// in the initial SYN-ACK.\n@@ -119,9 +120,10 @@ func timeStamp(clock tcpip.Clock) uint32 {\n}\n// newListenContext creates a new listen context.\n-func newListenContext(stk *stack.Stack, listenEP *endpoint, rcvWnd seqnum.Size, v6Only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {\n+func newListenContext(stk *stack.Stack, protocol *protocol, listenEP *endpoint, rcvWnd seqnum.Size, v6Only bool, netProto tcpip.NetworkProtocolNumber) *listenContext {\nl := &listenContext{\nstack: stk,\n+ protocol: protocol,\nrcvWnd: rcvWnd,\nhasher: sha1.New(),\nv6Only: v6Only,\n@@ -213,7 +215,7 @@ func (l *listenContext) createConnectingEndpoint(s *segment, rcvdSynOpts *header\nreturn nil, err\n}\n- n := newEndpoint(l.stack, netProto, queue)\n+ n := newEndpoint(l.stack, l.protocol, netProto, queue)\nn.ops.SetV6Only(l.v6Only)\nn.TransportEndpointInfo.ID = s.id\nn.boundNICID = s.nicID\n@@ -247,7 +249,7 @@ func (l *listenContext) createConnectingEndpoint(s *segment, rcvdSynOpts *header\nfunc (l *listenContext) startHandshake(s *segment, opts *header.TCPSynOptions, queue *waiter.Queue, owner tcpip.PacketOwner) (*handshake, tcpip.Error) {\n// Create new endpoint.\nirs := s.sequenceNumber\n- isn := generateSecureISN(s.id, l.stack.Clock(), l.stack.Seed())\n+ isn := generateSecureISN(s.id, l.stack.Clock(), l.protocol.seqnumSecret)\nep, err := l.createConnectingEndpoint(s, opts, queue)\nif err != nil {\nreturn nil, err\n@@ -779,7 +781,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nfunc (e *endpoint) protocolListenLoop(rcvWnd seqnum.Size) {\ne.mu.Lock()\nv6Only := e.ops.GetV6Only()\n- ctx := newListenContext(e.stack, e, rcvWnd, v6Only, e.NetProto)\n+ ctx := newListenContext(e.stack, e.protocol, e, rcvWnd, v6Only, e.NetProto)\ndefer func() {\n// Mark endpoint as closed. This will prevent goroutines running\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -150,7 +150,7 @@ func (h *handshake) resetState() {\nh.flags = header.TCPFlagSyn\nh.ackNum = 0\nh.mss = 0\n- h.iss = generateSecureISN(h.ep.TransportEndpointInfo.ID, h.ep.stack.Clock(), h.ep.stack.Seed())\n+ h.iss = generateSecureISN(h.ep.TransportEndpointInfo.ID, h.ep.stack.Clock(), h.ep.protocol.seqnumSecret)\n}\n// generateSecureISN generates a secure Initial Sequence number based on the\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -378,6 +378,7 @@ type endpoint struct {\n// The following fields are initialized at creation time and do not\n// change throughout the lifetime of the endpoint.\nstack *stack.Stack `state:\"manual\"`\n+ protocol *protocol `state:\"manual\"`\nwaiterQueue *waiter.Queue `state:\"wait\"`\nuniqueID uint64\n@@ -803,9 +804,10 @@ type keepalive struct {\nwaker sleep.Waker `state:\"nosave\"`\n}\n-func newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) *endpoint {\n+func newEndpoint(s *stack.Stack, protocol *protocol, netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) *endpoint {\ne := &endpoint{\nstack: s,\n+ protocol: protocol,\nTransportEndpointInfo: stack.TransportEndpointInfo{\nNetProto: netProto,\nTransProto: header.TCPProtocolNumber,\n@@ -2198,7 +2200,7 @@ func (e *endpoint) connect(addr tcpip.FullAddress, handshake bool, run bool) tcp\nportBuf := make([]byte, 2)\nbinary.LittleEndian.PutUint16(portBuf, e.ID.RemotePort)\n- h := jenkins.Sum32(e.stack.Seed())\n+ h := jenkins.Sum32(e.protocol.portOffsetSecret)\nfor _, s := range [][]byte{\n[]byte(e.ID.LocalAddress),\n[]byte(e.ID.RemoteAddress),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint_state.go",
"diff": "@@ -170,6 +170,7 @@ func (e *endpoint) Resume(s *stack.Stack) {\nsnd.probeTimer.init(s.Clock(), &snd.probeWaker)\n}\ne.stack = s\n+ e.protocol = protocolFromStack(s)\ne.ops.InitHandler(e, e.stack, GetTCPSendBufferLimits, GetTCPReceiveBufferLimits)\ne.segmentQueue.thaw()\nepState := EndpointState(e.origEndpointState)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/forwarder.go",
"new_path": "pkg/tcpip/transport/tcp/forwarder.go",
"diff": "@@ -54,7 +54,7 @@ func NewForwarder(s *stack.Stack, rcvWnd, maxInFlight int, handler func(*Forward\nmaxInFlight: maxInFlight,\nhandler: handler,\ninFlight: make(map[stack.TransportEndpointID]struct{}),\n- listen: newListenContext(s, nil /* listenEP */, seqnum.Size(rcvWnd), true, 0),\n+ listen: newListenContext(s, protocolFromStack(s), nil /* listenEP */, seqnum.Size(rcvWnd), true, 0),\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -96,6 +96,9 @@ type protocol struct {\nmaxRetries uint32\nsynRetries uint8\ndispatcher dispatcher\n+ // The following secrets are initialized once and stay unchanged after.\n+ seqnumSecret uint32\n+ portOffsetSecret uint32\n}\n// Number returns the tcp protocol number.\n@@ -105,7 +108,7 @@ func (*protocol) Number() tcpip.TransportProtocolNumber {\n// NewEndpoint creates a new tcp endpoint.\nfunc (p *protocol) NewEndpoint(netProto tcpip.NetworkProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, tcpip.Error) {\n- return newEndpoint(p.stack, netProto, waiterQueue), nil\n+ return newEndpoint(p.stack, p, netProto, waiterQueue), nil\n}\n// NewRawEndpoint creates a new raw TCP endpoint. Raw TCP sockets are currently\n@@ -479,7 +482,14 @@ func NewProtocol(s *stack.Stack) stack.TransportProtocol {\nmaxRTO: MaxRTO,\nmaxRetries: MaxRetries,\nrecovery: tcpip.TCPRACKLossDetection,\n+ seqnumSecret: s.Rand().Uint32(),\n+ portOffsetSecret: s.Rand().Uint32(),\n}\np.dispatcher.init(s.Rand(), runtime.GOMAXPROCS(0))\nreturn &p\n}\n+\n+// protocolFromStack retrieves the tcp.protocol instance from stack s.\n+func protocolFromStack(s *stack.Stack) *protocol {\n+ return s.TransportProtocolInstance(ProtocolNumber).(*protocol)\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Split TCP secrets from Stack to tcp.protocol
Use different secrets for different purposes (port picking,
ISN generation, tsOffset generation) and moved the secrets
from stack.Stack to tcp.protocol.
PiperOrigin-RevId: 391641238 |
259,898 | 19.08.2021 13:12:50 | 25,200 | 50ed6b2e0994225b9bffa63b57a42da2d05e02b9 | Use a hash function to generate tcp timestamp offset
Also fix an option parsing error in checker.TCPTimestampChecker while I am here. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -729,7 +729,7 @@ func TCPTimestampChecker(wantTS bool, wantTSVal uint32, wantTSEcr uint32) Transp\nreturn\n}\nl := int(opts[i+1])\n- if i < 2 || i+l > limit {\n+ if l < 2 || i+l > limit {\nreturn\n}\ni += l\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -160,6 +160,10 @@ type Stack struct {\n// This is required to prevent potential ACK loops.\n// Setting this to 0 will disable all rate limiting.\ntcpInvalidRateLimit time.Duration\n+\n+ // tsOffsetSecret is the secret key for generating timestamp offsets\n+ // initialized at stack startup.\n+ tsOffsetSecret uint32\n}\n// UniqueID is an abstract generator of unique identifiers.\n@@ -383,6 +387,7 @@ func New(opts Options) *Stack {\nMax: DefaultMaxBufferSize,\n},\ntcpInvalidRateLimit: defaultTCPInvalidRateLimit,\n+ tsOffsetSecret: randomGenerator.Uint32(),\n}\n// Add specified network protocols.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/BUILD",
"new_path": "pkg/tcpip/transport/tcp/BUILD",
"diff": "@@ -96,6 +96,7 @@ go_test(\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/checker\",\n+ \"//pkg/tcpip/faketime\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/loopback\",\n\"//pkg/tcpip/link/sniffer\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -602,7 +602,7 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nsynOpts := header.TCPSynOptions{\nWS: -1,\nTS: opts.TS,\n- TSVal: tcpTimeStamp(e.stack.Clock().NowMonotonic(), timeStampOffset(e.stack.Rand())),\n+ TSVal: tcpTimeStamp(e.stack.Clock().NowMonotonic(), timeStampOffset(e.protocol.tsOffsetSecret, s.dstAddr, s.srcAddr)),\nTSEcr: opts.TSVal,\nMSS: calculateAdvertisedMSS(e.userMSS, route),\n}\n@@ -728,11 +728,9 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nn.isRegistered = true\n- // clear the tsOffset for the newly created\n- // endpoint as the Timestamp was already\n- // randomly offset when the original SYN-ACK was\n- // sent above.\n- n.TSOffset = 0\n+ // Reset the tsOffset for the newly created endpoint to the one\n+ // that we have used in SYN-ACK in order to calculate RTT.\n+ n.TSOffset = timeStampOffset(e.protocol.tsOffsetSecret, s.dstAddr, s.srcAddr)\n// Switch state to connected.\nn.isConnectNotified = true\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -117,6 +117,8 @@ func (e *endpoint) newHandshake() *handshake {\nh.resetState()\n// Store reference to handshake state in endpoint.\ne.h = h\n+ // By the time handshake is created, e.ID is already initialized.\n+ e.TSOffset = timeStampOffset(e.protocol.tsOffsetSecret, e.ID.LocalAddress, e.ID.RemoteAddress)\nreturn h\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"fmt\"\n\"io\"\n\"math\"\n- \"math/rand\"\n\"runtime\"\n\"strings\"\n\"sync/atomic\"\n@@ -876,7 +875,7 @@ func newEndpoint(s *stack.Stack, protocol *protocol, netProto tcpip.NetworkProto\n}\ne.segmentQueue.ep = e\n- e.TSOffset = timeStampOffset(e.stack.Rand())\n+\ne.acceptCond = sync.NewCond(&e.acceptMu)\ne.keepalive.timer.init(e.stack.Clock(), &e.keepalive.waker)\n@@ -2929,17 +2928,22 @@ func tcpTimeStamp(curTime tcpip.MonotonicTime, offset uint32) uint32 {\n// timeStampOffset returns a randomized timestamp offset to be used when sending\n// timestamp values in a timestamp option for a TCP segment.\n-func timeStampOffset(rng *rand.Rand) uint32 {\n+func timeStampOffset(secret uint32, src, dst tcpip.Address) uint32 {\n// Initialize a random tsOffset that will be added to the recentTS\n// everytime the timestamp is sent when the Timestamp option is enabled.\n//\n// See https://tools.ietf.org/html/rfc7323#section-5.4 for details on\n// why this is required.\n//\n- // NOTE: This is not completely to spec as normally this should be\n- // initialized in a manner analogous to how sequence numbers are\n- // randomized per connection basis. But for now this is sufficient.\n- return rng.Uint32()\n+ // TODO(https://gvisor.dev/issues/6473): This is not really secure as\n+ // it does not use the recommended algorithm linked above.\n+ h := jenkins.Sum32(secret)\n+ // Per hash.Hash.Writer:\n+ //\n+ // It never returns an error.\n+ _, _ = h.Write([]byte(src))\n+ _, _ = h.Write([]byte(dst))\n+ return h.Sum32()\n}\n// maybeEnableSACKPermitted marks the SACKPermitted option enabled for this endpoint\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -99,6 +99,7 @@ type protocol struct {\n// The following secrets are initialized once and stay unchanged after.\nseqnumSecret uint32\nportOffsetSecret uint32\n+ tsOffsetSecret uint32\n}\n// Number returns the tcp protocol number.\n@@ -484,6 +485,7 @@ func NewProtocol(s *stack.Stack) stack.TransportProtocol {\nrecovery: tcpip.TCPRACKLossDetection,\nseqnumSecret: s.Rand().Uint32(),\nportOffsetSecret: s.Rand().Uint32(),\n+ tsOffsetSecret: s.Rand().Uint32(),\n}\np.dispatcher.init(s.Rand(), runtime.GOMAXPROCS(0))\nreturn &p\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -28,6 +28,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/faketime\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/sniffer\"\n@@ -8056,3 +8057,93 @@ func TestSendBufferTuning(t *testing.T) {\n})\n}\n}\n+\n+func TestTimestampSynCookies(t *testing.T) {\n+ clock := faketime.NewManualClock()\n+ c := context.NewWithOpts(t, context.Options{\n+ EnableV4: true,\n+ EnableV6: true,\n+ MTU: defaultMTU,\n+ Clock: clock,\n+ })\n+ defer c.Cleanup()\n+ opt := tcpip.TCPAlwaysUseSynCookies(true)\n+ if err := c.Stack().SetTransportProtocolOption(tcp.ProtocolNumber, &opt); err != nil {\n+ t.Fatalf(\"SetTransportProtocolOption(%d, &%T(%t)): %s\", tcp.ProtocolNumber, opt, opt, err)\n+ }\n+ wq := &waiter.Queue{}\n+ ep, err := c.Stack().NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, wq)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint failed: %s\", err)\n+ }\n+ defer ep.Close()\n+\n+ tcpOpts := [12]byte{header.TCPOptionNOP, header.TCPOptionNOP}\n+ header.EncodeTSOption(42, 0, tcpOpts[2:])\n+ if err := ep.Bind(tcpip.FullAddress{Port: context.StackPort}); err != nil {\n+ t.Fatalf(\"Bind failed: %s\", err)\n+ }\n+ if err := ep.Listen(10); err != nil {\n+ t.Fatalf(\"Listen failed: %s\", err)\n+ }\n+ iss := seqnum.Value(context.TestInitialSequenceNumber)\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagSyn,\n+ RcvWnd: seqnum.Size(512),\n+ SeqNum: iss,\n+ TCPOpts: tcpOpts[:],\n+ })\n+ // Get the TSVal of SYN-ACK.\n+ b := c.GetPacket()\n+ tcpHdr := header.TCP(header.IPv4(b).Payload())\n+ c.IRS = seqnum.Value(tcpHdr.SequenceNumber())\n+ initialTSVal := tcpHdr.ParsedOptions().TSVal\n+\n+ header.EncodeTSOption(420, initialTSVal, tcpOpts[2:])\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: context.StackPort,\n+ Flags: header.TCPFlagAck,\n+ RcvWnd: seqnum.Size(512),\n+ SeqNum: iss + 1,\n+ AckNum: c.IRS + 1,\n+ TCPOpts: tcpOpts[:],\n+ })\n+ c.EP, _, err = ep.Accept(nil)\n+ // Try to accept the connection.\n+ we, ch := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.ReadableEvents)\n+ defer wq.EventUnregister(&we)\n+ if cmp.Equal(&tcpip.ErrWouldBlock{}, err) {\n+ // Wait for connection to be established.\n+ select {\n+ case <-ch:\n+ c.EP, _, err = ep.Accept(nil)\n+ if err != nil {\n+ t.Fatalf(\"Accept failed: %s\", err)\n+ }\n+\n+ case <-time.After(1 * time.Second):\n+ t.Fatalf(\"Timed out waiting for accept\")\n+ }\n+ } else if err != nil {\n+ t.Fatalf(\"failed to accept: %s\", err)\n+ }\n+\n+ const elapsed = 200 * time.Millisecond\n+ clock.Advance(elapsed)\n+ data := []byte{1, 2, 3}\n+ var r bytes.Reader\n+ r.Reset(data)\n+ if _, err := c.EP.Write(&r, tcpip.WriteOptions{}); err != nil {\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+\n+ // The endpoint should have a correct TSOffset so that the received TSVal\n+ // should match our expectation.\n+ if got, want := header.TCP(header.IPv4(c.GetPacket()).Payload()).ParsedOptions().TSVal, initialTSVal+uint32(elapsed.Milliseconds()); got != want {\n+ t.Fatalf(\"got TSVal = %d, want %d\", got, want)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"new_path": "pkg/tcpip/transport/tcp/testing/context/context.go",
"diff": "@@ -122,6 +122,9 @@ type Options struct {\n// MTU indicates the maximum transmission unit on the link layer.\nMTU uint32\n+\n+ // Clock that is used by Stack.\n+ Clock tcpip.Clock\n}\n// Context provides an initialized Network stack and a link layer endpoint\n@@ -182,6 +185,7 @@ func NewWithOpts(t *testing.T, opts Options) *Context {\nstackOpts := stack.Options{\nTransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ Clock: opts.Clock,\n}\nif opts.EnableV4 {\nstackOpts.NetworkProtocols = append(stackOpts.NetworkProtocols, ipv4.NewProtocol)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use a hash function to generate tcp timestamp offset
Also fix an option parsing error in checker.TCPTimestampChecker while I am here.
PiperOrigin-RevId: 391828329 |
259,885 | 19.08.2021 17:08:02 | 25,200 | a77eaf2a9e0539326defc766d748b8eff1d89b0b | Use MM-mapped I/O instead of buffered copies in gofer.specialFileFD.
The rationale given for using buffered copies is still valid, but it's unclear
whether holding MM locks or allocating buffers is better in practice, and the
former is at least consistent with gofer.regularFileFD (and VFS1), making
performance easier to reason about. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/handle.go",
"new_path": "pkg/sentry/fsimpl/gofer/handle.go",
"diff": "@@ -20,6 +20,7 @@ import (\n\"gvisor.dev/gvisor/pkg/p9\"\n\"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/hostfd\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n)\n// handle represents a remote \"open file descriptor\", consisting of an opened\n@@ -130,3 +131,43 @@ func (h *handle) writeFromBlocksAt(ctx context.Context, srcs safemem.BlockSeq, o\n}\nreturn uint64(n), cperr\n}\n+\n+type handleReadWriter struct {\n+ ctx context.Context\n+ h *handle\n+ off uint64\n+}\n+\n+var handleReadWriterPool = sync.Pool{\n+ New: func() interface{} {\n+ return &handleReadWriter{}\n+ },\n+}\n+\n+func getHandleReadWriter(ctx context.Context, h *handle, offset int64) *handleReadWriter {\n+ rw := handleReadWriterPool.Get().(*handleReadWriter)\n+ rw.ctx = ctx\n+ rw.h = h\n+ rw.off = uint64(offset)\n+ return rw\n+}\n+\n+func putHandleReadWriter(rw *handleReadWriter) {\n+ rw.ctx = nil\n+ rw.h = nil\n+ handleReadWriterPool.Put(rw)\n+}\n+\n+// ReadToBlocks implements safemem.Reader.ReadToBlocks.\n+func (rw *handleReadWriter) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\n+ n, err := rw.h.readToBlocksAt(rw.ctx, dsts, rw.off)\n+ rw.off += n\n+ return n, err\n+}\n+\n+// WriteFromBlocks implements safemem.Writer.WriteFromBlocks.\n+func (rw *handleReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error) {\n+ n, err := rw.h.writeFromBlocksAt(rw.ctx, srcs, rw.off)\n+ rw.off += n\n+ return n, err\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/special_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/special_file.go",
"diff": "@@ -24,7 +24,6 @@ import (\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n\"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/p9\"\n- \"gvisor.dev/gvisor/pkg/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/fsmetric\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sync\"\n@@ -229,23 +228,13 @@ func (fd *specialFileFD) PRead(ctx context.Context, dst usermem.IOSequence, offs\n}\n}\n- // Going through dst.CopyOutFrom() would hold MM locks around file\n- // operations of unknown duration. For regularFileFD, doing so is necessary\n- // to support mmap due to lock ordering; MM locks precede dentry.dataMu.\n- // That doesn't hold here since specialFileFD doesn't client-cache data.\n- // Just buffer the read instead.\n- buf := make([]byte, dst.NumBytes())\n- n, err := fd.handle.readToBlocksAt(ctx, safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf)), uint64(offset))\n+ rw := getHandleReadWriter(ctx, &fd.handle, offset)\n+ n, err := dst.CopyOutFrom(ctx, rw)\n+ putHandleReadWriter(rw)\nif linuxerr.Equals(linuxerr.EAGAIN, err) {\nerr = linuxerr.ErrWouldBlock\n}\n- if n == 0 {\n- return bufN, err\n- }\n- if cp, cperr := dst.CopyOut(ctx, buf[:n]); cperr != nil {\n- return bufN + int64(cp), cperr\n- }\n- return bufN + int64(n), err\n+ return bufN + n, err\n}\n// Read implements vfs.FileDescriptionImpl.Read.\n@@ -316,20 +305,15 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\n}\n}\n- // Do a buffered write. See rationale in PRead.\n- buf := make([]byte, src.NumBytes())\n- copied, copyErr := src.CopyIn(ctx, buf)\n- if copied == 0 && copyErr != nil {\n- // Only return the error if we didn't get any data.\n- return 0, offset, copyErr\n- }\n- n, err := fd.handle.writeFromBlocksAt(ctx, safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf[:copied])), uint64(offset))\n+ rw := getHandleReadWriter(ctx, &fd.handle, offset)\n+ n, err := src.CopyInTo(ctx, rw)\n+ putHandleReadWriter(rw)\nif linuxerr.Equals(linuxerr.EAGAIN, err) {\nerr = linuxerr.ErrWouldBlock\n}\n// Update offset if the offset is valid.\nif offset >= 0 {\n- offset += int64(n)\n+ offset += n\n}\n// Update file size for regular files.\nif fd.isRegularFile {\n@@ -340,11 +324,8 @@ func (fd *specialFileFD) pwrite(ctx context.Context, src usermem.IOSequence, off\natomic.StoreUint64(&d.size, uint64(offset))\n}\n}\n- if err != nil {\nreturn int64(n), offset, err\n}\n- return int64(n), offset, copyErr\n-}\n// Write implements vfs.FileDescriptionImpl.Write.\nfunc (fd *specialFileFD) Write(ctx context.Context, src usermem.IOSequence, opts vfs.WriteOptions) (int64, error) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use MM-mapped I/O instead of buffered copies in gofer.specialFileFD.
The rationale given for using buffered copies is still valid, but it's unclear
whether holding MM locks or allocating buffers is better in practice, and the
former is at least consistent with gofer.regularFileFD (and VFS1), making
performance easier to reason about.
PiperOrigin-RevId: 391877913 |
260,001 | 19.08.2021 17:20:21 | 25,200 | 3ba8df92a86aa1044ab59110c640ba413341b9f3 | Cache verity dentries
Add an LRU cache to cache verity dentries when ref count drop to 0. This
way we don't need to hash and verify the previous opened files or
directories each time. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/BUILD",
"new_path": "pkg/sentry/fsimpl/verity/BUILD",
"diff": "load(\"//tools:defs.bzl\", \"go_library\", \"go_test\")\n+load(\"//tools/go_generics:defs.bzl\", \"go_template_instance\")\nlicenses([\"notice\"])\n+go_template_instance(\n+ name = \"dentry_list\",\n+ out = \"dentry_list.go\",\n+ package = \"verity\",\n+ prefix = \"dentry\",\n+ template = \"//pkg/ilist:generic_list\",\n+ types = {\n+ \"Element\": \"*dentry\",\n+ \"Linker\": \"*dentry\",\n+ },\n+)\n+\ngo_library(\nname = \"verity\",\nsrcs = [\n+ \"dentry_list.go\",\n\"filesystem.go\",\n\"save_restore.go\",\n\"verity.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"new_path": "pkg/sentry/fsimpl/verity/filesystem.go",
"diff": "@@ -66,40 +66,23 @@ func putDentrySlice(ds *[]*dentry) {\ndentrySlicePool.Put(ds)\n}\n-// renameMuRUnlockAndCheckDrop calls fs.renameMu.RUnlock(), then calls\n-// dentry.checkDropLocked on all dentries in *ds with fs.renameMu locked for\n+// renameMuRUnlockAndCheckCaching calls fs.renameMu.RUnlock(), then calls\n+// dentry.checkCachingLocked on all dentries in *ds with fs.renameMu locked for\n// writing.\n//\n// ds is a pointer-to-pointer since defer evaluates its arguments immediately,\n// but dentry slices are allocated lazily, and it's much easier to say \"defer\n-// fs.renameMuRUnlockAndCheckDrop(&ds)\" than \"defer func() {\n-// fs.renameMuRUnlockAndCheckDrop(ds) }()\" to work around this.\n+// fs.renameMuRUnlockAndCheckCaching(&ds)\" than \"defer func() {\n+// fs.renameMuRUnlockAndCheckCaching(ds) }()\" to work around this.\n// +checklocksrelease:fs.renameMu\n-func (fs *filesystem) renameMuRUnlockAndCheckDrop(ctx context.Context, ds **[]*dentry) {\n+func (fs *filesystem) renameMuRUnlockAndCheckCaching(ctx context.Context, ds **[]*dentry) {\nfs.renameMu.RUnlock()\nif *ds == nil {\nreturn\n}\n- if len(**ds) != 0 {\n- fs.renameMu.Lock()\nfor _, d := range **ds {\n- d.checkDropLocked(ctx)\n+ d.checkCachingLocked(ctx, false /* renameMuWriteLocked */)\n}\n- fs.renameMu.Unlock()\n- }\n- putDentrySlice(*ds)\n-}\n-\n-// +checklocksrelease:fs.renameMu\n-func (fs *filesystem) renameMuUnlockAndCheckDrop(ctx context.Context, ds **[]*dentry) {\n- if *ds == nil {\n- fs.renameMu.Unlock()\n- return\n- }\n- for _, d := range **ds {\n- d.checkDropLocked(ctx)\n- }\n- fs.renameMu.Unlock()\nputDentrySlice(*ds)\n}\n@@ -700,7 +683,7 @@ func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds\n}\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn err\n@@ -712,7 +695,7 @@ func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds\nfunc (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetDentryOptions) (*vfs.Dentry, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn nil, err\n@@ -733,7 +716,7 @@ func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, op\nfunc (fs *filesystem) GetParentDentryAt(ctx context.Context, rp *vfs.ResolvingPath) (*vfs.Dentry, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nstart := rp.Start().Impl().(*dentry)\nd, err := fs.walkParentDirLocked(ctx, rp, start, &ds)\nif err != nil {\n@@ -770,7 +753,7 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nstart := rp.Start().Impl().(*dentry)\nif rp.Done() {\n@@ -952,7 +935,7 @@ func (d *dentry) openLocked(ctx context.Context, rp *vfs.ResolvingPath, opts *vf\nfunc (fs *filesystem) ReadlinkAt(ctx context.Context, rp *vfs.ResolvingPath) (string, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn \"\", err\n@@ -982,7 +965,7 @@ func (fs *filesystem) SetStatAt(ctx context.Context, rp *vfs.ResolvingPath, opts\nfunc (fs *filesystem) StatAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.StatOptions) (linux.Statx, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn linux.Statx{}, err\n@@ -1028,7 +1011,7 @@ func (fs *filesystem) UnlinkAt(ctx context.Context, rp *vfs.ResolvingPath) error\nfunc (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.BoundEndpointOptions) (transport.BoundEndpoint, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nif _, err := fs.resolveLocked(ctx, rp, &ds); err != nil {\nreturn nil, err\n}\n@@ -1039,7 +1022,7 @@ func (fs *filesystem) BoundEndpointAt(ctx context.Context, rp *vfs.ResolvingPath\nfunc (fs *filesystem) ListXattrAt(ctx context.Context, rp *vfs.ResolvingPath, size uint64) ([]string, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn nil, err\n@@ -1055,7 +1038,7 @@ func (fs *filesystem) ListXattrAt(ctx context.Context, rp *vfs.ResolvingPath, si\nfunc (fs *filesystem) GetXattrAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetXattrOptions) (string, error) {\nvar ds *[]*dentry\nfs.renameMu.RLock()\n- defer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n+ defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)\nd, err := fs.resolveLocked(ctx, rp, &ds)\nif err != nil {\nreturn \"\", err\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/verity/verity.go",
"new_path": "pkg/sentry/fsimpl/verity/verity.go",
"diff": "// Lock order:\n//\n// filesystem.renameMu\n+// dentry.cachingMu\n+// filesystem.cacheMu\n// dentry.dirMu\n// fileDescription.mu\n// filesystem.verityMu\n@@ -96,6 +98,9 @@ const (\n// sizeOfStringInt32 is the size for a 32 bit integer stored as string in\n// extended attributes. The maximum value of a 32 bit integer has 10 digits.\nsizeOfStringInt32 = 10\n+\n+ // defaultMaxCachedDentries is the default limit of dentry cache.\n+ defaultMaxCachedDentries = uint64(1000)\n)\nvar (\n@@ -109,6 +114,7 @@ const (\nmoptLowerPath = \"lower_path\"\nmoptRootHash = \"root_hash\"\nmoptRootName = \"root_name\"\n+ moptDentryCacheLimit = \"dentry_cache_limit\"\n)\n// HashAlgorithm is a type specifying the algorithm used to hash the file\n@@ -188,6 +194,17 @@ type filesystem struct {\n// dentries.\nrenameMu sync.RWMutex `state:\"nosave\"`\n+ // cachedDentries contains all dentries with 0 references. (Due to race\n+ // conditions, it may also contain dentries with non-zero references.)\n+ // cachedDentriesLen is the number of dentries in cachedDentries. These\n+ // fields are protected by cacheMu.\n+ cacheMu sync.Mutex `state:\"nosave\"`\n+ cachedDentries dentryList\n+ cachedDentriesLen uint64\n+\n+ // maxCachedDentries is the maximum size of filesystem.cachedDentries.\n+ maxCachedDentries uint64\n+\n// verityMu synchronizes enabling verity files, protects files or\n// directories from being enabled by different threads simultaneously.\n// It also ensures that verity does not access files that are being\n@@ -198,6 +215,10 @@ type filesystem struct {\n// is for the whole file system to ensure that no more than one file is\n// enabled the same time.\nverityMu sync.RWMutex `state:\"nosave\"`\n+\n+ // released is nonzero once filesystem.Release has been called. It is accessed\n+ // with atomic memory operations.\n+ released int32\n}\n// InternalFilesystemOptions may be passed as\n@@ -266,6 +287,16 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\ndelete(mopts, moptRootName)\nrootName = root\n}\n+ maxCachedDentries := defaultMaxCachedDentries\n+ if str, ok := mopts[moptDentryCacheLimit]; ok {\n+ delete(mopts, moptDentryCacheLimit)\n+ maxCD, err := strconv.ParseUint(str, 10, 64)\n+ if err != nil {\n+ ctx.Warningf(\"verity.FilesystemType.GetFilesystem: invalid dentry cache limit: %s=%s\", moptDentryCacheLimit, str)\n+ return nil, nil, linuxerr.EINVAL\n+ }\n+ maxCachedDentries = maxCD\n+ }\n// Check for unparsed options.\nif len(mopts) != 0 {\n@@ -339,12 +370,16 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\naction: iopts.Action,\nopts: opts.Data,\nallowRuntimeEnable: iopts.AllowRuntimeEnable,\n+ maxCachedDentries: maxCachedDentries,\n}\nfs.vfsfs.Init(vfsObj, &fstype, fs)\n// Construct the root dentry.\nd := fs.newDentry()\n- d.refs = 1\n+ // Set the root's reference count to 2. One reference is returned to\n+ // the caller, and the other is held by fs to prevent the root from\n+ // being \"cached\" and subsequently evicted.\n+ d.refs = 2\nlowerVD := vfs.MakeVirtualDentry(lowerMount, lowerMount.Root())\nlowerVD.IncRef()\nd.lowerVD = lowerVD\n@@ -519,7 +554,16 @@ func (fstype FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.Virt\n// Release implements vfs.FilesystemImpl.Release.\nfunc (fs *filesystem) Release(ctx context.Context) {\n+ atomic.StoreInt32(&fs.released, 1)\nfs.lowerMount.DecRef(ctx)\n+\n+ fs.renameMu.Lock()\n+ fs.evictAllCachedDentriesLocked(ctx)\n+ fs.renameMu.Unlock()\n+\n+ // An extra reference was held by the filesystem on the root to prevent\n+ // it from being cached/evicted.\n+ fs.rootDentry.DecRef(ctx)\n}\n// MountOptions implements vfs.FilesystemImpl.MountOptions.\n@@ -533,6 +577,11 @@ func (fs *filesystem) MountOptions() string {\ntype dentry struct {\nvfsd vfs.Dentry\n+ // refs is the reference count. Each dentry holds a reference on its\n+ // parent, even if disowned. When refs reaches 0, the dentry may be\n+ // added to the cache or destroyed. If refs == -1, the dentry has\n+ // already been destroyed. refs is accessed using atomic memory\n+ // operations.\nrefs int64\n// fs is the owning filesystem. fs is immutable.\n@@ -587,13 +636,23 @@ type dentry struct {\n// is protected by hashMu.\nhashMu sync.RWMutex `state:\"nosave\"`\nhash []byte\n+\n+ // cachingMu is used to synchronize concurrent dentry caching attempts on\n+ // this dentry.\n+ cachingMu sync.Mutex `state:\"nosave\"`\n+\n+ // If cached is true, dentryEntry links dentry into\n+ // filesystem.cachedDentries. cached and dentryEntry are protected by\n+ // cachingMu.\n+ cached bool\n+ dentryEntry\n}\n// newDentry creates a new dentry representing the given verity file. The\n-// dentry initially has no references; it is the caller's responsibility to set\n-// the dentry's reference count and/or call dentry.destroy() as appropriate.\n-// The dentry is initially invalid in that it contains no underlying dentry;\n-// the caller is responsible for setting them.\n+// dentry initially has no references, but is not cached; it is the caller's\n+// responsibility to set the dentry's reference count and/or call\n+// dentry.destroy() as appropriate. The dentry is initially invalid in that it\n+// contains no underlying dentry; the caller is responsible for setting them.\nfunc (fs *filesystem) newDentry() *dentry {\nd := &dentry{\nfs: fs,\n@@ -629,42 +688,23 @@ func (d *dentry) TryIncRef() bool {\n// DecRef implements vfs.DentryImpl.DecRef.\nfunc (d *dentry) DecRef(ctx context.Context) {\n- r := atomic.AddInt64(&d.refs, -1)\n- if d.LogRefs() {\n- refsvfs2.LogDecRef(d, r)\n- }\n- if r == 0 {\n- d.fs.renameMu.Lock()\n- d.checkDropLocked(ctx)\n- d.fs.renameMu.Unlock()\n- } else if r < 0 {\n- panic(\"verity.dentry.DecRef() called without holding a reference\")\n+ if d.decRefNoCaching() == 0 {\n+ d.checkCachingLocked(ctx, false /* renameMuWriteLocked */)\n}\n}\n-func (d *dentry) decRefLocked(ctx context.Context) {\n+// decRefNoCaching decrements d's reference count without calling\n+// d.checkCachingLocked, even if d's reference count reaches 0; callers are\n+// responsible for ensuring that d.checkCachingLocked will be called later.\n+func (d *dentry) decRefNoCaching() int64 {\nr := atomic.AddInt64(&d.refs, -1)\nif d.LogRefs() {\nrefsvfs2.LogDecRef(d, r)\n}\n- if r == 0 {\n- d.checkDropLocked(ctx)\n- } else if r < 0 {\n- panic(\"verity.dentry.decRefLocked() called without holding a reference\")\n- }\n-}\n-\n-// checkDropLocked should be called after d's reference count becomes 0 or it\n-// becomes deleted.\n-func (d *dentry) checkDropLocked(ctx context.Context) {\n- // Dentries with a positive reference count must be retained. Dentries\n- // with a negative reference count have already been destroyed.\n- if atomic.LoadInt64(&d.refs) != 0 {\n- return\n+ if r < 0 {\n+ panic(\"verity.dentry.decRefNoCaching() called without holding a reference\")\n}\n- // Refs is still zero; destroy it.\n- d.destroyLocked(ctx)\n- return\n+ return r\n}\n// destroyLocked destroys the dentry.\n@@ -683,6 +723,12 @@ func (d *dentry) destroyLocked(ctx context.Context) {\npanic(\"verity.dentry.destroyLocked() called with references on the dentry\")\n}\n+ // Drop the reference held by d on its parent without recursively\n+ // locking d.fs.renameMu.\n+ if d.parent != nil && d.parent.decRefNoCaching() == 0 {\n+ d.parent.checkCachingLocked(ctx, true /* renameMuWriteLocked */)\n+ }\n+\nif d.lowerVD.Ok() {\nd.lowerVD.DecRef(ctx)\n}\n@@ -695,7 +741,6 @@ func (d *dentry) destroyLocked(ctx context.Context) {\ndelete(d.parent.children, d.name)\n}\nd.parent.dirMu.Unlock()\n- d.parent.decRefLocked(ctx)\n}\nrefsvfs2.Unregister(d)\n}\n@@ -734,6 +779,140 @@ func (d *dentry) OnZeroWatches(context.Context) {\n//TODO(b/159261227): Implement OnZeroWatches.\n}\n+// checkCachingLocked should be called after d's reference count becomes 0 or\n+// it becomes disowned.\n+//\n+// For performance, checkCachingLocked can also be called after d's reference\n+// count becomes non-zero, so that d can be removed from the LRU cache. This\n+// may help in reducing the size of the cache and hence reduce evictions. Note\n+// that this is not necessary for correctness.\n+//\n+// It may be called on a destroyed dentry. For example,\n+// renameMu[R]UnlockAndCheckCaching may call checkCachingLocked multiple times\n+// for the same dentry when the dentry is visited more than once in the same\n+// operation. One of the calls may destroy the dentry, so subsequent calls will\n+// do nothing.\n+//\n+// Preconditions: d.fs.renameMu must be locked for writing if\n+// renameMuWriteLocked is true; it may be temporarily unlocked.\n+func (d *dentry) checkCachingLocked(ctx context.Context, renameMuWriteLocked bool) {\n+ d.cachingMu.Lock()\n+ refs := atomic.LoadInt64(&d.refs)\n+ if refs == -1 {\n+ // Dentry has already been destroyed.\n+ d.cachingMu.Unlock()\n+ return\n+ }\n+ if refs > 0 {\n+ // fs.cachedDentries is permitted to contain dentries with non-zero refs,\n+ // which are skipped by fs.evictCachedDentryLocked() upon reaching the end\n+ // of the LRU. But it is still beneficial to remove d from the cache as we\n+ // are already holding d.cachingMu. Keeping a cleaner cache also reduces\n+ // the number of evictions (which is expensive as it acquires fs.renameMu).\n+ d.removeFromCacheLocked()\n+ d.cachingMu.Unlock()\n+ return\n+ }\n+\n+ if atomic.LoadInt32(&d.fs.released) != 0 {\n+ d.cachingMu.Unlock()\n+ if !renameMuWriteLocked {\n+ // Need to lock d.fs.renameMu to access d.parent. Lock it for writing as\n+ // needed by d.destroyLocked() later.\n+ d.fs.renameMu.Lock()\n+ defer d.fs.renameMu.Unlock()\n+ }\n+ if d.parent != nil {\n+ d.parent.dirMu.Lock()\n+ delete(d.parent.children, d.name)\n+ d.parent.dirMu.Unlock()\n+ }\n+ d.destroyLocked(ctx) // +checklocksforce: see above.\n+ return\n+ }\n+\n+ d.fs.cacheMu.Lock()\n+ // If d is already cached, just move it to the front of the LRU.\n+ if d.cached {\n+ d.fs.cachedDentries.Remove(d)\n+ d.fs.cachedDentries.PushFront(d)\n+ d.fs.cacheMu.Unlock()\n+ d.cachingMu.Unlock()\n+ return\n+ }\n+ // Cache the dentry, then evict the least recently used cached dentry if\n+ // the cache becomes over-full.\n+ d.fs.cachedDentries.PushFront(d)\n+ d.fs.cachedDentriesLen++\n+ d.cached = true\n+ shouldEvict := d.fs.cachedDentriesLen > d.fs.maxCachedDentries\n+ d.fs.cacheMu.Unlock()\n+ d.cachingMu.Unlock()\n+\n+ if shouldEvict {\n+ if !renameMuWriteLocked {\n+ // Need to lock d.fs.renameMu for writing as needed by\n+ // d.evictCachedDentryLocked().\n+ d.fs.renameMu.Lock()\n+ defer d.fs.renameMu.Unlock()\n+ }\n+ d.fs.evictCachedDentryLocked(ctx) // +checklocksforce: see above.\n+ }\n+}\n+\n+// Preconditions: d.cachingMu must be locked.\n+func (d *dentry) removeFromCacheLocked() {\n+ if d.cached {\n+ d.fs.cacheMu.Lock()\n+ d.fs.cachedDentries.Remove(d)\n+ d.fs.cachedDentriesLen--\n+ d.fs.cacheMu.Unlock()\n+ d.cached = false\n+ }\n+}\n+\n+// Precondition: fs.renameMu must be locked for writing; it may be temporarily\n+// unlocked.\n+// +checklocks:fs.renameMu\n+func (fs *filesystem) evictAllCachedDentriesLocked(ctx context.Context) {\n+ for fs.cachedDentriesLen != 0 {\n+ fs.evictCachedDentryLocked(ctx)\n+ }\n+}\n+\n+// Preconditions:\n+// * fs.renameMu must be locked for writing; it may be temporarily unlocked.\n+// +checklocks:fs.renameMu\n+func (fs *filesystem) evictCachedDentryLocked(ctx context.Context) {\n+ fs.cacheMu.Lock()\n+ victim := fs.cachedDentries.Back()\n+ fs.cacheMu.Unlock()\n+ if victim == nil {\n+ // fs.cachedDentries may have become empty between when it was\n+ // checked and when we locked fs.cacheMu.\n+ return\n+ }\n+\n+ victim.cachingMu.Lock()\n+ victim.removeFromCacheLocked()\n+ // victim.refs may have become non-zero from an earlier path resolution\n+ // since it was inserted into fs.cachedDentries.\n+ if atomic.LoadInt64(&victim.refs) != 0 {\n+ victim.cachingMu.Unlock()\n+ return\n+ }\n+ if victim.parent != nil {\n+ victim.parent.dirMu.Lock()\n+ // Note that victim can't be a mount point (in any mount\n+ // namespace), since VFS holds references on mount points.\n+ fs.vfsfs.VirtualFilesystem().InvalidateDentry(ctx, &victim.vfsd)\n+ delete(victim.parent.children, victim.name)\n+ victim.parent.dirMu.Unlock()\n+ }\n+ victim.cachingMu.Unlock()\n+ victim.destroyLocked(ctx) // +checklocksforce: owned as precondition, victim.fs == fs.\n+}\n+\nfunc (d *dentry) isSymlink() bool {\nreturn atomic.LoadUint32(&d.mode)&linux.S_IFMT == linux.S_IFLNK\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache verity dentries
Add an LRU cache to cache verity dentries when ref count drop to 0. This
way we don't need to hash and verify the previous opened files or
directories each time.
PiperOrigin-RevId: 391880157 |
259,885 | 20.08.2021 15:11:49 | 25,200 | 154ccbae312f5754b3497e6a296da756952d620c | Remove experimental warning in the VFS2 README. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/README.md",
"new_path": "pkg/sentry/vfs/README.md",
"diff": "# The gVisor Virtual Filesystem\n-THIS PACKAGE IS CURRENTLY EXPERIMENTAL AND NOT READY OR ENABLED FOR PRODUCTION\n-USE. For the filesystem implementation currently used by gVisor, see the `fs`\n-package.\n-\n## Implementation Notes\n### Reference Counting\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove experimental warning in the VFS2 README.
PiperOrigin-RevId: 392078690 |
259,885 | 20.08.2021 17:47:30 | 25,200 | 0a15a216daab9523a5f0c7b93bbceae98dbcbcc1 | Allow gofer.specialFileFDs to be mmapped with a host FD. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"new_path": "pkg/sentry/fsimpl/gofer/save_restore.go",
"diff": "@@ -158,6 +158,10 @@ func (d *dentryPlatformFile) afterLoad() {\n// afterLoad is invoked by stateify.\nfunc (fd *specialFileFD) afterLoad() {\nfd.handle.fd = -1\n+ if fd.hostFileMapper.IsInited() {\n+ // Ensure that we don't call fd.hostFileMapper.Init() again.\n+ fd.hostFileMapperInitOnce.Do(func() {})\n+ }\n}\n// CompleteRestore implements\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/special_file.go",
"new_path": "pkg/sentry/fsimpl/gofer/special_file.go",
"diff": "@@ -22,9 +22,13 @@ import (\n\"gvisor.dev/gvisor/pkg/context\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n\"gvisor.dev/gvisor/pkg/fdnotifier\"\n+ \"gvisor.dev/gvisor/pkg/hostarch\"\n\"gvisor.dev/gvisor/pkg/metric\"\n\"gvisor.dev/gvisor/pkg/p9\"\n+ \"gvisor.dev/gvisor/pkg/safemem\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/fsutil\"\n\"gvisor.dev/gvisor/pkg/sentry/fsmetric\"\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/usermem\"\n@@ -74,6 +78,16 @@ type specialFileFD struct {\nbufMu sync.Mutex `state:\"nosave\"`\nhaveBuf uint32\nbuf []byte\n+\n+ // If handle.fd >= 0, hostFileMapper caches mappings of handle.fd, and\n+ // hostFileMapperInitOnce is used to initialize it on first use.\n+ hostFileMapperInitOnce sync.Once `state:\"nosave\"`\n+ hostFileMapper fsutil.HostFileMapper\n+\n+ // If handle.fd >= 0, fileRefs counts references on memmap.File offsets.\n+ // fileRefs is protected by fileRefsMu.\n+ fileRefsMu sync.Mutex `state:\"nosave\"`\n+ fileRefs fsutil.FrameRefSet\n}\nfunc newSpecialFileFD(h handle, mnt *vfs.Mount, d *dentry, flags uint32) (*specialFileFD, error) {\n@@ -392,3 +406,85 @@ func (fd *specialFileFD) sync(ctx context.Context, forFilesystemSync bool) error\n}\nreturn nil\n}\n+\n+// ConfigureMMap implements vfs.FileDescriptionImpl.ConfigureMMap.\n+func (fd *specialFileFD) ConfigureMMap(ctx context.Context, opts *memmap.MMapOpts) error {\n+ if fd.handle.fd < 0 || fd.filesystem().opts.forcePageCache {\n+ return linuxerr.ENODEV\n+ }\n+ // After this point, fd may be used as a memmap.Mappable and memmap.File.\n+ fd.hostFileMapperInitOnce.Do(fd.hostFileMapper.Init)\n+ return vfs.GenericConfigureMMap(&fd.vfsfd, fd, opts)\n+}\n+\n+// AddMapping implements memmap.Mappable.AddMapping.\n+func (fd *specialFileFD) AddMapping(ctx context.Context, ms memmap.MappingSpace, ar hostarch.AddrRange, offset uint64, writable bool) error {\n+ fd.hostFileMapper.IncRefOn(memmap.MappableRange{offset, offset + uint64(ar.Length())})\n+ return nil\n+}\n+\n+// RemoveMapping implements memmap.Mappable.RemoveMapping.\n+func (fd *specialFileFD) RemoveMapping(ctx context.Context, ms memmap.MappingSpace, ar hostarch.AddrRange, offset uint64, writable bool) {\n+ fd.hostFileMapper.DecRefOn(memmap.MappableRange{offset, offset + uint64(ar.Length())})\n+}\n+\n+// CopyMapping implements memmap.Mappable.CopyMapping.\n+func (fd *specialFileFD) CopyMapping(ctx context.Context, ms memmap.MappingSpace, srcAR, dstAR hostarch.AddrRange, offset uint64, writable bool) error {\n+ return fd.AddMapping(ctx, ms, dstAR, offset, writable)\n+}\n+\n+// Translate implements memmap.Mappable.Translate.\n+func (fd *specialFileFD) Translate(ctx context.Context, required, optional memmap.MappableRange, at hostarch.AccessType) ([]memmap.Translation, error) {\n+ mr := optional\n+ if fd.filesystem().opts.limitHostFDTranslation {\n+ mr = maxFillRange(required, optional)\n+ }\n+ return []memmap.Translation{\n+ {\n+ Source: mr,\n+ File: fd,\n+ Offset: mr.Start,\n+ Perms: hostarch.AnyAccess,\n+ },\n+ }, nil\n+}\n+\n+// InvalidateUnsavable implements memmap.Mappable.InvalidateUnsavable.\n+func (fd *specialFileFD) InvalidateUnsavable(ctx context.Context) error {\n+ return nil\n+}\n+\n+// IncRef implements memmap.File.IncRef.\n+func (fd *specialFileFD) IncRef(fr memmap.FileRange) {\n+ fd.fileRefsMu.Lock()\n+ defer fd.fileRefsMu.Unlock()\n+ fd.fileRefs.IncRefAndAccount(fr)\n+}\n+\n+// DecRef implements memmap.File.DecRef.\n+func (fd *specialFileFD) DecRef(fr memmap.FileRange) {\n+ fd.fileRefsMu.Lock()\n+ defer fd.fileRefsMu.Unlock()\n+ fd.fileRefs.DecRefAndAccount(fr)\n+}\n+\n+// MapInternal implements memmap.File.MapInternal.\n+func (fd *specialFileFD) MapInternal(fr memmap.FileRange, at hostarch.AccessType) (safemem.BlockSeq, error) {\n+ fd.requireHostFD()\n+ return fd.hostFileMapper.MapInternal(fr, int(fd.handle.fd), at.Write)\n+}\n+\n+// FD implements memmap.File.FD.\n+func (fd *specialFileFD) FD() int {\n+ fd.requireHostFD()\n+ return int(fd.handle.fd)\n+}\n+\n+func (fd *specialFileFD) requireHostFD() {\n+ if fd.handle.fd < 0 {\n+ // This is possible if fd was successfully mmapped before saving, then\n+ // was restored without a host FD. This is unrecoverable: without a\n+ // host FD, we can't mmap this file post-restore.\n+ panic(\"gofer.specialFileFD can no longer be memory-mapped without a host FD\")\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow gofer.specialFileFDs to be mmapped with a host FD.
PiperOrigin-RevId: 392102898 |
259,858 | 23.08.2021 10:50:37 | 25,200 | 8dc3be7a61c9d8199c66260cd2d416c8e3e0bc96 | Use --output=starlark trick for all build path parsing.
There is no reason to limit this to debian paths. | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -444,7 +444,7 @@ $(RELEASE_ARTIFACTS)/%:\n@mkdir -p $@\n@$(call copy,//runsc:runsc,$@)\n@$(call copy,//shim:containerd-shim-runsc-v1,$@)\n- @$(call deb_copy,//debian:debian,$@)\n+ @$(call copy,//debian:debian,$@)\nrelease: $(RELEASE_KEY) $(RELEASE_ARTIFACTS)/$(ARCH)\n@mkdir -p $(RELEASE_ROOT)\n"
},
{
"change_type": "DELETE",
"old_path": "debian/show_paths.bzl",
"new_path": null,
"diff": "-\"\"\"Formatter to extract the output files from pkg_deb.\"\"\"\n-\n-def format(target):\n- provider_map = providers(target)\n- return \"\\n\".join([\n- provider_map[\"OutputGroupInfo\"].out.to_list()[0].path,\n- provider_map[\"OutputGroupInfo\"].deb.to_list()[0].path,\n- provider_map[\"OutputGroupInfo\"].changes.to_list()[0].path,\n- ])\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -181,35 +181,17 @@ endif\n# build_paths extracts the built binary from the bazel stderr output.\n#\n-# This could be alternately done by parsing the bazel build event stream, but\n-# this is a complex schema, and begs the question: what will build the thing\n-# that parses the output? Bazel? Do we need a separate bootstrapping build\n-# command here? Yikes, let's just stick with the ugly shell pipeline.\n-#\n# The last line is used to prevent terminal shenanigans.\nbuild_paths = \\\n- (set -euo pipefail; \\\n- $(call wrapper,$(BAZEL) build $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1)) 2>&1 \\\n- | tee /dev/fd/2 \\\n- | sed -n -e '/^Target/,$$p' \\\n- | sed -n -e '/^ \\($(subst /,\\/,$(subst $(SPACE),\\|,$(BUILD_ROOTS)))\\)/p' \\\n- | sed -e 's/ /\\n/g' \\\n- | awk '{$$1=$$1};1' \\\n- | strings \\\n- | xargs -r -n 1 -I {} readlink -f \"{}\" \\\n- | xargs -r -n 1 -I {} bash -c 'set -xeuo pipefail; $(2)')\n-\n-debian_paths = \\\n(set -euo pipefail; \\\n$(call wrapper,$(BAZEL) build $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1)) && \\\n- $(call wrapper,$(BAZEL) cquery $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1) --output=starlark --starlark:file=debian/show_paths.bzl) \\\n+ $(call wrapper,$(BAZEL) cquery $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1) --output=starlark --starlark:file=tools/show_paths.bzl) \\\n| xargs -r -n 1 -I {} readlink -f \"{}\" \\\n| xargs -r -n 1 -I {} bash -c 'set -xeuo pipefail; $(2)')\nclean = $(call header,CLEAN) && $(call wrapper,$(BAZEL) clean)\nbuild = $(call header,BUILD $(1)) && $(call build_paths,$(1),echo {})\ncopy = $(call header,COPY $(1) $(2)) && $(call build_paths,$(1),cp -fa {} $(2))\n-deb_copy = $(call header,COPY $(1) $(2)) && $(call debian_paths,$(1),cp -fa {} $(2))\nrun = $(call header,RUN $(1) $(2)) && $(call build_paths,$(1),{} $(2))\nsudo = $(call header,SUDO $(1) $(2)) && $(call build_paths,$(1),sudo -E {} $(2))\ntest = $(call header,TEST $(1)) && $(call wrapper,$(BAZEL) test $(TEST_OPTIONS) $(1))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/show_paths.bzl",
"diff": "+\"\"\"Formatter to extract the output files from a target.\"\"\"\n+\n+def format(target):\n+ provider_map = providers(target)\n+ outputs = dict()\n+\n+ # Try to resolve in order.\n+ files_to_run = provider_map.get(\"FilesToRunProvider\", None)\n+ default_info = provider_map.get(\"DefaultInfo\", None)\n+ output_group_info = provider_map.get(\"OutputGroupInfo\", None)\n+ if files_to_run and files_to_run.executable:\n+ outputs[files_to_run.executable.path] = True\n+ elif default_info:\n+ for x in default_info.files:\n+ outputs[x.path] = True\n+ elif output_group_info:\n+ for entry in dir(output_group_info):\n+ # Filter out all built-ins and anything that is not a depset.\n+ if entry.startswith(\"_\") or not hasattr(getattr(output_group_info, entry), \"to_list\"):\n+ continue\n+ for x in getattr(output_group_info, entry).to_list():\n+ outputs[x.path] = True\n+\n+ # Return all found files.\n+ return \"\\n\".join(outputs.keys())\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use --output=starlark trick for all build path parsing.
There is no reason to limit this to debian paths.
PiperOrigin-RevId: 392469415 |
259,992 | 24.08.2021 15:23:14 | 25,200 | 19051dd26fe4840cdeb599f6fb393bf72851b4ee | Fix uninitialized messages in MsgqueueTest | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/msgqueue.cc",
"new_path": "test/syscalls/linux/msgqueue.cc",
"diff": "@@ -731,8 +731,9 @@ TEST(MsgqueueTest, MsgCtlIpcStat) {\nabsl::SleepFor(absl::Seconds(1));\nauto pre_send = absl::Now();\n- msgbuf buf;\n- ASSERT_THAT(msgsnd(queue.get(), &buf, msgSize, 0), SyscallSucceeds());\n+ msgbuf buf{1, \"A message.\"};\n+ ASSERT_THAT(msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0),\n+ SyscallSucceeds());\nASSERT_THAT(msgctl(queue.get(), IPC_STAT, &ds), SyscallSucceeds());\n@@ -749,7 +750,7 @@ TEST(MsgqueueTest, MsgCtlIpcStat) {\nabsl::SleepFor(absl::Seconds(1));\nauto pre_receive = absl::Now();\n- ASSERT_THAT(msgrcv(queue.get(), &buf, msgSize, 0, 0),\n+ ASSERT_THAT(msgrcv(queue.get(), &buf, sizeof(buf.mtext), 0, 0),\nSyscallSucceedsWithValue(msgSize));\nASSERT_THAT(msgctl(queue.get(), IPC_STAT, &ds), SyscallSucceeds());\n@@ -850,8 +851,9 @@ TEST(MsgqueueTest, MsgCtlMsgInfo) {\nQueue queue(msgget(IPC_PRIVATE, 0600));\nASSERT_THAT(queue.get(), SyscallSucceeds());\n- msgbuf buf;\n- ASSERT_THAT(msgsnd(queue.get(), &buf, msgSize, 0), SyscallSucceeds());\n+ msgbuf buf{1, \"A message.\"};\n+ ASSERT_THAT(msgsnd(queue.get(), &buf, sizeof(buf.mtext), 0),\n+ SyscallSucceeds());\nASSERT_THAT(msgctl(0, MSG_INFO, reinterpret_cast<struct msqid_ds*>(&info)),\nSyscallSucceeds());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix uninitialized messages in MsgqueueTest
PiperOrigin-RevId: 392760305 |
260,001 | 25.08.2021 14:35:03 | 25,200 | c1d656c8e447da8b499dbe4ecf85bd7b96a2685e | Remove quotedev device | [
{
"change_type": "DELETE",
"old_path": "pkg/sentry/devices/quotedev/BUILD",
"new_path": null,
"diff": "-load(\"//tools:defs.bzl\", \"go_library\")\n-\n-licenses([\"notice\"])\n-\n-go_library(\n- name = \"quotedev\",\n- srcs = [\"quotedev.go\"],\n- visibility = [\"//pkg/sentry:internal\"],\n- deps = [\n- \"//pkg/abi/linux\",\n- \"//pkg/context\",\n- \"//pkg/errors/linuxerr\",\n- \"//pkg/sentry/fsimpl/devtmpfs\",\n- \"//pkg/sentry/vfs\",\n- ],\n-)\n"
},
{
"change_type": "DELETE",
"old_path": "pkg/sentry/devices/quotedev/quotedev.go",
"new_path": null,
"diff": "-// Copyright 2021 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-// Package quotedev implements a vfs.Device for /dev/gvisor_quote.\n-package quotedev\n-\n-import (\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/context\"\n- \"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n- \"gvisor.dev/gvisor/pkg/sentry/fsimpl/devtmpfs\"\n- \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n-)\n-\n-const (\n- quoteDevMinor = 0\n-)\n-\n-// quoteDevice implements vfs.Device for /dev/gvisor_quote\n-//\n-// +stateify savable\n-type quoteDevice struct{}\n-\n-// Open implements vfs.Device.Open.\n-// TODO(b/157161182): Add support for attestation ioctls.\n-func (quoteDevice) Open(ctx context.Context, mnt *vfs.Mount, vfsd *vfs.Dentry, opts vfs.OpenOptions) (*vfs.FileDescription, error) {\n- return nil, linuxerr.EIO\n-}\n-\n-// Register registers all devices implemented by this package in vfsObj.\n-func Register(vfsObj *vfs.VirtualFilesystem) error {\n- return vfsObj.RegisterDevice(vfs.CharDevice, linux.UNNAMED_MAJOR, quoteDevMinor, quoteDevice{}, &vfs.RegisterDeviceOptions{\n- GroupName: \"gvisor_quote\",\n- })\n-}\n-\n-// CreateDevtmpfsFiles creates device special files in dev representing all\n-// devices implemented by this package.\n-func CreateDevtmpfsFiles(ctx context.Context, dev *devtmpfs.Accessor) error {\n- return dev.CreateDeviceFile(ctx, \"gvisor_quote\", vfs.CharDevice, linux.UNNAMED_MAJOR, quoteDevMinor, 0666 /* mode */)\n-}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove quotedev device
PiperOrigin-RevId: 392982220 |
259,898 | 25.08.2021 16:32:16 | 25,200 | 4c7aaa941eaa05eea99b1b1e7f8e33b42c2bd6a8 | Improve TestTimestampSynCookies
.. by advancing the clock so that NowMonotonic does not return 0. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -8221,6 +8221,11 @@ func TestSendBufferTuning(t *testing.T) {\nfunc TestTimestampSynCookies(t *testing.T) {\nclock := faketime.NewManualClock()\n+ tsNow := func() uint32 {\n+ return uint32(clock.NowMonotonic().Sub(tcpip.MonotonicTime{}).Milliseconds())\n+ }\n+ // Advance the clock so that NowMonotonic is non-zero.\n+ clock.Advance(time.Second)\nc := context.NewWithOpts(t, context.Options{\nEnableV4: true,\nEnableV6: true,\n@@ -8261,6 +8266,8 @@ func TestTimestampSynCookies(t *testing.T) {\ntcpHdr := header.TCP(header.IPv4(b).Payload())\nc.IRS = seqnum.Value(tcpHdr.SequenceNumber())\ninitialTSVal := tcpHdr.ParsedOptions().TSVal\n+ // derive the tsOffset.\n+ tsOffset := initialTSVal - tsNow()\nheader.EncodeTSOption(420, initialTSVal, tcpOpts[2:])\nc.SendPacket(nil, &context.Headers{\n@@ -8293,8 +8300,8 @@ func TestTimestampSynCookies(t *testing.T) {\nt.Fatalf(\"failed to accept: %s\", err)\n}\n- const elapsed = 200 * time.Millisecond\n- clock.Advance(elapsed)\n+ // Advance the clock again so that we expect the next TSVal to change.\n+ clock.Advance(time.Second)\ndata := []byte{1, 2, 3}\nvar r bytes.Reader\nr.Reset(data)\n@@ -8304,7 +8311,7 @@ func TestTimestampSynCookies(t *testing.T) {\n// The endpoint should have a correct TSOffset so that the received TSVal\n// should match our expectation.\n- if got, want := header.TCP(header.IPv4(c.GetPacket()).Payload()).ParsedOptions().TSVal, initialTSVal+uint32(elapsed.Milliseconds()); got != want {\n+ if got, want := header.TCP(header.IPv4(c.GetPacket()).Payload()).ParsedOptions().TSVal, tsNow()+tsOffset; got != want {\nt.Fatalf(\"got TSVal = %d, want %d\", got, want)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Improve TestTimestampSynCookies
.. by advancing the clock so that NowMonotonic does not return 0.
PiperOrigin-RevId: 393005373 |
259,880 | 26.08.2021 17:00:10 | -7,200 | 73ba5943cfdc49ac2cb4638e00b14223ec7ee2b4 | fix tests in pty.cc
fixed and enabled SetForegroundProcessGroup and SetForegroundProcessGroupEmptyProcessGroup. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1594,9 +1594,9 @@ TEST_F(JobControlTest, GetForegroundProcessGroupNonControlling) {\n// - creates a child process in a new process group\n// - sets that child as the foreground process group\n// - kills its child and sets itself as the foreground process group.\n-// TODO(gvisor.dev/issue/5357): Fix and enable.\n-TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroup) {\n+TEST_F(JobControlTest, SetForegroundProcessGroup) {\nauto res = RunInChild([=]() {\n+ TEST_PCHECK(setsid() >= 0);\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n// Ignore SIGTTOU so that we don't stop ourself when calling tcsetpgrp.\n@@ -1634,7 +1634,7 @@ TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroup) {\n// Set ourself as the foreground process.\npid_t pgid;\n- TEST_PCHECK(pgid = getpgid(0) == 0);\n+ TEST_PCHECK((pgid = getpgid(0)) >= 0);\nTEST_PCHECK(!tcsetpgrp(replica_.get(), pgid));\n});\nASSERT_NO_ERRNO(res);\n@@ -1735,9 +1735,9 @@ TEST_F(JobControlTest, SetForegroundProcessGroupNegPgid) {\nASSERT_NO_ERRNO(ret);\n}\n-// TODO(gvisor.dev/issue/5357): Fix and enable.\n-TEST_F(JobControlTest, DISABLED_SetForegroundProcessGroupEmptyProcessGroup) {\n+TEST_F(JobControlTest, SetForegroundProcessGroupEmptyProcessGroup) {\nauto res = RunInChild([=]() {\n+ TEST_PCHECK(setsid() >= 0);\nTEST_PCHECK(!ioctl(replica_.get(), TIOCSCTTY, 0));\n// Create a new process, put it in a new process group, make that group the\n"
}
] | Go | Apache License 2.0 | google/gvisor | fix tests in pty.cc
fixed and enabled SetForegroundProcessGroup and SetForegroundProcessGroupEmptyProcessGroup. |
259,898 | 26.08.2021 17:42:15 | 25,200 | 1076702371fa02a36b70a6abf10dbec886742208 | Add Stack.Seed() back
... because it is still used by fuchsia. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -1823,6 +1823,13 @@ func (s *Stack) SetNUDConfigurations(id tcpip.NICID, proto tcpip.NetworkProtocol\nreturn nic.setNUDConfigs(proto, c)\n}\n+// Seed returns a 32 bit value that can be used as a seed value.\n+//\n+// NOTE: The seed is generated once during stack initialization only.\n+func (s *Stack) Seed() uint32 {\n+ return s.seed\n+}\n+\n// Rand returns a reference to a pseudo random generator that can be used\n// to generate random numbers as required.\nfunc (s *Stack) Rand() *rand.Rand {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Stack.Seed() back
... because it is still used by fuchsia.
PiperOrigin-RevId: 393246904 |
260,004 | 27.08.2021 11:12:08 | 25,200 | fbf020d6a0258275a68573032bea225a1f5396ab | Add LinkEndpoint.WriteRawPacket with stubs
...returning unsupported errors. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/channel/channel.go",
"new_path": "pkg/tcpip/link/channel/channel.go",
"diff": "@@ -290,3 +290,6 @@ func (*Endpoint) ARPHardwareType() header.ARPHardwareType {\n// AddHeader implements stack.LinkEndpoint.AddHeader.\nfunc (*Endpoint) AddHeader(tcpip.LinkAddress, tcpip.LinkAddress, tcpip.NetworkProtocolNumber, *stack.PacketBuffer) {\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*Endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/ethernet/ethernet.go",
"new_path": "pkg/tcpip/link/ethernet/ethernet.go",
"diff": "@@ -112,3 +112,8 @@ func (*Endpoint) AddHeader(local, remote tcpip.LinkAddress, proto tcpip.NetworkP\n}\neth.Encode(&fields)\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (e *Endpoint) WriteRawPacket(pkt *stack.PacketBuffer) tcpip.Error {\n+ return e.Endpoint.WriteRawPacket(pkt)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -505,6 +505,9 @@ func (e *endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.Net\n}\n}\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n+\n// WritePacket writes outbound packets to the file descriptor. If it is not\n// currently writable, the packet is dropped.\nfunc (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/loopback/loopback.go",
"new_path": "pkg/tcpip/link/loopback/loopback.go",
"diff": "@@ -103,3 +103,6 @@ func (*endpoint) ARPHardwareType() header.ARPHardwareType {\nfunc (e *endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/muxed/injectable.go",
"new_path": "pkg/tcpip/link/muxed/injectable.go",
"diff": "@@ -131,6 +131,11 @@ func (*InjectableEndpoint) ARPHardwareType() header.ARPHardwareType {\nfunc (*InjectableEndpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\n}\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*InjectableEndpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n// NewInjectableEndpoint creates a new multi-endpoint injectable endpoint.\nfunc NewInjectableEndpoint(routes map[tcpip.Address]stack.InjectableLinkEndpoint) *InjectableEndpoint {\nreturn &InjectableEndpoint{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/nested/nested.go",
"new_path": "pkg/tcpip/link/nested/nested.go",
"diff": "@@ -152,3 +152,8 @@ func (e *Endpoint) ARPHardwareType() header.ARPHardwareType {\nfunc (e *Endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\ne.child.AddHeader(local, remote, protocol, pkt)\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (e *Endpoint) WriteRawPacket(pkt *stack.PacketBuffer) tcpip.Error {\n+ return e.child.WriteRawPacket(pkt)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/pipe/pipe.go",
"new_path": "pkg/tcpip/link/pipe/pipe.go",
"diff": "@@ -121,3 +121,6 @@ func (*Endpoint) ARPHardwareType() header.ARPHardwareType {\n// AddHeader implements stack.LinkEndpoint.\nfunc (*Endpoint) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*Endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go",
"new_path": "pkg/tcpip/link/qdisc/fifo/endpoint.go",
"diff": "@@ -228,3 +228,8 @@ func (e *endpoint) ARPHardwareType() header.ARPHardwareType {\nfunc (e *endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\ne.lower.AddHeader(local, remote, protocol, pkt)\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (e *endpoint) WriteRawPacket(pkt *stack.PacketBuffer) tcpip.Error {\n+ return e.lower.WriteRawPacket(pkt)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"diff": "@@ -202,6 +202,9 @@ func (e *endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.Net\neth.Encode(ethHdr)\n}\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n+\n// WritePacket writes outbound packets to the file descriptor. If it is not\n// currently writable, the packet is dropped.\nfunc (e *endpoint) WritePacket(r stack.RouteInfo, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) tcpip.Error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/waitable/waitable.go",
"new_path": "pkg/tcpip/link/waitable/waitable.go",
"diff": "@@ -155,3 +155,6 @@ func (e *Endpoint) ARPHardwareType() header.ARPHardwareType {\nfunc (e *Endpoint) AddHeader(local, remote tcpip.LinkAddress, protocol tcpip.NetworkProtocolNumber, pkt *stack.PacketBuffer) {\ne.lower.AddHeader(local, remote, protocol, pkt)\n}\n+\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*Endpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error { return &tcpip.ErrNotSupported{} }\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/waitable/waitable_test.go",
"new_path": "pkg/tcpip/link/waitable/waitable_test.go",
"diff": "@@ -80,6 +80,11 @@ func (e *countedEndpoint) WritePackets(_ stack.RouteInfo, pkts stack.PacketBuffe\nreturn pkts.Len(), nil\n}\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*countedEndpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n// ARPHardwareType implements stack.LinkEndpoint.ARPHardwareType.\nfunc (*countedEndpoint) ARPHardwareType() header.ARPHardwareType {\npanic(\"unimplemented\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/internal/testutil/testutil.go",
"new_path": "pkg/tcpip/network/internal/testutil/testutil.go",
"diff": "@@ -101,6 +101,11 @@ func (*MockLinkEndpoint) ARPHardwareType() header.ARPHardwareType { return heade\nfunc (*MockLinkEndpoint) AddHeader(_, _ tcpip.LinkAddress, _ tcpip.NetworkProtocolNumber, _ *stack.PacketBuffer) {\n}\n+// WriteRawPacket implements stack.LinkEndpoint.\n+func (*MockLinkEndpoint) WriteRawPacket(*stack.PacketBuffer) tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n// MakeRandPkt generates a randomized packet. transportHeaderLength indicates\n// how many random bytes will be copied in the Transport Header.\n// extraHeaderReserveLength indicates how much extra space will be reserved for\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/forwarding_test.go",
"new_path": "pkg/tcpip/stack/forwarding_test.go",
"diff": "@@ -342,6 +342,10 @@ func (e *fwdTestLinkEndpoint) WritePackets(r RouteInfo, pkts PacketBufferList, p\nreturn n, nil\n}\n+func (*fwdTestLinkEndpoint) WriteRawPacket(*PacketBuffer) tcpip.Error {\n+ return &tcpip.ErrNotSupported{}\n+}\n+\n// Wait implements stack.LinkEndpoint.Wait.\nfunc (*fwdTestLinkEndpoint) Wait() {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -846,6 +846,14 @@ type LinkEndpoint interface {\n// offload is enabled. If it will be used for something else, syscall filters\n// may need to be updated.\nWritePackets(RouteInfo, PacketBufferList, tcpip.NetworkProtocolNumber) (int, tcpip.Error)\n+\n+ // WriteRawPacket writes a packet directly to the link.\n+ //\n+ // If the link-layer has its own header, the payload must already include the\n+ // header.\n+ //\n+ // WriteRawPacket takes ownership of the packet.\n+ WriteRawPacket(*PacketBuffer) tcpip.Error\n}\n// InjectableLinkEndpoint is a LinkEndpoint where inbound packets are\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add LinkEndpoint.WriteRawPacket with stubs
...returning unsupported errors.
PiperOrigin-RevId: 393388991 |
259,898 | 30.08.2021 10:56:32 | 25,200 | 9625071e6dd6d949f6bd443910eaf56ce1c9762d | Avoid pseudo endpoint for TSVal generation | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/internal/tcp/BUILD",
"diff": "+load(\"//tools:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"tcp\",\n+ srcs = [\"tcp.go\"],\n+ visibility = [\"//pkg/tcpip:__subpackages__\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ ],\n+)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/internal/tcp/tcp.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Package tcp contains internal type definitions that are not expected to be\n+// used by anyone else outside pkg/tcpip.\n+package tcp\n+\n+import (\n+ \"time\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\n+\n+// TSOffset is an offset applied to the value of the TSVal field in the TCP\n+// Timestamp option.\n+//\n+// +stateify savable\n+type TSOffset struct {\n+ milliseconds uint32\n+}\n+\n+// NewTSOffset creates a new TSOffset from milliseconds.\n+func NewTSOffset(milliseconds uint32) TSOffset {\n+ return TSOffset{\n+ milliseconds: milliseconds,\n+ }\n+}\n+\n+// TSVal applies the offset to now and returns the timestamp in milliseconds.\n+func (offset TSOffset) TSVal(now tcpip.MonotonicTime) uint32 {\n+ return uint32(now.Sub(tcpip.MonotonicTime{}).Milliseconds()) + offset.milliseconds\n+}\n+\n+// Elapsed calculates the elapsed time given now and the echoed back timestamp.\n+func (offset TSOffset) Elapsed(now tcpip.MonotonicTime, tsEcr uint32) time.Duration {\n+ return time.Duration(offset.TSVal(now)-tsEcr) * time.Millisecond\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/BUILD",
"new_path": "pkg/tcpip/stack/BUILD",
"diff": "@@ -85,6 +85,7 @@ go_library(\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/hash/jenkins\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/internal/tcp\",\n\"//pkg/tcpip/ports\",\n\"//pkg/tcpip/seqnum\",\n\"//pkg/tcpip/transport/tcpconntrack\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/tcp.go",
"new_path": "pkg/tcpip/stack/tcp.go",
"diff": "@@ -19,6 +19,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/internal/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n)\n@@ -402,7 +403,7 @@ type TCPSndBufState struct {\ntype TCPEndpointStateInner struct {\n// TSOffset is a randomized offset added to the value of the TSVal\n// field in the timestamp option.\n- TSOffset uint32\n+ TSOffset tcp.TSOffset\n// SACKPermitted is set to true if the peer sends the TCPSACKPermitted\n// option in the SYN/SYN-ACK.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/BUILD",
"new_path": "pkg/tcpip/transport/tcp/BUILD",
"diff": "@@ -68,6 +68,7 @@ go_library(\n\"//pkg/tcpip/hash/jenkins\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/header/parse\",\n+ \"//pkg/tcpip/internal/tcp\",\n\"//pkg/tcpip/ports\",\n\"//pkg/tcpip/seqnum\",\n\"//pkg/tcpip/stack\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/accept.go",
"new_path": "pkg/tcpip/transport/tcp/accept.go",
"diff": "@@ -606,14 +606,9 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) tcpip.Err\nMSS: calculateAdvertisedMSS(e.userMSS, route),\n}\nif opts.TS {\n- // Create a barely-sufficient endpoint to calculate the TSVal.\n- pseudoEndpoint := endpoint{\n- TCPEndpointStateInner: stack.TCPEndpointStateInner{\n- TSOffset: e.protocol.tsOffset(s.dstAddr, s.srcAddr),\n- },\n- stack: e.stack,\n- }\n- synOpts.TSVal = pseudoEndpoint.tsValNow()\n+ offset := e.protocol.tsOffset(s.dstAddr, s.srcAddr)\n+ now := e.stack.Clock().NowMonotonic()\n+ synOpts.TSVal = offset.TSVal(now)\n}\ncookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))\nfields := tcpFields{\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2913,7 +2913,7 @@ func (e *endpoint) maybeEnableTimestamp(synOpts header.TCPSynOptions) {\n}\nfunc (e *endpoint) tsVal(now tcpip.MonotonicTime) uint32 {\n- return uint32(now.Sub(tcpip.MonotonicTime{}).Milliseconds()) + e.TSOffset\n+ return e.TSOffset.TSVal(now)\n}\nfunc (e *endpoint) tsValNow() uint32 {\n@@ -2921,7 +2921,7 @@ func (e *endpoint) tsValNow() uint32 {\n}\nfunc (e *endpoint) elapsed(now tcpip.MonotonicTime, tsEcr uint32) time.Duration {\n- return time.Duration(e.tsVal(now)-tsEcr) * time.Millisecond\n+ return e.TSOffset.Elapsed(now, tsEcr)\n}\n// maybeEnableSACKPermitted marks the SACKPermitted option enabled for this endpoint\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/protocol.go",
"new_path": "pkg/tcpip/transport/tcp/protocol.go",
"diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/hash/jenkins\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/header/parse\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/internal/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/seqnum\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/raw\"\n@@ -158,7 +159,7 @@ func (p *protocol) HandleUnknownDestinationPacket(id stack.TransportEndpointID,\nreturn stack.UnknownDestinationPacketHandled\n}\n-func (p *protocol) tsOffset(src, dst tcpip.Address) uint32 {\n+func (p *protocol) tsOffset(src, dst tcpip.Address) tcp.TSOffset {\n// Initialize a random tsOffset that will be added to the recentTS\n// everytime the timestamp is sent when the Timestamp option is enabled.\n//\n@@ -173,7 +174,7 @@ func (p *protocol) tsOffset(src, dst tcpip.Address) uint32 {\n// It never returns an error.\n_, _ = h.Write([]byte(src))\n_, _ = h.Write([]byte(dst))\n- return h.Sum32()\n+ return tcp.NewTSOffset(h.Sum32())\n}\n// replyWithReset replies to the given segment with a reset segment.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Avoid pseudo endpoint for TSVal generation
PiperOrigin-RevId: 393808461 |
259,885 | 30.08.2021 12:37:33 | 25,200 | 574c6542a538bc2917fc95e443cf0976946db1c0 | Use specialFileFD handles in specialFileFD.Stat(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"new_path": "pkg/sentry/fsimpl/gofer/gofer.go",
"diff": "@@ -995,7 +995,7 @@ func (d *dentry) refreshSizeLocked(ctx context.Context) error {\nif d.writeFD < 0 {\nd.handleMu.RUnlock()\n// Ask the gofer if we don't have a host FD.\n- return d.updateFromGetattrLocked(ctx)\n+ return d.updateFromGetattrLocked(ctx, p9file{})\n}\nvar stat unix.Statx_t\n@@ -1014,33 +1014,35 @@ func (d *dentry) updateFromGetattr(ctx context.Context) error {\n// updating stale attributes in d.updateFromP9AttrsLocked().\nd.metadataMu.Lock()\ndefer d.metadataMu.Unlock()\n- return d.updateFromGetattrLocked(ctx)\n+ return d.updateFromGetattrLocked(ctx, p9file{})\n}\n// Preconditions:\n// * !d.isSynthetic().\n// * d.metadataMu is locked.\n// +checklocks:d.metadataMu\n-func (d *dentry) updateFromGetattrLocked(ctx context.Context) error {\n- // Use d.readFile or d.writeFile, which represent 9P FIDs that have been\n- // opened, in preference to d.file, which represents a 9P fid that has not.\n- // This may be significantly more efficient in some implementations. Prefer\n- // d.writeFile over d.readFile since some filesystem implementations may\n- // update a writable handle's metadata after writes to that handle, without\n- // making metadata updates immediately visible to read-only handles\n- // representing the same file.\n+func (d *dentry) updateFromGetattrLocked(ctx context.Context, file p9file) error {\n+ handleMuRLocked := false\n+ if file.isNil() {\n+ // Use d.readFile or d.writeFile, which represent 9P FIDs that have\n+ // been opened, in preference to d.file, which represents a 9P fid that\n+ // has not. This may be significantly more efficient in some\n+ // implementations. Prefer d.writeFile over d.readFile since some\n+ // filesystem implementations may update a writable handle's metadata\n+ // after writes to that handle, without making metadata updates\n+ // immediately visible to read-only handles representing the same file.\nd.handleMu.RLock()\n- handleMuRLocked := true\n- var file p9file\nswitch {\ncase !d.writeFile.isNil():\nfile = d.writeFile\n+ handleMuRLocked = true\ncase !d.readFile.isNil():\nfile = d.readFile\n+ handleMuRLocked = true\ndefault:\nfile = d.file\nd.handleMu.RUnlock()\n- handleMuRLocked = false\n+ }\n}\n_, attrMask, attr, err := file.getAttr(ctx, dentryAttrMask())\n@@ -2044,9 +2046,17 @@ func (fd *fileDescription) Stat(ctx context.Context, opts vfs.StatOptions) (linu\nd := fd.dentry()\nconst validMask = uint32(linux.STATX_MODE | linux.STATX_UID | linux.STATX_GID | linux.STATX_ATIME | linux.STATX_MTIME | linux.STATX_CTIME | linux.STATX_SIZE | linux.STATX_BLOCKS | linux.STATX_BTIME)\nif !d.cachedMetadataAuthoritative() && opts.Mask&validMask != 0 && opts.Sync != linux.AT_STATX_DONT_SYNC {\n- // TODO(jamieliu): Use specialFileFD.handle.file for the getattr if\n- // available?\n- if err := d.updateFromGetattr(ctx); err != nil {\n+ // Use specialFileFD.handle.file for the getattr if available, for the\n+ // same reason that we try to use open file handles in\n+ // dentry.updateFromGetattrLocked().\n+ var file p9file\n+ if sffd, ok := fd.vfsfd.Impl().(*specialFileFD); ok {\n+ file = sffd.handle.file\n+ }\n+ d.metadataMu.Lock()\n+ err := d.updateFromGetattrLocked(ctx, file)\n+ d.metadataMu.Unlock()\n+ if err != nil {\nreturn linux.Statx{}, err\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use specialFileFD handles in specialFileFD.Stat().
PiperOrigin-RevId: 393831108 |
259,885 | 30.08.2021 13:25:31 | 25,200 | a247e227b1f629392d0a9132dc490a6ef9ee2519 | Narrow COW-break on thread stacks. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/mm/pma.go",
"new_path": "pkg/sentry/mm/pma.go",
"diff": "@@ -324,20 +324,37 @@ func (mm *MemoryManager) getPMAsInternalLocked(ctx context.Context, vseg vmaIter\npanic(fmt.Sprintf(\"pma %v needs to be copied for writing, but is not readable: %v\", pseg.Range(), oldpma))\n}\n}\n- // The majority of copy-on-write breaks on executable pages\n- // come from:\n+ var copyAR hostarch.AddrRange\n+ if vma := vseg.ValuePtr(); vma.effectivePerms.Execute {\n+ // The majority of copy-on-write breaks on executable\n+ // pages come from:\n//\n- // - The ELF loader, which must zero out bytes on the last\n- // page of each segment after the end of the segment.\n+ // - The ELF loader, which must zero out bytes on the\n+ // last page of each segment after the end of the\n+ // segment.\n//\n// - gdb's use of ptrace to insert breakpoints.\n//\n- // Neither of these cases has enough spatial locality to\n- // benefit from copying nearby pages, so if the vma is\n- // executable, only copy the pages required.\n- var copyAR hostarch.AddrRange\n- if vseg.ValuePtr().effectivePerms.Execute {\n+ // Neither of these cases has enough spatial locality\n+ // to benefit from copying nearby pages, so if the vma\n+ // is executable, only copy the pages required.\ncopyAR = pseg.Range().Intersect(ar)\n+ } else if vma.growsDown {\n+ // In most cases, the new process will not use most of\n+ // its stack before exiting or invoking execve(); it is\n+ // especially unlikely to return very far down its call\n+ // stack, since async-signal-safety concerns in\n+ // multithreaded programs prevent the new process from\n+ // being able to do much. So only copy up to one page\n+ // before and after the pages required.\n+ stackMaskAR := ar\n+ if newStart := stackMaskAR.Start - hostarch.PageSize; newStart < stackMaskAR.Start {\n+ stackMaskAR.Start = newStart\n+ }\n+ if newEnd := stackMaskAR.End + hostarch.PageSize; newEnd > stackMaskAR.End {\n+ stackMaskAR.End = newEnd\n+ }\n+ copyAR = pseg.Range().Intersect(stackMaskAR)\n} else {\ncopyAR = pseg.Range().Intersect(maskAR)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Narrow COW-break on thread stacks.
PiperOrigin-RevId: 393841270 |
259,975 | 30.08.2021 15:32:22 | 25,200 | dfbcb8903ae8bd0d1ff984889f1b5cf1e041865e | [syserr] Fix SIGBUS on syserr.FromError
Fix syzcaller panic SIGBUS on error handling. Done by
adding an interface, errors.GuestError, which errors can
implement in order to be compared against each other. | [
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/BUILD",
"new_path": "pkg/syserr/BUILD",
"diff": "@@ -14,6 +14,7 @@ go_library(\n\"//pkg/abi/linux/errno\",\n\"//pkg/errors\",\n\"//pkg/errors/linuxerr\",\n+ \"//pkg/safecopy\",\n\"//pkg/tcpip\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/syserr/syserr.go",
"new_path": "pkg/syserr/syserr.go",
"diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux/errno\"\n\"gvisor.dev/gvisor/pkg/errors\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/safecopy\"\n)\n// Error represents an internal error.\n@@ -278,15 +279,18 @@ func FromError(err error) *Error {\nif err == nil {\nreturn nil\n}\n- if errno, ok := err.(unix.Errno); ok {\n- return FromHost(errno)\n- }\n- if linuxErr, ok := err.(*errors.Error); ok {\n- return FromHost(unix.Errno(linuxErr.Errno()))\n+ switch e := err.(type) {\n+ case unix.Errno:\n+ return FromHost(e)\n+ case *errors.Error:\n+ return FromHost(unix.Errno(e.Errno()))\n+ case safecopy.SegvError, safecopy.BusError, safecopy.AlignmentError:\n+ return FromHost(unix.EFAULT)\n}\n- panic(\"unknown error: \" + err.Error())\n+ msg := fmt.Sprintf(\"err: %s type: %T\", err.Error(), err)\n+ panic(msg)\n}\n// ConvertIntr converts the provided error code (err) to another one (intr) if\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -3293,9 +3293,12 @@ cc_library(\n],\ndeps = [\n\":unix_domain_socket_test_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:memory_util\",\n\"//test/util:socket_util\",\n\"@com_google_absl//absl/strings\",\ngtest,\n+ \"//test/util:temp_path\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix.cc",
"new_path": "test/syscalls/linux/socket_unix.cc",
"diff": "#include \"gtest/gtest.h\"\n#include \"absl/strings/string_view.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/memory_util.h\"\n#include \"test/util/socket_util.h\"\n+#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\n@@ -268,6 +271,18 @@ TEST_P(UnixSocketPairTest, SocketReopenFromProcfs) {\n}\n}\n+// Repro for b/196804997.\n+TEST_P(UnixSocketPairTest, SendFromMmapBeyondEof) {\n+ TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+ Mapping m = ASSERT_NO_ERRNO_AND_VALUE(\n+ Mmap(nullptr, kPageSize, PROT_READ, MAP_SHARED, fd.get(), 0));\n+\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ ASSERT_THAT(send(sockets->first_fd(), m.ptr(), m.len(), 0),\n+ SyscallFailsWithErrno(EFAULT));\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | [syserr] Fix SIGBUS on syserr.FromError
Fix syzcaller panic SIGBUS on error handling. Done by
adding an interface, errors.GuestError, which errors can
implement in order to be compared against each other.
PiperOrigin-RevId: 393867554 |
259,885 | 31.08.2021 23:09:45 | 25,200 | c5cc6a65664fed83932596abf2a446a93e357bbe | Remove splice-to/from-weird-files tests.
These tests are permanently broken on Linux after "fs: don't allow
splice read/write without explicit ops". | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/eventfd.cc",
"new_path": "test/syscalls/linux/eventfd.cc",
"diff": "@@ -149,31 +149,6 @@ TEST(EventfdTest, BigWriteBigRead) {\nEXPECT_EQ(l[0], 1);\n}\n-TEST(EventfdTest, SpliceFromPipePartialSucceeds) {\n- int pipes[2];\n- ASSERT_THAT(pipe2(pipes, O_NONBLOCK), SyscallSucceeds());\n- const FileDescriptor pipe_rfd(pipes[0]);\n- const FileDescriptor pipe_wfd(pipes[1]);\n- constexpr uint64_t kVal{1};\n-\n- FileDescriptor efd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, EFD_NONBLOCK));\n-\n- uint64_t event_array[2];\n- event_array[0] = kVal;\n- event_array[1] = kVal;\n- ASSERT_THAT(write(pipe_wfd.get(), event_array, sizeof(event_array)),\n- SyscallSucceedsWithValue(sizeof(event_array)));\n- EXPECT_THAT(splice(pipe_rfd.get(), /*__offin=*/nullptr, efd.get(),\n- /*__offout=*/nullptr, sizeof(event_array[0]) + 1,\n- SPLICE_F_NONBLOCK),\n- SyscallSucceedsWithValue(sizeof(event_array[0])));\n-\n- uint64_t val;\n- ASSERT_THAT(read(efd.get(), &val, sizeof(val)),\n- SyscallSucceedsWithValue(sizeof(val)));\n- EXPECT_EQ(val, kVal);\n-}\n-\n// NotifyNonZero is inherently racy, so random save is disabled.\nTEST(EventfdTest, NotifyNonZero) {\n// Waits will time out at 10 seconds.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/inotify.cc",
"new_path": "test/syscalls/linux/inotify.cc",
"diff": "@@ -1849,34 +1849,6 @@ TEST(Inotify, SpliceOnWatchTarget) {\n}));\n}\n-TEST(Inotify, SpliceOnInotifyFD) {\n- int pipefds[2];\n- ASSERT_THAT(pipe2(pipefds, O_NONBLOCK), SyscallSucceeds());\n-\n- const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n- const FileDescriptor fd =\n- ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n- const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n- root.path(), \"some content\", TempPath::kDefaultFileMode));\n-\n- const FileDescriptor file1_fd =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));\n- const int watcher = ASSERT_NO_ERRNO_AND_VALUE(\n- InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\n-\n- char buf;\n- EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());\n-\n- EXPECT_THAT(splice(fd.get(), nullptr, pipefds[1], nullptr,\n- sizeof(struct inotify_event) + 1, SPLICE_F_NONBLOCK),\n- SyscallSucceedsWithValue(sizeof(struct inotify_event)));\n-\n- const FileDescriptor read_fd(pipefds[0]);\n- const std::vector<Event> events =\n- ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(read_fd.get()));\n- ASSERT_THAT(events, Are({Event(IN_ACCESS, watcher)}));\n-}\n-\n// Watches on a parent should not be triggered by actions on a hard link to one\n// of its children that has a different parent.\nTEST(Inotify, LinkOnOtherParent) {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sendfile.cc",
"new_path": "test/syscalls/linux/sendfile.cc",
"diff": "@@ -208,38 +208,6 @@ TEST(SendFileTest, SendAndUpdateFileOffset) {\nabsl::string_view(actual, kHalfDataSize));\n}\n-TEST(SendFileTest, SendToDevZeroAndUpdateFileOffset) {\n- // Create temp files.\n- // Test input string length must be > 2 AND even.\n- constexpr char kData[] = \"The slings and arrows of outrageous fortune,\";\n- constexpr int kDataSize = sizeof(kData) - 1;\n- constexpr int kHalfDataSize = kDataSize / 2;\n- const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n- GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n-\n- // Open the input file as read only.\n- const FileDescriptor inf =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDONLY));\n-\n- // Open /dev/zero as write only.\n- const FileDescriptor outf =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/zero\", O_WRONLY));\n-\n- // Send data and verify that sendfile returns the correct value.\n- int bytes_sent;\n- EXPECT_THAT(\n- bytes_sent = sendfile(outf.get(), inf.get(), nullptr, kHalfDataSize),\n- SyscallSucceedsWithValue(kHalfDataSize));\n-\n- char actual[kHalfDataSize];\n- // Verify that the input file offset has been updated.\n- ASSERT_THAT(read(inf.get(), &actual, kDataSize - bytes_sent),\n- SyscallSucceedsWithValue(kHalfDataSize));\n- EXPECT_EQ(\n- absl::string_view(kData + kDataSize - bytes_sent, kDataSize - bytes_sent),\n- absl::string_view(actual, kHalfDataSize));\n-}\n-\nTEST(SendFileTest, SendAndUpdateFileOffsetFromNonzeroStartingPoint) {\n// Create temp files.\n// Test input string length must be > 2 AND divisible by 4.\n@@ -609,23 +577,6 @@ TEST(SendFileTest, SendPipeBlocks) {\nSyscallSucceedsWithValue(kDataSize));\n}\n-TEST(SendFileTest, SendToSpecialFile) {\n- // Create temp file.\n- const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n- GetAbsoluteTestTmpdir(), \"\", TempPath::kDefaultFileMode));\n-\n- const FileDescriptor inf =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n- constexpr int kSize = 0x7ff;\n- ASSERT_THAT(ftruncate(inf.get(), kSize), SyscallSucceeds());\n-\n- auto eventfd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD());\n-\n- // eventfd can accept a number of bytes which is a multiple of 8.\n- EXPECT_THAT(sendfile(eventfd.get(), inf.get(), nullptr, 0xfffff),\n- SyscallSucceedsWithValue(kSize & (~7)));\n-}\n-\nTEST(SendFileTest, SendFileToPipe) {\n// Create temp file.\nconstexpr char kData[] = \"<insert-quote-here>\";\n@@ -672,57 +623,6 @@ TEST(SendFileTest, SendFileToSelf) {\nSyscallSucceedsWithValue(kSendfileSize));\n}\n-static volatile int signaled = 0;\n-void SigUsr1Handler(int sig, siginfo_t* info, void* context) { signaled = 1; }\n-\n-TEST(SendFileTest, ToEventFDDoesNotSpin) {\n- FileDescriptor efd = ASSERT_NO_ERRNO_AND_VALUE(NewEventFD(0, 0));\n-\n- // Write the maximum value of an eventfd to a file.\n- const uint64_t kMaxEventfdValue = 0xfffffffffffffffe;\n- const auto tempfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n- const auto tempfd = ASSERT_NO_ERRNO_AND_VALUE(Open(tempfile.path(), O_RDWR));\n- ASSERT_THAT(\n- pwrite(tempfd.get(), &kMaxEventfdValue, sizeof(kMaxEventfdValue), 0),\n- SyscallSucceedsWithValue(sizeof(kMaxEventfdValue)));\n-\n- // Set the eventfd's value to 1.\n- const uint64_t kOne = 1;\n- ASSERT_THAT(write(efd.get(), &kOne, sizeof(kOne)),\n- SyscallSucceedsWithValue(sizeof(kOne)));\n-\n- // Set up signal handler.\n- struct sigaction sa = {};\n- sa.sa_sigaction = SigUsr1Handler;\n- sa.sa_flags = SA_SIGINFO;\n- const auto cleanup_sigact =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGUSR1, sa));\n-\n- // Send SIGUSR1 to this thread in 1 second.\n- struct sigevent sev = {};\n- sev.sigev_notify = SIGEV_THREAD_ID;\n- sev.sigev_signo = SIGUSR1;\n- sev.sigev_notify_thread_id = gettid();\n- auto timer = ASSERT_NO_ERRNO_AND_VALUE(TimerCreate(CLOCK_MONOTONIC, sev));\n- struct itimerspec its = {};\n- its.it_value = absl::ToTimespec(absl::Seconds(1));\n- DisableSave ds; // Asserting an EINTR.\n- ASSERT_NO_ERRNO(timer.Set(0, its));\n-\n- // Sendfile from tempfd to the eventfd. Since the eventfd is not already at\n- // its maximum value, the eventfd is \"ready for writing\"; however, since the\n- // eventfd's existing value plus the new value would exceed the maximum, the\n- // write should internally fail with EWOULDBLOCK. In this case, sendfile()\n- // should block instead of spinning, and eventually be interrupted by our\n- // timer. See b/172075629.\n- EXPECT_THAT(\n- sendfile(efd.get(), tempfd.get(), nullptr, sizeof(kMaxEventfdValue)),\n- SyscallFailsWithErrno(EINTR));\n-\n- // Signal should have been handled.\n- EXPECT_EQ(signaled, 1);\n-}\n-\n} // namespace\n} // namespace testing\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/splice.cc",
"new_path": "test/syscalls/linux/splice.cc",
"diff": "@@ -195,81 +195,6 @@ TEST(SpliceTest, PipeOffsets) {\nSyscallFailsWithErrno(ESPIPE));\n}\n-// Event FDs may be used with splice without an offset.\n-TEST(SpliceTest, FromEventFD) {\n- // Open the input eventfd with an initial value so that it is readable.\n- constexpr uint64_t kEventFDValue = 1;\n- int efd;\n- ASSERT_THAT(efd = eventfd(kEventFDValue, 0), SyscallSucceeds());\n- const FileDescriptor in_fd(efd);\n-\n- // Create a new pipe.\n- int fds[2];\n- ASSERT_THAT(pipe(fds), SyscallSucceeds());\n- const FileDescriptor rfd(fds[0]);\n- const FileDescriptor wfd(fds[1]);\n-\n- // Splice 8-byte eventfd value to pipe.\n- constexpr int kEventFDSize = 8;\n- EXPECT_THAT(splice(in_fd.get(), nullptr, wfd.get(), nullptr, kEventFDSize, 0),\n- SyscallSucceedsWithValue(kEventFDSize));\n-\n- // Contents should be equal.\n- std::vector<char> rbuf(kEventFDSize);\n- ASSERT_THAT(read(rfd.get(), rbuf.data(), rbuf.size()),\n- SyscallSucceedsWithValue(kEventFDSize));\n- EXPECT_EQ(memcmp(rbuf.data(), &kEventFDValue, rbuf.size()), 0);\n-}\n-\n-// Event FDs may not be used with splice with an offset.\n-TEST(SpliceTest, FromEventFDOffset) {\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());\n- const FileDescriptor in_fd(efd);\n-\n- // Create a new pipe.\n- int fds[2];\n- ASSERT_THAT(pipe(fds), SyscallSucceeds());\n- const FileDescriptor rfd(fds[0]);\n- const FileDescriptor wfd(fds[1]);\n-\n- // Attempt to splice 8-byte eventfd value to pipe with offset.\n- //\n- // This is not allowed because eventfd doesn't support pread.\n- constexpr int kEventFDSize = 8;\n- loff_t in_off = 0;\n- EXPECT_THAT(splice(in_fd.get(), &in_off, wfd.get(), nullptr, kEventFDSize, 0),\n- SyscallFailsWithErrno(EINVAL));\n-}\n-\n-// Event FDs may not be used with splice with an offset.\n-TEST(SpliceTest, ToEventFDOffset) {\n- // Create a new pipe.\n- int fds[2];\n- ASSERT_THAT(pipe(fds), SyscallSucceeds());\n- const FileDescriptor rfd(fds[0]);\n- const FileDescriptor wfd(fds[1]);\n-\n- // Fill with a value.\n- constexpr int kEventFDSize = 8;\n- std::vector<char> buf(kEventFDSize);\n- buf[0] = 1;\n- ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),\n- SyscallSucceedsWithValue(kEventFDSize));\n-\n- int efd;\n- ASSERT_THAT(efd = eventfd(0, 0), SyscallSucceeds());\n- const FileDescriptor out_fd(efd);\n-\n- // Attempt to splice 8-byte eventfd value to pipe with offset.\n- //\n- // This is not allowed because eventfd doesn't support pwrite.\n- loff_t out_off = 0;\n- EXPECT_THAT(\n- splice(rfd.get(), nullptr, out_fd.get(), &out_off, kEventFDSize, 0),\n- SyscallFailsWithErrno(EINVAL));\n-}\n-\nTEST(SpliceTest, ToPipe) {\n// Open the input file.\nconst TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n@@ -852,34 +777,6 @@ TEST(SpliceTest, FromPipeMaxFileSize) {\nEXPECT_EQ(memcmp(rbuf.data(), buf.data(), buf.size()), 0);\n}\n-TEST(SpliceTest, FromPipeToDevZero) {\n- // Create a new pipe.\n- int fds[2];\n- ASSERT_THAT(pipe(fds), SyscallSucceeds());\n- const FileDescriptor rfd(fds[0]);\n- FileDescriptor wfd(fds[1]);\n-\n- // Fill with some random data.\n- std::vector<char> buf(kPageSize);\n- RandomizeBuffer(buf.data(), buf.size());\n- ASSERT_THAT(write(wfd.get(), buf.data(), buf.size()),\n- SyscallSucceedsWithValue(kPageSize));\n-\n- const FileDescriptor zero =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(\"/dev/zero\", O_WRONLY));\n-\n- // Close the write end to prevent blocking below.\n- wfd.reset();\n-\n- // Splice to /dev/zero. The first call should empty the pipe, and the return\n- // value should not exceed the number of bytes available for reading.\n- EXPECT_THAT(\n- splice(rfd.get(), nullptr, zero.get(), nullptr, kPageSize + 123, 0),\n- SyscallSucceedsWithValue(kPageSize));\n- EXPECT_THAT(splice(rfd.get(), nullptr, zero.get(), nullptr, 1, 0),\n- SyscallSucceedsWithValue(0));\n-}\n-\nstatic volatile int signaled = 0;\nvoid SigUsr1Handler(int sig, siginfo_t* info, void* context) { signaled = 1; }\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove splice-to/from-weird-files tests.
These tests are permanently broken on Linux after 36e2c7421f02 "fs: don't allow
splice read/write without explicit ops".
PiperOrigin-RevId: 394161079 |
259,885 | 01.09.2021 10:27:30 | 25,200 | 810ea0957517bcfc459627aeb10a3594340c895b | Cache cpuid.HostFeatureSet(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid.go",
"new_path": "pkg/cpuid/cpuid.go",
"diff": "@@ -37,6 +37,14 @@ package cpuid\n// arch/arm64/include/uapi/asm/hwcap.h\ntype Feature int\n+// HostFeatureSet returns a FeatureSet that matches that of the host machine.\n+// Callers must not mutate the returned FeatureSet.\n+func HostFeatureSet() *FeatureSet {\n+ return hostFeatureSet\n+}\n+\n+var hostFeatureSet = getHostFeatureSet()\n+\n// ErrIncompatible is returned by FeatureSet.HostCompatible if fs is not a\n// subset of the host feature set.\ntype ErrIncompatible struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_arm64.go",
"new_path": "pkg/cpuid/cpuid_arm64.go",
"diff": "@@ -230,6 +230,16 @@ type FeatureSet struct {\nCPURevision uint8\n}\n+// Clone returns a copy of fs.\n+func (fs *FeatureSet) Clone() *FeatureSet {\n+ fs2 := *fs\n+ fs2.Set = make(map[Feature]bool)\n+ for f, b := range fs.Set {\n+ fs2.Set[f] = b\n+ }\n+ return &fs2\n+}\n+\n// CheckHostCompatible returns nil if fs is a subset of the host feature set.\n// Noop on arm64.\nfunc (fs *FeatureSet) CheckHostCompatible() error {\n@@ -292,9 +302,9 @@ func (fs FeatureSet) WriteCPUInfoTo(cpu uint, b *bytes.Buffer) {\nfmt.Fprintln(b, \"\") // The /proc/cpuinfo file ends with an extra newline.\n}\n-// HostFeatureSet uses hwCap to get host values and construct a feature set\n+// getHostFeatureSet uses hwCap to get host values and construct a feature set\n// that matches that of the host machine.\n-func HostFeatureSet() *FeatureSet {\n+func getHostFeatureSet() *FeatureSet {\ns := make(map[Feature]bool)\nfor f := range arm64FeatureStrings {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/cpuid/cpuid_x86.go",
"new_path": "pkg/cpuid/cpuid_x86.go",
"diff": "@@ -627,6 +627,17 @@ type FeatureSet struct {\nCacheLine uint32\n}\n+// Clone returns a copy of fs.\n+func (fs *FeatureSet) Clone() *FeatureSet {\n+ fs2 := *fs\n+ fs2.Set = make(map[Feature]bool)\n+ for f, b := range fs.Set {\n+ fs2.Set[f] = b\n+ }\n+ fs2.Caches = append([]Cache(nil), fs.Caches...)\n+ return &fs2\n+}\n+\n// FlagsString prints out supported CPU flags. If cpuinfoOnly is true, it is\n// equivalent to the \"flags\" field in /proc/cpuinfo.\nfunc (fs *FeatureSet) FlagsString(cpuinfoOnly bool) string {\n@@ -961,13 +972,13 @@ func (fs *FeatureSet) UseXsaveopt() bool {\n// HostID executes a native CPUID instruction.\nfunc HostID(axArg, cxArg uint32) (ax, bx, cx, dx uint32)\n-// HostFeatureSet uses cpuid to get host values and construct a feature set\n+// getHostFeatureSet uses cpuid to get host values and construct a feature set\n// that matches that of the host machine. Note that there are several places\n// where there appear to be some unnecessary assignments between register names\n// (ax, bx, cx, or dx) and featureBlockN variables. This is to explicitly show\n// where the different feature blocks come from, to make the code easier to\n// inspect and read.\n-func HostFeatureSet() *FeatureSet {\n+func getHostFeatureSet() *FeatureSet {\n// eax=0 gets max supported feature and vendor ID.\n_, bx, cx, dx := HostID(0, 0)\nvendorID := vendorIDFromRegs(bx, cx, dx)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache cpuid.HostFeatureSet().
PiperOrigin-RevId: 394261815 |
259,896 | 01.09.2021 10:43:26 | 25,200 | 5e3a5189152e682f94c745a544993c26e18eb9a2 | gVisor rack blog
A blog about RACK loss detection algorithm implemented in gVisor.
(https://datatracker.ietf.org/doc/rfc8985/) | [
{
"change_type": "MODIFY",
"old_path": "website/_config.yml",
"new_path": "website/_config.yml",
"diff": "@@ -44,3 +44,6 @@ authors:\nmpratt:\nname: Michael Pratt\nemail: [email protected]\n+ nybidari:\n+ name: Nayana Bidari\n+ email: [email protected]\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/images/2021-08-31-rack-figure1.png",
"new_path": "website/assets/images/2021-08-31-rack-figure1.png",
"diff": "Binary files /dev/null and b/website/assets/images/2021-08-31-rack-figure1.png differ\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/images/2021-08-31-rack-figure2.png",
"new_path": "website/assets/images/2021-08-31-rack-figure2.png",
"diff": "Binary files /dev/null and b/website/assets/images/2021-08-31-rack-figure2.png differ\n"
},
{
"change_type": "ADD",
"old_path": "website/assets/images/2021-08-31-rack-figure3.png",
"new_path": "website/assets/images/2021-08-31-rack-figure3.png",
"diff": "Binary files /dev/null and b/website/assets/images/2021-08-31-rack-figure3.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "website/blog/BUILD",
"new_path": "website/blog/BUILD",
"diff": "@@ -49,6 +49,16 @@ doc(\npermalink = \"/blog/2020/10/22/platform-portability/\",\n)\n+doc(\n+ name = \"gvisor-rack\",\n+ src = \"2021-08-31-gvisor-rack.md\",\n+ authors = [\n+ \"nybidari\",\n+ ],\n+ layout = \"post\",\n+ permalink = \"/blog/2021/08/31/gvisor-rack/\",\n+)\n+\ndocs(\nname = \"posts\",\ndeps = [\n"
}
] | Go | Apache License 2.0 | google/gvisor | gVisor rack blog
A blog about RACK loss detection algorithm implemented in gVisor.
(https://datatracker.ietf.org/doc/rfc8985/)
PiperOrigin-RevId: 394265634 |
259,853 | 01.09.2021 11:46:02 | 25,200 | 927ea16dd384f675a2ce1456be457a371109c488 | unix: handle a case when a buffer is overflowed
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/queue.go",
"new_path": "pkg/sentry/socket/unix/transport/queue.go",
"diff": "@@ -133,7 +133,7 @@ func (q *queue) Enqueue(ctx context.Context, data [][]byte, c ControlMessages, f\nfree := q.limit - q.used\nif l > free && truncate {\n- if free == 0 {\n+ if free <= 0 {\n// Message can't fit right now.\nq.mu.Unlock()\nreturn 0, false, syserr.ErrWouldBlock\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix_stream.cc",
"new_path": "test/syscalls/linux/socket_unix_stream.cc",
"diff": "@@ -181,6 +181,21 @@ TEST_P(StreamUnixSocketPairTest, SetSocketSendBuf) {\nASSERT_EQ(quarter_sz, val);\n}\n+TEST_P(StreamUnixSocketPairTest, SendBufferOverflow) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+ auto s = sockets->first_fd();\n+\n+ constexpr int kBufSz = 4096;\n+ std::vector<char> buf(kBufSz * 4);\n+ ASSERT_THAT(RetryEINTR(send)(s, buf.data(), buf.size(), MSG_DONTWAIT),\n+ SyscallSucceeds());\n+ // The new buffer size should be smaller that the amount of data in the queue.\n+ ASSERT_THAT(setsockopt(s, SOL_SOCKET, SO_SNDBUF, &kBufSz, sizeof(kBufSz)),\n+ SyscallSucceeds());\n+ ASSERT_THAT(RetryEINTR(send)(s, buf.data(), buf.size(), MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\nTEST_P(StreamUnixSocketPairTest, IncreasedSocketSendBufUnblocksWrites) {\nauto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\nint sock = sockets->first_fd();\n"
}
] | Go | Apache License 2.0 | google/gvisor | unix: handle a case when a buffer is overflowed
Reported-by: [email protected]
PiperOrigin-RevId: 394279838 |
259,885 | 01.09.2021 13:05:27 | 25,200 | 5da4270a884e9f0c88d583da34f757783f314645 | Propagate vfs.MkdirOptions.ForSyntheticMountpoint to overlay copy-up. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/copy_up.go",
"new_path": "pkg/sentry/fsimpl/overlay/copy_up.go",
"diff": "@@ -36,6 +36,10 @@ func (d *dentry) isCopiedUp() bool {\n//\n// Preconditions: filesystem.renameMu must be locked.\nfunc (d *dentry) copyUpLocked(ctx context.Context) error {\n+ return d.copyUpMaybeSyntheticMountpointLocked(ctx, false /* forSyntheticMountpoint */)\n+}\n+\n+func (d *dentry) copyUpMaybeSyntheticMountpointLocked(ctx context.Context, forSyntheticMountpoint bool) error {\n// Fast path.\nif d.isCopiedUp() {\nreturn nil\n@@ -59,7 +63,7 @@ func (d *dentry) copyUpLocked(ctx context.Context) error {\n// d is a filesystem root with no upper layer.\nreturn linuxerr.EROFS\n}\n- if err := d.parent.copyUpLocked(ctx); err != nil {\n+ if err := d.parent.copyUpMaybeSyntheticMountpointLocked(ctx, forSyntheticMountpoint); err != nil {\nreturn err\n}\n@@ -169,6 +173,7 @@ func (d *dentry) copyUpLocked(ctx context.Context) error {\ncase linux.S_IFDIR:\nif err := vfsObj.MkdirAt(ctx, d.fs.creds, &newpop, &vfs.MkdirOptions{\nMode: linux.FileMode(d.mode &^ linux.S_IFMT),\n+ ForSyntheticMountpoint: forSyntheticMountpoint,\n}); err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"new_path": "pkg/sentry/fsimpl/overlay/filesystem.go",
"diff": "@@ -462,13 +462,21 @@ func (fs *filesystem) resolveLocked(ctx context.Context, rp *vfs.ResolvingPath,\nreturn d, nil\n}\n+type createType int\n+\n+const (\n+ createNonDirectory createType = iota\n+ createDirectory\n+ createSyntheticMountpoint\n+)\n+\n// doCreateAt checks that creating a file at rp is permitted, then invokes\n// create to do so.\n//\n// Preconditions:\n// * !rp.Done().\n// * For the final path component in rp, !rp.ShouldFollowSymlink().\n-func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir bool, create func(parent *dentry, name string, haveUpperWhiteout bool) error) error {\n+func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, ct createType, create func(parent *dentry, name string, haveUpperWhiteout bool) error) error {\nvar ds *[]*dentry\nfs.renameMu.RLock()\ndefer fs.renameMuRUnlockAndCheckDrop(ctx, &ds)\n@@ -504,7 +512,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nreturn linuxerr.EEXIST\n}\n- if !dir && rp.MustBeDir() {\n+ if ct == createNonDirectory && rp.MustBeDir() {\nreturn linuxerr.ENOENT\n}\n@@ -518,7 +526,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\n}\n// Ensure that the parent directory is copied-up so that we can create the\n// new file in the upper layer.\n- if err := parent.copyUpLocked(ctx); err != nil {\n+ if err := parent.copyUpMaybeSyntheticMountpointLocked(ctx, ct == createSyntheticMountpoint); err != nil {\nreturn err\n}\n@@ -529,7 +537,7 @@ func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir\nparent.dirents = nil\nev := linux.IN_CREATE\n- if dir {\n+ if ct != createNonDirectory {\nev |= linux.IN_ISDIR\n}\nparent.watches.Notify(ctx, name, uint32(ev), 0 /* cookie */, vfs.InodeEvent, false /* unlinked */)\n@@ -618,7 +626,7 @@ func (fs *filesystem) GetParentDentryAt(ctx context.Context, rp *vfs.ResolvingPa\n// LinkAt implements vfs.FilesystemImpl.LinkAt.\nfunc (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry) error {\n- return fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\n+ return fs.doCreateAt(ctx, rp, createNonDirectory, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\nif rp.Mount() != vd.Mount() {\nreturn linuxerr.EXDEV\n}\n@@ -671,7 +679,11 @@ func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.\n// MkdirAt implements vfs.FilesystemImpl.MkdirAt.\nfunc (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {\n- return fs.doCreateAt(ctx, rp, true /* dir */, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\n+ ct := createDirectory\n+ if opts.ForSyntheticMountpoint {\n+ ct = createSyntheticMountpoint\n+ }\n+ return fs.doCreateAt(ctx, rp, ct, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\nvfsObj := fs.vfsfs.VirtualFilesystem()\npop := vfs.PathOperation{\nRoot: parent.upperVD,\n@@ -722,7 +734,7 @@ func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n// MknodAt implements vfs.FilesystemImpl.MknodAt.\nfunc (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {\n- return fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\n+ return fs.doCreateAt(ctx, rp, createNonDirectory, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\n// Disallow attempts to create whiteouts.\nif opts.Mode&linux.S_IFMT == linux.S_IFCHR && opts.DevMajor == 0 && opts.DevMinor == 0 {\nreturn linuxerr.EPERM\n@@ -1476,7 +1488,7 @@ func (fs *filesystem) StatFSAt(ctx context.Context, rp *vfs.ResolvingPath) (linu\n// SymlinkAt implements vfs.FilesystemImpl.SymlinkAt.\nfunc (fs *filesystem) SymlinkAt(ctx context.Context, rp *vfs.ResolvingPath, target string) error {\n- return fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\n+ return fs.doCreateAt(ctx, rp, createNonDirectory, func(parent *dentry, childName string, haveUpperWhiteout bool) error {\nvfsObj := fs.vfsfs.VirtualFilesystem()\npop := vfs.PathOperation{\nRoot: parent.upperVD,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Propagate vfs.MkdirOptions.ForSyntheticMountpoint to overlay copy-up.
PiperOrigin-RevId: 394296687 |
259,885 | 01.09.2021 13:21:40 | 25,200 | 702fe7d60da4d38344f00200187fe1f0766bef8d | Cache vdso.so's __kernel_rt_sigreturn location. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/loader.go",
"new_path": "pkg/sentry/loader/loader.go",
"diff": "@@ -295,15 +295,7 @@ func Load(ctx context.Context, args LoadArgs, extraAuxv []arch.AuxEntry, vdso *V\nm.SetEnvvEnd(sl.EnvvEnd)\nm.SetAuxv(auxv)\nm.SetExecutable(ctx, file)\n-\n- symbolValue, err := getSymbolValueFromVDSO(\"rt_sigreturn\")\n- if err != nil {\n- return 0, nil, \"\", syserr.NewDynamic(fmt.Sprintf(\"Failed to find rt_sigreturn in vdso: %v\", err), syserr.FromError(err).ToLinux())\n- }\n-\n- // Found rt_sigretrun.\n- addr := uint64(vdsoAddr) + symbolValue - vdsoPrelink\n- m.SetVDSOSigReturn(addr)\n+ m.SetVDSOSigReturn(uint64(vdsoAddr) + vdsoSigreturnOffset - vdsoPrelink)\nac.SetIP(uintptr(loaded.entry))\nac.SetStack(uintptr(stack.Bottom))\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/vdso.go",
"new_path": "pkg/sentry/loader/vdso.go",
"diff": "@@ -19,7 +19,6 @@ import (\n\"debug/elf\"\n\"fmt\"\n\"io\"\n- \"strings\"\n\"gvisor.dev/gvisor/pkg/abi\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -177,27 +176,6 @@ type VDSO struct {\nphdrs []elf.ProgHeader `state:\".([]elfProgHeader)\"`\n}\n-// getSymbolValueFromVDSO returns the specific symbol value in vdso.so.\n-func getSymbolValueFromVDSO(symbol string) (uint64, error) {\n- f, err := elf.NewFile(bytes.NewReader(vdsodata.Binary))\n- if err != nil {\n- return 0, err\n- }\n- syms, err := f.Symbols()\n- if err != nil {\n- return 0, err\n- }\n-\n- for _, sym := range syms {\n- if elf.ST_BIND(sym.Info) != elf.STB_LOCAL && sym.Section != elf.SHN_UNDEF {\n- if strings.Contains(sym.Name, symbol) {\n- return sym.Value, nil\n- }\n- }\n- }\n- return 0, fmt.Errorf(\"no %v in vdso.so\", symbol)\n-}\n-\n// PrepareVDSO validates the system VDSO and returns a VDSO, containing the\n// param page for updating by the kernel.\nfunc PrepareVDSO(mfp pgalloc.MemoryFileProvider) (*VDSO, error) {\n@@ -388,3 +366,21 @@ func (v *VDSO) Release(ctx context.Context) {\nv.ParamPage.DecRef(ctx)\nv.vdso.DecRef(ctx)\n}\n+\n+var vdsoSigreturnOffset = func() uint64 {\n+ f, err := elf.NewFile(bytes.NewReader(vdsodata.Binary))\n+ if err != nil {\n+ panic(fmt.Sprintf(\"failed to parse vdso.so as ELF file: %v\", err))\n+ }\n+ syms, err := f.Symbols()\n+ if err != nil {\n+ panic(fmt.Sprintf(\"failed to read symbols from vdso.so: %v\", err))\n+ }\n+ const sigreturnSymbol = \"__kernel_rt_sigreturn\"\n+ for _, sym := range syms {\n+ if elf.ST_BIND(sym.Info) != elf.STB_LOCAL && sym.Section != elf.SHN_UNDEF && sym.Name == sigreturnSymbol {\n+ return sym.Value\n+ }\n+ }\n+ panic(fmt.Sprintf(\"no symbol %q in vdso.so\", sigreturnSymbol))\n+}()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Cache vdso.so's __kernel_rt_sigreturn location.
PiperOrigin-RevId: 394300607 |
259,885 | 01.09.2021 14:04:50 | 25,200 | b4de26d6b1bbb0e75187690da6d3fe120f53656b | Don't use reflection in fpu.alignedBytes.
reflect.ValueOf takes an interface{}, so when passed a slice the compiler emits
a call to runtime.convTslice to heap-allocate a copy of the slice header. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/fpu/BUILD",
"new_path": "pkg/sentry/arch/fpu/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"fpu_amd64.go\",\n\"fpu_amd64.s\",\n\"fpu_arm64.go\",\n+ \"fpu_unsafe.go\",\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/arch/fpu/fpu.go",
"new_path": "pkg/sentry/arch/fpu/fpu.go",
"diff": "@@ -17,7 +17,6 @@ package fpu\nimport (\n\"fmt\"\n- \"reflect\"\n)\n// State represents floating point state.\n@@ -40,15 +39,3 @@ type ErrLoadingState struct {\nfunc (e ErrLoadingState) Error() string {\nreturn fmt.Sprintf(\"floating point state contains unsupported features; supported: %#x saved: %#x\", e.supportedFeatures, e.savedFeatures)\n}\n-\n-// alignedBytes returns a slice of size bytes, aligned in memory to the given\n-// alignment. This is used because we require certain structures to be aligned\n-// in a specific way (for example, the X86 floating point data).\n-func alignedBytes(size, alignment uint) []byte {\n- data := make([]byte, size+alignment-1)\n- offset := uint(reflect.ValueOf(data).Index(0).Addr().Pointer() % uintptr(alignment))\n- if offset == 0 {\n- return data[:size:size]\n- }\n- return data[alignment-offset:][:size:size]\n-}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/arch/fpu/fpu_unsafe.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package fpu\n+\n+import (\n+ \"unsafe\"\n+)\n+\n+// alignedBytes returns a slice of size bytes, aligned in memory to the given\n+// alignment. This is used because we require certain structures to be aligned\n+// in a specific way (for example, the X86 floating point data).\n+func alignedBytes(size, alignment uint) []byte {\n+ data := make([]byte, size+alignment-1)\n+ offset := uint(uintptr(unsafe.Pointer(&data[0])) % uintptr(alignment))\n+ if offset == 0 {\n+ return data[:size:size]\n+ }\n+ return data[alignment-offset:][:size:size]\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't use reflection in fpu.alignedBytes.
reflect.ValueOf takes an interface{}, so when passed a slice the compiler emits
a call to runtime.convTslice to heap-allocate a copy of the slice header.
PiperOrigin-RevId: 394310052 |
260,001 | 01.09.2021 15:48:29 | 25,200 | 5032f4f57d9d46a3dfebb50523907724713e0001 | Add ioctl stub constants | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/ioctl.go",
"new_path": "pkg/abi/linux/ioctl.go",
"diff": "@@ -170,3 +170,18 @@ const (\nKCOV_MODE_TRACE_PC = 2\nKCOV_MODE_TRACE_CMP = 3\n)\n+\n+// Attestation ioctls.\n+var (\n+ SIGN_ATTESTATION_REPORT = IOC(_IOC_READ, 's', 1, 65)\n+)\n+\n+// SizeOfQuoteInputData is the number of bytes in the input data of ioctl call\n+// to get quote.\n+const SizeOfQuoteInputData = 64\n+\n+// SignReport is a struct that gets signed quote from input data.\n+type SignReport struct {\n+ data [64]byte\n+ quote []byte\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add ioctl stub constants
PiperOrigin-RevId: 394331928 |
259,962 | 01.09.2021 17:30:17 | 25,200 | 2d3919532a7531083a5e4db956401ff0e1356a77 | Out-of-order segment should not block in-sequence segments.
For a small receive buffer the first out-of-order segment will get accepted and
fill up the receive buffer today. This change now includes the size of the
out-of-order segment when checking whether to queue the out of order segment or
not. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/rcv.go",
"new_path": "pkg/tcpip/transport/tcp/rcv.go",
"diff": "@@ -477,7 +477,7 @@ func (r *receiver) handleRcvdSegment(s *segment) (drop bool, err tcpip.Error) {\n// segments. This ensures that we always leave some space for the inorder\n// segments to arrive allowing pending segments to be processed and\n// delivered to the user.\n- if rcvBufSize := r.ep.ops.GetReceiveBufferSize(); rcvBufSize > 0 && r.PendingBufUsed < int(rcvBufSize)>>2 {\n+ if rcvBufSize := r.ep.ops.GetReceiveBufferSize(); rcvBufSize > 0 && (r.PendingBufUsed+int(segLen)) < int(rcvBufSize)>>2 {\nr.ep.rcvQueueInfo.rcvQueueMu.Lock()\nr.PendingBufUsed += s.segMemSize()\nr.ep.rcvQueueInfo.rcvQueueMu.Unlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -2128,6 +2128,211 @@ func TestFullWindowReceive(t *testing.T) {\n)\n}\n+func TestSmallReceiveBufferReadiness(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{tcp.NewProtocol},\n+ })\n+\n+ ep := loopback.New()\n+ if testing.Verbose() {\n+ ep = sniffer.New(ep)\n+ }\n+\n+ const nicID = 1\n+ nicOpts := stack.NICOptions{Name: \"nic1\"}\n+ if err := s.CreateNICWithOptions(nicID, ep, nicOpts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %s\", nicOpts, err)\n+ }\n+\n+ addr := tcpip.AddressWithPrefix{\n+ Address: tcpip.Address(\"\\x7f\\x00\\x00\\x01\"),\n+ PrefixLen: 8,\n+ }\n+ if err := s.AddAddressWithPrefix(nicID, ipv4.ProtocolNumber, addr); err != nil {\n+ t.Fatalf(\"AddAddressWithPrefix(_, _, %s) failed: %s\", addr, err)\n+ }\n+\n+ {\n+ subnet, err := tcpip.NewSubnet(\"\\x7f\\x00\\x00\\x00\", \"\\xff\\x00\\x00\\x00\")\n+ if err != nil {\n+ t.Fatalf(\"tcpip.NewSubnet failed: %s\", err)\n+ }\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: subnet,\n+ NIC: nicID,\n+ },\n+ })\n+ }\n+\n+ listenerEntry, listenerCh := waiter.NewChannelEntry(nil)\n+ var listenerWQ waiter.Queue\n+ listener, err := s.NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &listenerWQ)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint failed: %s\", err)\n+ }\n+ defer listener.Close()\n+ listenerWQ.EventRegister(&listenerEntry, waiter.ReadableEvents)\n+ defer listenerWQ.EventUnregister(&listenerEntry)\n+\n+ if err := listener.Bind(tcpip.FullAddress{}); err != nil {\n+ t.Fatalf(\"Bind failed: %s\", err)\n+ }\n+ if err := listener.Listen(1); err != nil {\n+ t.Fatalf(\"Bind failed: %s\", err)\n+ }\n+\n+ localAddress, err := listener.GetLocalAddress()\n+ if err != nil {\n+ t.Fatalf(\"GetLocalAddress failed: %s\", err)\n+ }\n+\n+ for i := 8; i > 0; i /= 2 {\n+ size := int64(i << 10)\n+ t.Run(fmt.Sprintf(\"size=%d\", size), func(t *testing.T) {\n+ var clientWQ waiter.Queue\n+ client, err := s.NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &clientWQ)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint failed: %s\", err)\n+ }\n+ defer client.Close()\n+ switch err := client.Connect(localAddress).(type) {\n+ case nil:\n+ t.Fatal(\"Connect returned nil error\")\n+ case *tcpip.ErrConnectStarted:\n+ default:\n+ t.Fatalf(\"Connect failed: %s\", err)\n+ }\n+\n+ <-listenerCh\n+ server, serverWQ, err := listener.Accept(nil)\n+ if err != nil {\n+ t.Fatalf(\"Accept failed: %s\", err)\n+ }\n+ defer server.Close()\n+\n+ client.SocketOptions().SetReceiveBufferSize(size, true)\n+ // Send buffer size doesn't seem to affect this test.\n+ // server.SocketOptions().SetSendBufferSize(size, true)\n+\n+ clientEntry, clientCh := waiter.NewChannelEntry(nil)\n+ clientWQ.EventRegister(&clientEntry, waiter.ReadableEvents)\n+ defer clientWQ.EventUnregister(&clientEntry)\n+\n+ serverEntry, serverCh := waiter.NewChannelEntry(nil)\n+ serverWQ.EventRegister(&serverEntry, waiter.WritableEvents)\n+ defer serverWQ.EventUnregister(&serverEntry)\n+\n+ var total int64\n+ for {\n+ var b [64 << 10]byte\n+ var r bytes.Reader\n+ r.Reset(b[:])\n+ switch n, err := server.Write(&r, tcpip.WriteOptions{}); err.(type) {\n+ case nil:\n+ t.Logf(\"wrote %d bytes\", n)\n+ total += n\n+ continue\n+ case *tcpip.ErrWouldBlock:\n+ select {\n+ case <-serverCh:\n+ continue\n+ case <-time.After(100 * time.Millisecond):\n+ // Well and truly full.\n+ t.Logf(\"send and receive queues are full\")\n+ }\n+ default:\n+ t.Fatalf(\"Write failed: %s\", err)\n+ }\n+ break\n+ }\n+ t.Logf(\"wrote %d bytes in total\", total)\n+\n+ var wg sync.WaitGroup\n+ defer wg.Wait()\n+\n+ wg.Add(2)\n+ go func() {\n+ defer wg.Done()\n+\n+ var b [64 << 10]byte\n+ var r bytes.Reader\n+ r.Reset(b[:])\n+ if err := func() error {\n+ var total int64\n+ defer t.Logf(\"wrote %d bytes in total\", total)\n+ for r.Len() != 0 {\n+ switch n, err := server.Write(&r, tcpip.WriteOptions{}); err.(type) {\n+ case nil:\n+ t.Logf(\"wrote %d bytes\", n)\n+ total += n\n+ case *tcpip.ErrWouldBlock:\n+ for {\n+ t.Logf(\"waiting on server\")\n+ select {\n+ case <-serverCh:\n+ case <-time.After(time.Second):\n+ if readiness := server.Readiness(waiter.WritableEvents); readiness != 0 {\n+ t.Logf(\"server.Readiness(%b) = %b but channel not signaled\", waiter.WritableEvents, readiness)\n+ }\n+ continue\n+ }\n+ break\n+ }\n+ default:\n+ return fmt.Errorf(\"server.Write failed: %s\", err)\n+ }\n+ }\n+ if err := server.Shutdown(tcpip.ShutdownWrite); err != nil {\n+ return fmt.Errorf(\"server.Shutdown failed: %s\", err)\n+ }\n+ t.Logf(\"server end shutdown done\")\n+ return nil\n+ }(); err != nil {\n+ t.Error(err)\n+ }\n+ }()\n+\n+ go func() {\n+ defer wg.Done()\n+\n+ if err := func() error {\n+ total := 0\n+ defer t.Logf(\"read %d bytes in total\", total)\n+ for {\n+ switch res, err := client.Read(ioutil.Discard, tcpip.ReadOptions{}); err.(type) {\n+ case nil:\n+ t.Logf(\"read %d bytes\", res.Count)\n+ total += res.Count\n+ t.Logf(\"read total %d bytes till now\", total)\n+ case *tcpip.ErrClosedForReceive:\n+ return nil\n+ case *tcpip.ErrWouldBlock:\n+ for {\n+ t.Logf(\"waiting on client\")\n+ select {\n+ case <-clientCh:\n+ case <-time.After(time.Second):\n+ if readiness := client.Readiness(waiter.ReadableEvents); readiness != 0 {\n+ return fmt.Errorf(\"client.Readiness(%b) = %b but channel not signaled\", waiter.ReadableEvents, readiness)\n+ }\n+ continue\n+ }\n+ break\n+ }\n+ default:\n+ return fmt.Errorf(\"client.Write failed: %s\", err)\n+ }\n+ }\n+ }(); err != nil {\n+ t.Error(err)\n+ }\n+ }()\n+ })\n+ }\n+}\n+\n// Test the stack receive window advertisement on receiving segments smaller than\n// segment overhead. It tests for the right edge of the window to not grow when\n// the endpoint is not being read from.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Out-of-order segment should not block in-sequence segments.
For a small receive buffer the first out-of-order segment will get accepted and
fill up the receive buffer today. This change now includes the size of the
out-of-order segment when checking whether to queue the out of order segment or
not.
PiperOrigin-RevId: 394351309 |
259,951 | 07.09.2021 14:05:54 | 25,200 | dfc518005bf9fd6abdc8dc906d7572f6cc2c5a35 | Remove protocolMainLoop unused return value | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -1342,7 +1342,7 @@ func (e *endpoint) protocolMainLoopDone(closeTimer tcpip.Timer) {\n// protocolMainLoop is the main loop of the TCP protocol. It runs in its own\n// goroutine and is responsible for sending segments and handling received\n// segments.\n-func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{}) tcpip.Error {\n+func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{}) {\nvar (\ncloseTimer tcpip.Timer\ncloseWaker sleep.Waker\n@@ -1360,7 +1360,7 @@ func (e *endpoint) protocolMainLoop(handshake bool, wakerInitDone chan<- struct{\ne.workerCleanup = true\ne.protocolMainLoopDone(closeTimer)\n- return err\n+ return\n}\n}\n@@ -1588,7 +1588,7 @@ loop:\n// endpoint.\ncleanupOnError(nil)\ne.protocolMainLoopDone(closeTimer)\n- return nil\n+ return\ncase StateTimeWait:\nfallthrough\ncase StateClose:\n@@ -1597,7 +1597,7 @@ loop:\nif err := funcs[v].f(); err != nil {\ncleanupOnError(err)\ne.protocolMainLoopDone(closeTimer)\n- return nil\n+ return\n}\n}\n}\n@@ -1621,7 +1621,7 @@ loop:\nif e.EndpointState() == StateError {\ncleanupOnError(nil)\ne.protocolMainLoopDone(closeTimer)\n- return nil\n+ return\n}\ne.transitionToStateCloseLocked()\n@@ -1633,8 +1633,6 @@ loop:\nif reuseTW != nil {\nreuseTW()\n}\n-\n- return nil\n}\n// handleTimeWaitSegments processes segments received during TIME_WAIT\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove protocolMainLoop unused return value
PiperOrigin-RevId: 395325998 |
259,902 | 07.09.2021 14:56:27 | 25,200 | 2f2fb3813f59922156258b816ea50d49a70d617c | Conditionally use GetAbsoluteTestTmpdir() rather than hard-code "/tmp"
NewTempAbsPathInDir("/tmp") prevents the generated socket address from
exceeding sizeof(addr.sun_path). However, existing systems that are built with
the ANDROID configuration have their temp directory in a different location.
This change allows those systems to run tests that depend on UniqueUnixAddr. | [
{
"change_type": "MODIFY",
"old_path": "test/util/socket_util.cc",
"new_path": "test/util/socket_util.cc",
"diff": "@@ -57,7 +57,19 @@ Creator<FileDescriptor> SyscallSocketCreator(int domain, int type,\nPosixErrorOr<struct sockaddr_un> UniqueUnixAddr(bool abstract, int domain) {\nstruct sockaddr_un addr = {};\n+\n+#ifdef ANDROID\n+ // Using NewTempAbsPath() can cause the tmp directory path to exceed the max\n+ // length (i.e., sizeof(addr.sun_path)).\n+ //\n+ // However, existing systems that are built with the ANDROID configuration\n+ // have their temp directory in a different location, and must respect the\n+ // TEST_TMPDIR.\n+ std::string path = NewTempAbsPath();\n+#else\nstd::string path = NewTempAbsPathInDir(\"/tmp\");\n+#endif // ANDROID\n+\nif (path.size() >= sizeof(addr.sun_path)) {\nreturn PosixError(EINVAL,\n\"Unable to generate a temp path of appropriate length\");\n"
}
] | Go | Apache License 2.0 | google/gvisor | Conditionally use GetAbsoluteTestTmpdir() rather than hard-code "/tmp"
NewTempAbsPathInDir("/tmp") prevents the generated socket address from
exceeding sizeof(addr.sun_path). However, existing systems that are built with
the ANDROID configuration have their temp directory in a different location.
This change allows those systems to run tests that depend on UniqueUnixAddr.
PiperOrigin-RevId: 395336483 |
259,985 | 07.09.2021 15:06:55 | 25,200 | e90ecdb48885bcabd0d7b00ff01621e7f92e3614 | Stub some memory control files. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/cgroupfs/memory.go",
"new_path": "pkg/sentry/fsimpl/cgroupfs/memory.go",
"diff": "@@ -32,21 +32,33 @@ type memoryController struct {\ncontrollerCommon\nlimitBytes int64\n+ softLimitBytes int64\n+ moveChargeAtImmigrate int64\n}\nvar _ controller = (*memoryController)(nil)\nfunc newMemoryController(fs *filesystem, defaults map[string]int64) *memoryController {\nc := &memoryController{\n- // Linux sets this to (PAGE_COUNTER_MAX * PAGE_SIZE) by default, which\n- // is ~ 2**63 on a 64-bit system. So essentially, inifinity. The exact\n- // value isn't very important.\n+ // Linux sets these limits to (PAGE_COUNTER_MAX * PAGE_SIZE) by default,\n+ // which is ~ 2**63 on a 64-bit system. So essentially, inifinity. The\n+ // exact value isn't very important.\n+\nlimitBytes: math.MaxInt64,\n+ softLimitBytes: math.MaxInt64,\n+ }\n+\n+ consumeDefault := func(name string, valPtr *int64) {\n+ if val, ok := defaults[name]; ok {\n+ *valPtr = val\n+ delete(defaults, name)\n}\n- if val, ok := defaults[\"memory.limit_in_bytes\"]; ok {\n- c.limitBytes = val\n- delete(defaults, \"memory.limit_in_bytes\")\n}\n+\n+ consumeDefault(\"memory.limit_in_bytes\", &c.limitBytes)\n+ consumeDefault(\"memory.soft_limit_in_bytes\", &c.softLimitBytes)\n+ consumeDefault(\"memory.move_charge_at_immigrate\", &c.moveChargeAtImmigrate)\n+\nc.controllerCommon.init(controllerMemory, fs)\nreturn c\n}\n@@ -55,6 +67,8 @@ func newMemoryController(fs *filesystem, defaults map[string]int64) *memoryContr\nfunc (c *memoryController) AddControlFiles(ctx context.Context, creds *auth.Credentials, _ *cgroupInode, contents map[string]kernfs.Inode) {\ncontents[\"memory.usage_in_bytes\"] = c.fs.newControllerFile(ctx, creds, &memoryUsageInBytesData{})\ncontents[\"memory.limit_in_bytes\"] = c.fs.newStaticControllerFile(ctx, creds, linux.FileMode(0644), fmt.Sprintf(\"%d\\n\", c.limitBytes))\n+ contents[\"memory.soft_limit_in_bytes\"] = c.fs.newStaticControllerFile(ctx, creds, linux.FileMode(0644), fmt.Sprintf(\"%d\\n\", c.softLimitBytes))\n+ contents[\"memory.move_charge_at_immigrate\"] = c.fs.newStaticControllerFile(ctx, creds, linux.FileMode(0644), fmt.Sprintf(\"%d\\n\", c.moveChargeAtImmigrate))\n}\n// +stateify savable\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub some memory control files.
PiperOrigin-RevId: 395338926 |
259,962 | 09.09.2021 11:01:29 | 25,200 | 5e9c3a0b934f0dd7513e21372b3fd8593b87525b | Add EthernetHeader only if underlying NIC has a mac address.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/network.go",
"new_path": "runsc/boot/network.go",
"diff": "@@ -210,7 +210,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nlinkEP, err := fdbased.New(&fdbased.Options{\nFDs: FDs,\nMTU: uint32(link.MTU),\n- EthernetHeader: true,\n+ EthernetHeader: mac != \"\",\nAddress: mac,\nPacketDispatchMode: fdbased.RecvMMsg,\nGSOMaxSize: link.GSOMaxSize,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add EthernetHeader only if underlying NIC has a mac address.
Fixes #6532
PiperOrigin-RevId: 395741741 |
259,985 | 09.09.2021 22:54:51 | 25,200 | 7da9bb18c28bdd874e928d85363e1f99cea03b2c | Use accessor for runsc ControlConfig proto. | [
{
"change_type": "MODIFY",
"old_path": "runsc/config/config.go",
"new_path": "runsc/config/config.go",
"diff": "@@ -404,7 +404,7 @@ func (c *controlConfig) Get() interface{} {\n// String implements flag.Value.\nfunc (c *controlConfig) String() string {\nv := \"\"\n- for _, control := range c.Controls.AllowedControls {\n+ for _, control := range c.Controls.GetAllowedControls() {\nif len(v) > 0 {\nv += \",\"\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use accessor for runsc ControlConfig proto.
PiperOrigin-RevId: 395859347 |
259,858 | 13.09.2021 10:51:23 | 25,200 | 6bcacb2fd17fadefbc9fb2eed9059eb36ae2783b | Support anonymous structs in checklocks.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -41,17 +41,6 @@ func (l *linkResolver) confirmReachable(addr tcpip.Address) {\nvar _ NetworkInterface = (*nic)(nil)\n-// TODO(https://gvisor.dev/issue/6558): Use an anonymous struct in nic for this\n-// once copylocks supports anonymous structs.\n-type packetEPs struct {\n- mu sync.RWMutex\n-\n- // eps is protected by the mutex, but the values contained in it are not.\n- //\n- // +checklocks:mu\n- eps map[tcpip.NetworkProtocolNumber]*packetEndpointList\n-}\n-\n// nic represents a \"network interface card\" to which the networking stack is\n// attached.\ntype nic struct {\n@@ -85,7 +74,14 @@ type nic struct {\npromiscuous bool\n}\n- packetEPs packetEPs\n+ packetEPs struct {\n+ mu sync.RWMutex\n+\n+ // eps is protected by the mutex, but the values contained in it are not.\n+ //\n+ // +checklocks:mu\n+ eps map[tcpip.NetworkProtocolNumber]*packetEndpointList\n+ }\n}\n// makeNICStats initializes the NIC statistics and associates them to the global\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/checklocks.go",
"new_path": "tools/checklocks/checklocks.go",
"diff": "@@ -90,12 +90,14 @@ func run(pass *analysis.Pass) (interface{}, error) {\n// Find all struct declarations and export relevant facts.\npc.forAllTypes(func(ts *ast.TypeSpec) {\nif ss, ok := ts.Type.(*ast.StructType); ok {\n- pc.exportLockFieldFacts(ts, ss)\n+ structType := pc.pass.TypesInfo.TypeOf(ts.Name).Underlying().(*types.Struct)\n+ pc.exportLockFieldFacts(structType, ss)\n}\n})\npc.forAllTypes(func(ts *ast.TypeSpec) {\nif ss, ok := ts.Type.(*ast.StructType); ok {\n- pc.exportLockGuardFacts(ts, ss)\n+ structType := pc.pass.TypesInfo.TypeOf(ts.Name).Underlying().(*types.Struct)\n+ pc.exportLockGuardFacts(structType, ss)\n}\n})\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/facts.go",
"new_path": "tools/checklocks/facts.go",
"diff": "@@ -399,13 +399,12 @@ var (\n)\n// exportLockFieldFacts finds all struct fields that are mutexes, and ensures\n-// that they are annotated approperly.\n+// that they are annotated properly.\n//\n// This information is consumed subsequently by exportLockGuardFacts, and this\n// function must be called first on all structures.\n-func (pc *passContext) exportLockFieldFacts(ts *ast.TypeSpec, ss *ast.StructType) {\n- structType := pc.pass.TypesInfo.TypeOf(ts.Name).Underlying().(*types.Struct)\n- for i := range ss.Fields.List {\n+func (pc *passContext) exportLockFieldFacts(structType *types.Struct, ss *ast.StructType) {\n+ for i, field := range ss.Fields.List {\nlff := &lockFieldFacts{\nFieldNumber: i,\n}\n@@ -426,6 +425,13 @@ func (pc *passContext) exportLockFieldFacts(ts *ast.TypeSpec, ss *ast.StructType\n// We must always export the lockFieldFacts, since traversal\n// can take place along any object in the struct.\npc.pass.ExportObjectFact(fieldObj, lff)\n+ // If this is an anonymous type, then we won't discover it via\n+ // the AST global declarations. We can recurse from here.\n+ if ss, ok := field.Type.(*ast.StructType); ok {\n+ if st, ok := fieldObj.Type().(*types.Struct); ok {\n+ pc.exportLockFieldFacts(st, ss)\n+ }\n+ }\n}\n}\n@@ -433,18 +439,15 @@ func (pc *passContext) exportLockFieldFacts(ts *ast.TypeSpec, ss *ast.StructType\n//\n// This function requires exportLockFieldFacts be called first on all\n// structures.\n-func (pc *passContext) exportLockGuardFacts(ts *ast.TypeSpec, ss *ast.StructType) {\n- structType := pc.pass.TypesInfo.TypeOf(ts.Name).Underlying().(*types.Struct)\n+func (pc *passContext) exportLockGuardFacts(structType *types.Struct, ss *ast.StructType) {\nfor i, field := range ss.Fields.List {\n- if field.Doc == nil {\n- continue\n- }\n+ fieldObj := structType.Field(i)\n+ if field.Doc != nil {\nvar (\nlff lockFieldFacts\nlgf lockGuardFacts\n)\npc.pass.ImportObjectFact(structType.Field(i), &lff)\n- fieldObj := structType.Field(i)\nfor _, l := range field.Doc.List {\npc.extractAnnotations(l.Text, map[string]func(string){\ncheckAtomicAnnotation: func(string) {\n@@ -488,6 +491,13 @@ func (pc *passContext) exportLockGuardFacts(ts *ast.TypeSpec, ss *ast.StructType\npc.pass.ExportObjectFact(structType.Field(i), &lgf)\n}\n}\n+ // See above, for anonymous structure fields.\n+ if ss, ok := field.Type.(*ast.StructType); ok {\n+ if st, ok := fieldObj.Type().(*types.Struct); ok {\n+ pc.exportLockGuardFacts(st, ss)\n+ }\n+ }\n+ }\n}\n// countFields gives an accurate field count, according for unnamed arguments\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/checklocks/test/BUILD",
"new_path": "tools/checklocks/test/BUILD",
"diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"test\",\nsrcs = [\n\"alignment.go\",\n+ \"anon.go\",\n\"atomics.go\",\n\"basics.go\",\n\"branches.go\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/checklocks/test/anon.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package test\n+\n+import \"sync\"\n+\n+type anonStruct struct {\n+ anon struct {\n+ mu sync.RWMutex\n+ // +checklocks:mu\n+ x int\n+ }\n+}\n+\n+func testAnonAccessValid(tc *anonStruct) {\n+ tc.anon.mu.Lock()\n+ tc.anon.x = 1\n+ tc.anon.mu.Unlock()\n+}\n+\n+func testAnonAccessInvalid(tc *anonStruct) {\n+ tc.anon.x = 1 // +checklocksfail\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support anonymous structs in checklocks.
Fixes #6558
PiperOrigin-RevId: 396393293 |
259,881 | 13.09.2021 16:01:07 | 14,400 | 9bdeddd8826f98251584567b4157c63b297b7825 | runsc/cmd: alphabetize runsc debug profiling options
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/debug.go",
"new_path": "runsc/cmd/debug.go",
"diff": "@@ -37,9 +37,9 @@ type Debug struct {\npid int\nstacks bool\nsignal int\n- profileHeap string\n- profileCPU string\nprofileBlock string\n+ profileCPU string\n+ profileHeap string\nprofileMutex string\ntrace string\nstrace string\n@@ -70,9 +70,9 @@ func (*Debug) Usage() string {\nfunc (d *Debug) SetFlags(f *flag.FlagSet) {\nf.IntVar(&d.pid, \"pid\", 0, \"sandbox process ID. Container ID is not necessary if this is set\")\nf.BoolVar(&d.stacks, \"stacks\", false, \"if true, dumps all sandbox stacks to the log\")\n- f.StringVar(&d.profileHeap, \"profile-heap\", \"\", \"writes heap profile to the given file.\")\n- f.StringVar(&d.profileCPU, \"profile-cpu\", \"\", \"writes CPU profile to the given file.\")\nf.StringVar(&d.profileBlock, \"profile-block\", \"\", \"writes block profile to the given file.\")\n+ f.StringVar(&d.profileCPU, \"profile-cpu\", \"\", \"writes CPU profile to the given file.\")\n+ f.StringVar(&d.profileHeap, \"profile-heap\", \"\", \"writes heap profile to the given file.\")\nf.StringVar(&d.profileMutex, \"profile-mutex\", \"\", \"writes mutex profile to the given file.\")\nf.DurationVar(&d.delay, \"delay\", time.Hour, \"amount of time to delay for collecting heap and goroutine profiles.\")\nf.DurationVar(&d.duration, \"duration\", time.Hour, \"amount of time to wait for CPU and trace profiles.\")\n@@ -219,19 +219,19 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Open profiling files.\nvar (\n- heapFile *os.File\n- cpuFile *os.File\n- traceFile *os.File\nblockFile *os.File\n+ cpuFile *os.File\n+ heapFile *os.File\nmutexFile *os.File\n+ traceFile *os.File\n)\n- if d.profileHeap != \"\" {\n- f, err := os.OpenFile(d.profileHeap, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n+ if d.profileBlock != \"\" {\n+ f, err := os.OpenFile(d.profileBlock, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\nif err != nil {\n- return Errorf(\"error opening heap profile output: %v\", err)\n+ return Errorf(\"error opening blocking profile output: %v\", err)\n}\ndefer f.Close()\n- heapFile = f\n+ blockFile = f\n}\nif d.profileCPU != \"\" {\nf, err := os.OpenFile(d.profileCPU, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n@@ -241,20 +241,13 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ndefer f.Close()\ncpuFile = f\n}\n- if d.trace != \"\" {\n- f, err := os.OpenFile(d.trace, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n- if err != nil {\n- return Errorf(\"error opening trace profile output: %v\", err)\n- }\n- traceFile = f\n- }\n- if d.profileBlock != \"\" {\n- f, err := os.OpenFile(d.profileBlock, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n+ if d.profileHeap != \"\" {\n+ f, err := os.OpenFile(d.profileHeap, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\nif err != nil {\n- return Errorf(\"error opening blocking profile output: %v\", err)\n+ return Errorf(\"error opening heap profile output: %v\", err)\n}\ndefer f.Close()\n- blockFile = f\n+ heapFile = f\n}\nif d.profileMutex != \"\" {\nf, err := os.OpenFile(d.profileMutex, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n@@ -264,21 +257,28 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ndefer f.Close()\nmutexFile = f\n}\n+ if d.trace != \"\" {\n+ f, err := os.OpenFile(d.trace, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)\n+ if err != nil {\n+ return Errorf(\"error opening trace profile output: %v\", err)\n+ }\n+ traceFile = f\n+ }\n// Collect profiles.\nvar (\nwg sync.WaitGroup\n- heapErr error\n- cpuErr error\n- traceErr error\nblockErr error\n+ cpuErr error\n+ heapErr error\nmutexErr error\n+ traceErr error\n)\n- if heapFile != nil {\n+ if blockFile != nil {\nwg.Add(1)\ngo func() {\ndefer wg.Done()\n- heapErr = c.Sandbox.HeapProfile(heapFile, d.delay)\n+ blockErr = c.Sandbox.BlockProfile(blockFile, d.duration)\n}()\n}\nif cpuFile != nil {\n@@ -288,25 +288,25 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ncpuErr = c.Sandbox.CPUProfile(cpuFile, d.duration)\n}()\n}\n- if traceFile != nil {\n+ if heapFile != nil {\nwg.Add(1)\ngo func() {\ndefer wg.Done()\n- traceErr = c.Sandbox.Trace(traceFile, d.duration)\n+ heapErr = c.Sandbox.HeapProfile(heapFile, d.delay)\n}()\n}\n- if blockFile != nil {\n+ if mutexFile != nil {\nwg.Add(1)\ngo func() {\ndefer wg.Done()\n- blockErr = c.Sandbox.BlockProfile(blockFile, d.duration)\n+ mutexErr = c.Sandbox.MutexProfile(mutexFile, d.duration)\n}()\n}\n- if mutexFile != nil {\n+ if traceFile != nil {\nwg.Add(1)\ngo func() {\ndefer wg.Done()\n- mutexErr = c.Sandbox.MutexProfile(mutexFile, d.duration)\n+ traceErr = c.Sandbox.Trace(traceFile, d.duration)\n}()\n}\n@@ -339,31 +339,31 @@ func (d *Debug) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n// Collect all errors.\nerrorCount := 0\n- if heapErr != nil {\n+ if blockErr != nil {\nerrorCount++\n- log.Infof(\"error collecting heap profile: %v\", heapErr)\n- os.Remove(heapFile.Name())\n+ log.Infof(\"error collecting block profile: %v\", blockErr)\n+ os.Remove(blockFile.Name())\n}\nif cpuErr != nil {\nerrorCount++\nlog.Infof(\"error collecting cpu profile: %v\", cpuErr)\nos.Remove(cpuFile.Name())\n}\n- if traceErr != nil {\n- errorCount++\n- log.Infof(\"error collecting trace profile: %v\", traceErr)\n- os.Remove(traceFile.Name())\n- }\n- if blockErr != nil {\n+ if heapErr != nil {\nerrorCount++\n- log.Infof(\"error collecting block profile: %v\", blockErr)\n- os.Remove(blockFile.Name())\n+ log.Infof(\"error collecting heap profile: %v\", heapErr)\n+ os.Remove(heapFile.Name())\n}\nif mutexErr != nil {\nerrorCount++\nlog.Infof(\"error collecting mutex profile: %v\", mutexErr)\nos.Remove(mutexFile.Name())\n}\n+ if traceErr != nil {\n+ errorCount++\n+ log.Infof(\"error collecting trace profile: %v\", traceErr)\n+ os.Remove(traceFile.Name())\n+ }\nif errorCount > 0 {\nreturn subcommands.ExitFailure\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc/cmd: alphabetize runsc debug profiling options
Updates #220 |
260,004 | 13.09.2021 14:40:18 | 25,200 | e07fd058ec474d801748a849d9c5d1c6118c3c11 | Set NICID before delivering packet to raw endpoint
...as raw endpoints expect the packet's NICID to be set. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/BUILD",
"new_path": "pkg/tcpip/network/BUILD",
"diff": "@@ -23,8 +23,10 @@ go_test(\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/testutil\",\n\"//pkg/tcpip/transport/icmp\",\n+ \"//pkg/tcpip/transport/raw\",\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/ip_test.go",
"new_path": "pkg/tcpip/network/ip_test.go",
"diff": "package ip_test\nimport (\n+ \"bytes\"\n\"fmt\"\n\"strings\"\n\"testing\"\n@@ -32,8 +33,10 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/raw\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n)\nconst nicID = 1\n@@ -2032,3 +2035,93 @@ func TestJoinLeaveAllRoutersGroup(t *testing.T) {\n})\n}\n}\n+\n+func TestSetNICIDBeforeDeliveringToRawEndpoint(t *testing.T) {\n+ const nicID = 1\n+\n+ tests := []struct {\n+ name string\n+ proto tcpip.NetworkProtocolNumber\n+ addr tcpip.AddressWithPrefix\n+ payloadOffset int\n+ }{\n+ {\n+ name: \"IPv4\",\n+ proto: header.IPv4ProtocolNumber,\n+ addr: localIPv4AddrWithPrefix,\n+ payloadOffset: header.IPv4MinimumSize,\n+ },\n+ {\n+ name: \"IPv6\",\n+ proto: header.IPv6ProtocolNumber,\n+ addr: localIPv6AddrWithPrefix,\n+ payloadOffset: 0,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{\n+ ipv4.NewProtocol,\n+ ipv6.NewProtocol,\n+ },\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},\n+ RawFactory: raw.EndpointFactory{},\n+ })\n+ if err := s.CreateNIC(nicID, loopback.New()); err != nil {\n+ t.Fatalf(\"CreateNIC(%d, _): %s\", nicID, err)\n+ }\n+ if err := s.AddAddressWithPrefix(nicID, test.proto, test.addr); err != nil {\n+ t.Fatalf(\"AddAddressWithPrefix(%d, %d, %s): %s\", nicID, test.proto, test.addr, err)\n+ }\n+\n+ s.SetRouteTable([]tcpip.Route{\n+ {\n+ Destination: test.addr.Subnet(),\n+ NIC: nicID,\n+ },\n+ })\n+\n+ var wq waiter.Queue\n+ we, ch := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.ReadableEvents)\n+ ep, err := s.NewRawEndpoint(udp.ProtocolNumber, test.proto, &wq, true /* associated */)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(%d, %d, _): %s\", udp.ProtocolNumber, test.proto, err)\n+ }\n+ defer ep.Close()\n+\n+ writeOpts := tcpip.WriteOptions{\n+ To: &tcpip.FullAddress{\n+ Addr: test.addr.Address,\n+ },\n+ }\n+ data := []byte{1, 2, 3, 4}\n+ var r bytes.Reader\n+ r.Reset(data)\n+ if n, err := ep.Write(&r, writeOpts); err != nil {\n+ t.Fatalf(\"ep.Write(_, _): %s\", err)\n+ } else if want := int64(len(data)); n != want {\n+ t.Fatalf(\"got ep.Write(_, _) = (%d, nil), want = (%d, nil)\", n, want)\n+ }\n+\n+ // Wait for the endpoint to become readable.\n+ <-ch\n+\n+ var w bytes.Buffer\n+ rr, err := ep.Read(&w, tcpip.ReadOptions{\n+ NeedRemoteAddr: true,\n+ })\n+ if err != nil {\n+ t.Fatalf(\"ep.Read(...): %s\", err)\n+ }\n+ if diff := cmp.Diff(data, w.Bytes()[test.payloadOffset:]); diff != \"\" {\n+ t.Errorf(\"payload mismatch (-want +got):\\n%s\", diff)\n+ }\n+ if diff := cmp.Diff(tcpip.FullAddress{Addr: test.addr.Address, NIC: nicID}, rr.RemoteAddr); diff != \"\" {\n+ t.Errorf(\"remote addr mismatch (-want +got):\\n%s\", diff)\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -856,6 +856,8 @@ func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum\n}\nfunc (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer, inNICName string) {\n+ pkt.NICID = e.nic.ID()\n+\n// Raw socket packets are delivered based solely on the transport protocol\n// number. We only require that the packet be valid IPv4, and that they not\n// be fragmented.\n@@ -863,7 +865,6 @@ func (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer,\ne.dispatcher.DeliverRawPacket(h.TransportProtocol(), pkt)\n}\n- pkt.NICID = e.nic.ID()\nstats := e.stats\nstats.ip.ValidPacketsReceived.Increment()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -1127,11 +1127,12 @@ func (e *endpoint) handleLocalPacket(pkt *stack.PacketBuffer, canSkipRXChecksum\n}\nfunc (e *endpoint) handleValidatedPacket(h header.IPv6, pkt *stack.PacketBuffer, inNICName string) {\n+ pkt.NICID = e.nic.ID()\n+\n// Raw socket packets are delivered based solely on the transport protocol\n// number. We only require that the packet be valid IPv6.\ne.dispatcher.DeliverRawPacket(h.TransportProtocol(), pkt)\n- pkt.NICID = e.nic.ID()\nstats := e.stats.ip\nstats.ValidPacketsReceived.Increment()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Set NICID before delivering packet to raw endpoint
...as raw endpoints expect the packet's NICID to be set.
PiperOrigin-RevId: 396446552 |
259,853 | 13.09.2021 15:31:52 | 25,200 | 95fe4fea19f30281a3ff53f62c9fcda533c4e04a | tools/show_paths.bzl: check that provider_map isn't None
Otherwise it can fail:
$ bazel cquery pkg/p9/... --output=starlark --starlark:file=tools/show_paths.bzl
...
ERROR: Starlark evaluation error for //pkg/p9/p9test:mockgen:
Traceback (most recent call last):
File "tools/show_paths.bzl", line 8, column 32, in format
Error: 'NoneType' value has no field or method 'get' | [
{
"change_type": "MODIFY",
"old_path": ".buildkite/pipeline.yaml",
"new_path": ".buildkite/pipeline.yaml",
"diff": "@@ -169,6 +169,11 @@ steps:\nlabel: \":mechanical_arm: ARM\"\ncommand: make arm-qemu-smoke-test\n+ # Build everything.\n+ - <<: *common\n+ label: \":world_map: Build everything\"\n+ command: \"make build OPTIONS=--build_tag_filters=-nogo TARGETS=//...\"\n+\n# Run basic benchmarks smoke tests (no upload).\n- <<: *common\nlabel: \":fire: Benchmarks smoke test\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/BUILD",
"new_path": "test/util/BUILD",
"diff": "@@ -352,7 +352,6 @@ cc_library(\ncc_library(\nname = \"benchmark_main\",\ntestonly = 1,\n- srcs = [\"benchmark_main.cc\"],\nlinkstatic = 1,\ndeps = [\n\":test_util\",\n"
},
{
"change_type": "DELETE",
"old_path": "test/util/benchmark_main.cc",
"new_path": null,
"diff": "-// Copyright 2018 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-#include \"gtest/gtest.h\"\n-#include \"absl/flags/flag.h\"\n-#include \"third_party/benchmark/src/commandlineflags.h\"\n-#include \"test/util/test_util.h\"\n-\n-DECLARE_bool(benchmark_list_internal);\n-DECLARE_string(benchmark_filter_internal);\n-ABSL_FLAG(bool, benchmark_enable_random_interleaving_internal, false,\n- \"forward\");\n-ABSL_FLAG(double, benchmark_min_time_internal, -1.0, \"forward\");\n-ABSL_FLAG(int, benchmark_repetitions_internal, 1, \"forward\");\n-\n-// From //third_party/benchmark.\n-//\n-// These conflict with the internal definitions, but all the benchmark binaries\n-// link against the external benchmark library for compatibility with the open\n-// source build. We massage the internal-only flags into the external ones, and\n-// call the function to actually run all registered external benchmarks.\n-namespace benchmark {\n-BM_DECLARE_bool(benchmark_list_tests);\n-BM_DECLARE_string(benchmark_filter);\n-BM_DECLARE_int32(benchmark_repetitions);\n-BM_DECLARE_double(benchmark_min_time);\n-BM_DECLARE_bool(benchmark_enable_random_interleaving);\n-extern size_t RunSpecifiedBenchmarks();\n-} // namespace benchmark\n-\n-using benchmark::FLAGS_benchmark_enable_random_interleaving;\n-using benchmark::FLAGS_benchmark_filter;\n-using benchmark::FLAGS_benchmark_list_tests;\n-using benchmark::FLAGS_benchmark_min_time;\n-using benchmark::FLAGS_benchmark_repetitions;\n-\n-int main(int argc, char** argv) {\n- gvisor::testing::TestInit(&argc, &argv);\n- absl::SetFlag(&FLAGS_benchmark_list_tests,\n- absl::GetFlag(FLAGS_benchmark_list_internal));\n- absl::SetFlag(&FLAGS_benchmark_filter,\n- absl::GetFlag(FLAGS_benchmark_filter_internal));\n- absl::SetFlag(&FLAGS_benchmark_repetitions,\n- absl::GetFlag(FLAGS_benchmark_repetitions_internal));\n- absl::SetFlag(\n- &FLAGS_benchmark_enable_random_interleaving,\n- absl::GetFlag(FLAGS_benchmark_enable_random_interleaving_internal));\n- absl::SetFlag(&FLAGS_benchmark_min_time,\n- absl::GetFlag(FLAGS_benchmark_min_time_internal));\n-\n- benchmark::RunSpecifiedBenchmarks();\n- return 0;\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/bazel.mk",
"new_path": "tools/bazel.mk",
"diff": "@@ -186,8 +186,8 @@ build_paths = \\\n(set -euo pipefail; \\\n$(call wrapper,$(BAZEL) build $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1)) && \\\n$(call wrapper,$(BAZEL) cquery $(BASE_OPTIONS) $(BAZEL_OPTIONS) $(1) --output=starlark --starlark:file=tools/show_paths.bzl) \\\n- | xargs -r -n 1 -I {} readlink -f \"{}\" \\\n- | xargs -r -n 1 -I {} bash -c 'set -xeuo pipefail; $(2)')\n+ | xargs -r -n 1 -I {} bash -c 'test -e \"{}\" || exit 0; readlink -f \"{}\"' \\\n+ | xargs -r -n 1 -I {} bash -c 'set -euo pipefail; $(2)')\nclean = $(call header,CLEAN) && $(call wrapper,$(BAZEL) clean)\nbuild = $(call header,BUILD $(1)) && $(call build_paths,$(1),echo {})\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/show_paths.bzl",
"new_path": "tools/show_paths.bzl",
"diff": "def format(target):\nprovider_map = providers(target)\n+ if not provider_map:\n+ return \"\"\noutputs = dict()\n# Try to resolve in order.\n"
}
] | Go | Apache License 2.0 | google/gvisor | tools/show_paths.bzl: check that provider_map isn't None
Otherwise it can fail:
$ bazel cquery pkg/p9/... --output=starlark --starlark:file=tools/show_paths.bzl
...
ERROR: Starlark evaluation error for //pkg/p9/p9test:mockgen:
Traceback (most recent call last):
File "tools/show_paths.bzl", line 8, column 32, in format
Error: 'NoneType' value has no field or method 'get'
PiperOrigin-RevId: 396457764 |
260,004 | 13.09.2021 19:40:40 | 25,200 | 226e7d32cb855e69b3bf7a28791a17235074e49a | Accept packets destined to bound address
...if bound to an address.
We previously checked the source of a packet instead of the destination
of a packet when bound to an address. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -562,8 +562,6 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n- remoteAddr := pkt.Network().SourceAddress()\n-\nif e.bound {\n// If bound to a NIC, only accept data for that NIC.\nif e.BindNICID != 0 && e.BindNICID != pkt.NICID {\n@@ -572,16 +570,17 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\nreturn\n}\n// If bound to an address, only accept data for that address.\n- if e.BindAddr != \"\" && e.BindAddr != remoteAddr {\n+ if e.BindAddr != \"\" && e.BindAddr != pkt.Network().DestinationAddress() {\ne.rcvMu.Unlock()\ne.mu.RUnlock()\nreturn\n}\n}\n+ srcAddr := pkt.Network().SourceAddress()\n// If connected, only accept packets from the remote address we\n// connected to.\n- if e.connected && e.route.RemoteAddress() != remoteAddr {\n+ if e.connected && e.route.RemoteAddress() != srcAddr {\ne.rcvMu.Unlock()\ne.mu.RUnlock()\nreturn\n@@ -593,7 +592,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\npacket := &rawPacket{\nsenderAddr: tcpip.FullAddress{\nNIC: pkt.NICID,\n- Addr: remoteAddr,\n+ Addr: srcAddr,\n},\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket.cc",
"new_path": "test/syscalls/linux/raw_socket.cc",
"diff": "@@ -939,6 +939,124 @@ INSTANTIATE_TEST_SUITE_P(\n::testing::Combine(::testing::Values(IPPROTO_TCP, IPPROTO_UDP),\n::testing::Values(AF_INET, AF_INET6)));\n+void TestRawSocketMaybeBindReceive(bool do_bind) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveRawIPSocketCapability()));\n+\n+ constexpr char payload[] = \"abcdefgh\";\n+\n+ const sockaddr_in addr = {\n+ .sin_family = AF_INET,\n+ .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)},\n+ };\n+\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, SOL_UDP));\n+ sockaddr_in udp_sock_bind_addr = addr;\n+ socklen_t udp_sock_bind_addr_len = sizeof(udp_sock_bind_addr);\n+ ASSERT_THAT(bind(udp_sock.get(),\n+ reinterpret_cast<const sockaddr*>(&udp_sock_bind_addr),\n+ sizeof(udp_sock_bind_addr)),\n+ SyscallSucceeds());\n+ ASSERT_THAT(getsockname(udp_sock.get(),\n+ reinterpret_cast<sockaddr*>(&udp_sock_bind_addr),\n+ &udp_sock_bind_addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(udp_sock_bind_addr_len, sizeof(udp_sock_bind_addr));\n+\n+ FileDescriptor raw_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_RAW, SOL_UDP));\n+\n+ auto test_recv = [&](const char* scope, uint32_t expected_destination) {\n+ SCOPED_TRACE(scope);\n+\n+ constexpr int kInfinitePollTimeout = -1;\n+ pollfd pfd = {\n+ .fd = raw_sock.get(),\n+ .events = POLLIN,\n+ };\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kInfinitePollTimeout),\n+ SyscallSucceedsWithValue(1));\n+\n+ struct ipv4_udp_packet {\n+ iphdr ip;\n+ udphdr udp;\n+ char data[sizeof(payload)];\n+\n+ // Used to make sure only the required space is used.\n+ char unused_space;\n+ } ABSL_ATTRIBUTE_PACKED;\n+ constexpr size_t kExpectedIPPacketSize =\n+ offsetof(ipv4_udp_packet, unused_space);\n+\n+ // Receive the whole IPv4 packet on the raw socket.\n+ ipv4_udp_packet read_raw_packet;\n+ sockaddr_in peer;\n+ socklen_t peerlen = sizeof(peer);\n+ ASSERT_EQ(\n+ recvfrom(raw_sock.get(), reinterpret_cast<char*>(&read_raw_packet),\n+ sizeof(read_raw_packet), 0 /* flags */,\n+ reinterpret_cast<sockaddr*>(&peer), &peerlen),\n+ static_cast<ssize_t>(kExpectedIPPacketSize))\n+ << strerror(errno);\n+ ASSERT_EQ(peerlen, sizeof(peer));\n+ EXPECT_EQ(read_raw_packet.ip.version, static_cast<unsigned int>(IPVERSION));\n+ // IHL holds the number of header bytes in 4 byte units.\n+ EXPECT_EQ(read_raw_packet.ip.ihl, sizeof(read_raw_packet.ip) / 4);\n+ EXPECT_EQ(ntohs(read_raw_packet.ip.tot_len), kExpectedIPPacketSize);\n+ EXPECT_EQ(ntohs(read_raw_packet.ip.frag_off) & IP_OFFMASK, 0);\n+ EXPECT_EQ(read_raw_packet.ip.protocol, SOL_UDP);\n+ EXPECT_EQ(ntohl(read_raw_packet.ip.saddr), INADDR_LOOPBACK);\n+ EXPECT_EQ(ntohl(read_raw_packet.ip.daddr), expected_destination);\n+ EXPECT_EQ(read_raw_packet.udp.source, udp_sock_bind_addr.sin_port);\n+ EXPECT_EQ(read_raw_packet.udp.dest, udp_sock_bind_addr.sin_port);\n+ EXPECT_EQ(ntohs(read_raw_packet.udp.len),\n+ kExpectedIPPacketSize - sizeof(read_raw_packet.ip));\n+ for (size_t i = 0; i < sizeof(payload); i++) {\n+ EXPECT_EQ(read_raw_packet.data[i], payload[i])\n+ << \"byte mismatch @ idx=\" << i;\n+ }\n+ EXPECT_EQ(peer.sin_family, AF_INET);\n+ EXPECT_EQ(peer.sin_port, 0);\n+ EXPECT_EQ(ntohl(peer.sin_addr.s_addr), INADDR_LOOPBACK);\n+ };\n+\n+ if (do_bind) {\n+ ASSERT_THAT(bind(raw_sock.get(), reinterpret_cast<const sockaddr*>(&addr),\n+ sizeof(addr)),\n+ SyscallSucceeds());\n+ }\n+\n+ constexpr int kSendToFlags = 0;\n+ sockaddr_in different_addr = udp_sock_bind_addr;\n+ different_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK + 1);\n+ ASSERT_THAT(sendto(udp_sock.get(), payload, sizeof(payload), kSendToFlags,\n+ reinterpret_cast<const sockaddr*>(&different_addr),\n+ sizeof(different_addr)),\n+ SyscallSucceedsWithValue(sizeof(payload)));\n+ if (!do_bind) {\n+ ASSERT_NO_FATAL_FAILURE(\n+ test_recv(\"different_addr\", ntohl(different_addr.sin_addr.s_addr)));\n+ }\n+ ASSERT_THAT(sendto(udp_sock.get(), payload, sizeof(payload), kSendToFlags,\n+ reinterpret_cast<const sockaddr*>(&udp_sock_bind_addr),\n+ sizeof(udp_sock_bind_addr)),\n+ SyscallSucceedsWithValue(sizeof(payload)));\n+ ASSERT_NO_FATAL_FAILURE(\n+ test_recv(\"addr\", ntohl(udp_sock_bind_addr.sin_addr.s_addr)));\n+}\n+\n+TEST(RawSocketTest, UnboundReceive) {\n+ // Test that a raw socket receives packets destined to any address if it is\n+ // not bound to an address.\n+ ASSERT_NO_FATAL_FAILURE(TestRawSocketMaybeBindReceive(false /* do_bind */));\n+}\n+\n+TEST(RawSocketTest, BindReceive) {\n+ // Test that a raw socket only receives packets destined to the address it is\n+ // bound to.\n+ ASSERT_NO_FATAL_FAILURE(TestRawSocketMaybeBindReceive(true /* do_bind */));\n+}\n+\n} // namespace\n} // namespace testing\n"
}
] | Go | Apache License 2.0 | google/gvisor | Accept packets destined to bound address
...if bound to an address.
We previously checked the source of a packet instead of the destination
of a packet when bound to an address.
PiperOrigin-RevId: 396497647 |
259,881 | 14.09.2021 16:20:25 | 14,400 | 5ab2bdf332ccedbc3eedc6e5f7c96f6adb2b80d4 | runsc: allow rootless mode for runsc run
Rootless mode seems to work fine for simple containers with runsc run,
so allow its use.
Since runsc run is more widely used, require a workable --network option
is passed rather than automatically switching like runsc do does.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/run.go",
"new_path": "runsc/cmd/run.go",
"diff": "@@ -68,7 +68,14 @@ func (r *Run) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) s\nwaitStatus := args[1].(*unix.WaitStatus)\nif conf.Rootless {\n- return Errorf(\"Rootless mode not supported with %q\", r.Name())\n+ if conf.Network == config.NetworkSandbox {\n+ return Errorf(\"sandbox network isn't supported with --rootless, use --network=none or --network=host\")\n+ }\n+\n+ if err := specutils.MaybeRunAsRoot(); err != nil {\n+ return Errorf(\"Error executing inside namespace: %v\", err)\n+ }\n+ // Execution will continue here if no more capabilities are needed...\n}\nbundleDir := r.bundleDir\n"
}
] | Go | Apache License 2.0 | google/gvisor | runsc: allow rootless mode for runsc run
Rootless mode seems to work fine for simple containers with runsc run,
so allow its use.
Since runsc run is more widely used, require a workable --network option
is passed rather than automatically switching like runsc do does.
Fixes #3036 |
260,004 | 14.09.2021 13:35:21 | 25,200 | 2b46e2d19e642ed8a0a58ea1c62a38b53e7dfb2d | Defer mutex unlocking | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -534,8 +534,11 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, tcpip.Error) {\n// HandlePacket implements stack.RawTransportEndpoint.HandlePacket.\nfunc (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n+ notifyReadableEvents := func() bool {\ne.mu.RLock()\n+ defer e.mu.RUnlock()\ne.rcvMu.Lock()\n+ defer e.rcvMu.Unlock()\n// Drop the packet if our buffer is currently full or if this is an unassociated\n// endpoint (i.e endpoint created w/ IPPROTO_RAW). Such endpoints are send only\n@@ -546,34 +549,27 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Note that packet sockets don't reassemble IP fragments, unlike raw\n// sockets.\nif e.rcvClosed || !e.associated {\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\ne.stack.Stats().DroppedPackets.Increment()\ne.stats.ReceiveErrors.ClosedReceiver.Increment()\n- return\n+ return false\n}\nrcvBufSize := e.ops.GetReceiveBufferSize()\nif e.frozen || e.rcvBufSize >= int(rcvBufSize) {\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\ne.stack.Stats().DroppedPackets.Increment()\ne.stats.ReceiveErrors.ReceiveBufferOverflow.Increment()\n- return\n+ return false\n}\nif e.bound {\n// If bound to a NIC, only accept data for that NIC.\nif e.BindNICID != 0 && e.BindNICID != pkt.NICID {\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\n- return\n+ return false\n}\n+\n// If bound to an address, only accept data for that address.\nif e.BindAddr != \"\" && e.BindAddr != pkt.Network().DestinationAddress() {\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\n- return\n+ return false\n}\n}\n@@ -581,9 +577,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// If connected, only accept packets from the remote address we\n// connected to.\nif e.connected && e.route.RemoteAddress() != srcAddr {\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\n- return\n+ return false\n}\nwasEmpty := e.rcvBufSize == 0\n@@ -619,11 +613,13 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\ne.rcvList.PushBack(packet)\ne.rcvBufSize += packet.data.Size()\n- e.rcvMu.Unlock()\n- e.mu.RUnlock()\ne.stats.PacketsReceived.Increment()\n- // Notify waiters that there's data to be read.\n- if wasEmpty {\n+\n+ // Notify waiters that there is data to be read now.\n+ return wasEmpty\n+ }()\n+\n+ if notifyReadableEvents {\ne.waiterQueue.Notify(waiter.ReadableEvents)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Defer mutex unlocking
PiperOrigin-RevId: 396670516 |
260,004 | 14.09.2021 14:00:55 | 25,200 | 5593b8a7e6cb5fc04c1b9e23a92b880517330cd4 | Don't use SOL_UDP when creating sockets
SOL_UDP is used when get/set-ing socket options to specify the socket
level. When creating normal UDP sockets, the protocol need not be
specified. When creating RAW IP sockets for UDP, use IPPROTO_UDP. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket.cc",
"new_path": "test/syscalls/linux/raw_socket.cc",
"diff": "@@ -950,7 +950,7 @@ void TestRawSocketMaybeBindReceive(bool do_bind) {\n};\nFileDescriptor udp_sock =\n- ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, SOL_UDP));\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\nsockaddr_in udp_sock_bind_addr = addr;\nsocklen_t udp_sock_bind_addr_len = sizeof(udp_sock_bind_addr);\nASSERT_THAT(bind(udp_sock.get(),\n@@ -964,7 +964,7 @@ void TestRawSocketMaybeBindReceive(bool do_bind) {\nASSERT_EQ(udp_sock_bind_addr_len, sizeof(udp_sock_bind_addr));\nFileDescriptor raw_sock =\n- ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_RAW, SOL_UDP));\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_RAW, IPPROTO_UDP));\nauto test_recv = [&](const char* scope, uint32_t expected_destination) {\nSCOPED_TRACE(scope);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't use SOL_UDP when creating sockets
SOL_UDP is used when get/set-ing socket options to specify the socket
level. When creating normal UDP sockets, the protocol need not be
specified. When creating RAW IP sockets for UDP, use IPPROTO_UDP.
PiperOrigin-RevId: 396675986 |
260,004 | 14.09.2021 17:17:17 | 25,200 | 39470428dd3c5fef966cee138ae00ab8b9059983 | Use a shared method to get loopback index
Code to get the loopback interface's index is scattered throughout the
syscall tests. Implement the code once and use that in tests (where
applicable).
While I am here, trim the dependencies/includes for network namespace
tests. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1446,6 +1446,7 @@ cc_binary(\ndefines = select_system(),\nlinkstatic = 1,\ndeps = [\n+ \":ip_socket_test_util\",\n\":unix_domain_socket_test_util\",\n\"//test/util:capability_util\",\n\"//test/util:cleanup\",\n@@ -1465,6 +1466,7 @@ cc_binary(\nsrcs = [\"packet_socket.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \":ip_socket_test_util\",\n\":unix_domain_socket_test_util\",\n\"//test/util:capability_util\",\n\"//test/util:cleanup\",\n@@ -4132,12 +4134,10 @@ cc_binary(\nsrcs = [\"network_namespace.cc\"],\nlinkstatic = 1,\ndeps = [\n- \"//test/util:socket_util\",\ngtest,\n+ \":ip_socket_test_util\",\n\"//test/util:capability_util\",\n- \"//test/util:posix_error\",\n\"//test/util:test_main\",\n- \"//test/util:test_util\",\n\"//test/util:thread_util\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.h",
"new_path": "test/syscalls/linux/ip_socket_test_util.h",
"diff": "@@ -35,6 +35,9 @@ uint16_t PortFromInetSockaddr(const struct sockaddr* addr);\n// InterfaceIndex returns the index of the named interface.\nPosixErrorOr<int> InterfaceIndex(std::string name);\n+// GetLoopbackIndex returns the index of the loopback interface.\n+inline PosixErrorOr<int> GetLoopbackIndex() { return InterfaceIndex(\"lo\"); }\n+\n// IPv6TCPAcceptBindSocketPair returns a SocketPairKind that represents\n// SocketPairs created with bind() and accept() syscalls with AF_INET6 and the\n// given type bound to the IPv6 loopback.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/network_namespace.cc",
"new_path": "test/syscalls/linux/network_namespace.cc",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-#include <net/if.h>\n-#include <sched.h>\n-#include <sys/ioctl.h>\n-#include <sys/socket.h>\n-#include <sys/types.h>\n-\n-#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n-#include \"test/util/posix_error.h\"\n-#include \"test/util/socket_util.h\"\n-#include \"test/util/test_util.h\"\n#include \"test/util/thread_util.h\"\nnamespace gvisor {\n@@ -37,13 +28,7 @@ TEST(NetworkNamespaceTest, LoopbackExists) {\nASSERT_THAT(unshare(CLONE_NEWNET), SyscallSucceedsWithValue(0));\n// TODO(gvisor.dev/issue/1833): Update this to test that only \"lo\" exists.\n- // Check loopback device exists.\n- int sock = socket(AF_INET, SOCK_DGRAM, 0);\n- ASSERT_THAT(sock, SyscallSucceeds());\n- struct ifreq ifr;\n- strncpy(ifr.ifr_name, \"lo\", IFNAMSIZ);\n- EXPECT_THAT(ioctl(sock, SIOCGIFINDEX, &ifr), SyscallSucceeds())\n- << \"lo cannot be found\";\n+ ASSERT_NE(ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()), 0);\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "#include \"gtest/gtest.h\"\n#include \"absl/base/internal/endian.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/cleanup.h\"\n@@ -156,11 +157,9 @@ void CookedPacketTest::TearDown() {\n}\nint CookedPacketTest::GetLoopbackIndex() {\n- struct ifreq ifr;\n- snprintf(ifr.ifr_name, IFNAMSIZ, \"lo\");\n- EXPECT_THAT(ioctl(socket_, SIOCGIFINDEX, &ifr), SyscallSucceeds());\n- EXPECT_NE(ifr.ifr_ifindex, 0);\n- return ifr.ifr_ifindex;\n+ int v = EXPECT_NO_ERRNO_AND_VALUE(gvisor::testing::GetLoopbackIndex());\n+ EXPECT_NE(v, 0);\n+ return v;\n}\n// Receive and verify the message via packet socket on interface.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_raw.cc",
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "#include <arpa/inet.h>\n#include <net/ethernet.h>\n-#include <net/if.h>\n#include <net/if_arp.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/udp.h>\n#include <netpacket/packet.h>\n#include <poll.h>\n-#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/base/internal/endian.h\"\n+#include \"test/syscalls/linux/ip_socket_test_util.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/cleanup.h\"\n@@ -156,11 +155,9 @@ void RawPacketTest::TearDown() {\n}\nint RawPacketTest::GetLoopbackIndex() {\n- struct ifreq ifr;\n- snprintf(ifr.ifr_name, IFNAMSIZ, \"lo\");\n- EXPECT_THAT(ioctl(s_, SIOCGIFINDEX, &ifr), SyscallSucceeds());\n- EXPECT_NE(ifr.ifr_ifindex, 0);\n- return ifr.ifr_ifindex;\n+ int v = EXPECT_NO_ERRNO_AND_VALUE(gvisor::testing::GetLoopbackIndex());\n+ EXPECT_NE(v, 0);\n+ return v;\n}\n// Receive via a packet socket.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"new_path": "test/syscalls/linux/socket_ipv4_udp_unbound.cc",
"diff": "#include \"test/syscalls/linux/socket_ipv4_udp_unbound.h\"\n#include <arpa/inet.h>\n-#include <net/if.h>\n-#include <sys/ioctl.h>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <sys/un.h>\n@@ -140,7 +138,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNicNoDefaultSendIf) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nEXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -238,7 +236,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNic) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -326,7 +324,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNic) {\n// Set the default send interface.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -346,7 +344,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNic) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -437,7 +435,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicConnect) {\n// Set the default send interface.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -457,7 +455,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicConnect) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -548,7 +546,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelf) {\n// Set the default send interface.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -568,7 +566,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelf) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -657,7 +655,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfConnect) {\n// Set the default send interface.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -677,7 +675,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfConnect) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -770,7 +768,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfNoLoop) {\n// Set the default send interface.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,\nsizeof(iface)),\nSyscallSucceeds());\n@@ -794,7 +792,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfNoLoop) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nEXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -917,7 +915,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastDropNic) {\n// Register and unregister to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nEXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -981,7 +979,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIfSetShort) {\n// Create a valid full-sized request.\nip_mreqn iface = {};\n- iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\n// Send an optlen of 1 to check that optlen is enforced.\nEXPECT_THAT(\n@@ -1079,7 +1077,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIfSetNicGetReqn) {\nauto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nip_mreqn set = {};\n- set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set,\nsizeof(set)),\nSyscallSucceeds());\n@@ -1140,7 +1138,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIfSetNic) {\nauto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\nip_mreqn set = {};\n- set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ set.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &set,\nsizeof(set)),\nSyscallSucceeds());\n@@ -1186,7 +1184,7 @@ TEST_P(IPv4UDPUnboundSocketTest, TestMultipleJoinsOnSingleSocket) {\nauto fd = socket1->get();\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nEXPECT_THAT(\nsetsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group)),\n@@ -1204,7 +1202,7 @@ TEST_P(IPv4UDPUnboundSocketTest, TestTwoSocketsJoinSameMulticastGroup) {\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nEXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -1419,7 +1417,7 @@ TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenJoinThenReceive) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,\nsizeof(group)),\nSyscallSucceeds());\n@@ -2110,16 +2108,11 @@ TEST_P(IPv4UDPUnboundSocketTest, SetAndReceiveIPPKTINFO) {\nEXPECT_EQ(cmsg->cmsg_level, level);\nEXPECT_EQ(cmsg->cmsg_type, type);\n- // Get loopback index.\n- ifreq ifr = {};\n- absl::SNPrintF(ifr.ifr_name, IFNAMSIZ, \"lo\");\n- ASSERT_THAT(ioctl(sender->get(), SIOCGIFINDEX, &ifr), SyscallSucceeds());\n- ASSERT_NE(ifr.ifr_ifindex, 0);\n-\n// Check the data\nin_pktinfo received_pktinfo = {};\nmemcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(in_pktinfo));\n- EXPECT_EQ(received_pktinfo.ipi_ifindex, ifr.ifr_ifindex);\n+ EXPECT_EQ(received_pktinfo.ipi_ifindex,\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));\nEXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, htonl(INADDR_LOOPBACK));\nEXPECT_EQ(received_pktinfo.ipi_addr.s_addr, htonl(INADDR_LOOPBACK));\n}\n@@ -2439,7 +2432,7 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIPPacketInfo) {\n// Register to receive multicast packets.\nip_mreqn group = {};\ngroup.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);\n- group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"));\n+ group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());\nASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP,\n&group, sizeof(group)),\nSyscallSucceeds());\n@@ -2484,16 +2477,10 @@ TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIPPacketInfo) {\nEXPECT_EQ(cmsg->cmsg_level, IPPROTO_IP);\nEXPECT_EQ(cmsg->cmsg_type, IP_PKTINFO);\n- // Get loopback index.\n- ifreq ifr = {};\n- absl::SNPrintF(ifr.ifr_name, IFNAMSIZ, \"lo\");\n- ASSERT_THAT(ioctl(receiver_socket->get(), SIOCGIFINDEX, &ifr),\n- SyscallSucceeds());\n- ASSERT_NE(ifr.ifr_ifindex, 0);\n-\nin_pktinfo received_pktinfo = {};\nmemcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(in_pktinfo));\n- EXPECT_EQ(received_pktinfo.ipi_ifindex, ifr.ifr_ifindex);\n+ EXPECT_EQ(received_pktinfo.ipi_ifindex,\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));\nif (IsRunningOnGvisor()) {\n// This should actually be a unicast address assigned to the interface.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv6_udp_unbound_external_networking.cc",
"new_path": "test/syscalls/linux/socket_ipv6_udp_unbound_external_networking.cc",
"diff": "@@ -39,7 +39,7 @@ TEST_P(IPv6UDPUnboundExternalNetworkingSocketTest, TestJoinLeaveMulticast) {\n.ipv6mr_multiaddr =\nreinterpret_cast<sockaddr_in6*>(&multicast_addr.addr)->sin6_addr,\n.ipv6mr_interface = static_cast<decltype(ipv6_mreq::ipv6mr_interface)>(\n- ASSERT_NO_ERRNO_AND_VALUE(InterfaceIndex(\"lo\"))),\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex())),\n};\nASSERT_THAT(setsockopt(receiver->get(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP,\n&group_req, sizeof(group_req)),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use a shared method to get loopback index
Code to get the loopback interface's index is scattered throughout the
syscall tests. Implement the code once and use that in tests (where
applicable).
While I am here, trim the dependencies/includes for network namespace
tests.
PiperOrigin-RevId: 396718124 |
260,004 | 15.09.2021 12:18:00 | 25,200 | 149ca009678edc580de9f0b1d54f551d376742cb | [bind] Return EINVAL for under sized address
...and EAFNOSUPPORT for unexpected address family.
To comply with Linux.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -419,6 +419,27 @@ func bytesToIPAddress(addr []byte) tcpip.Address {\nreturn tcpip.Address(addr)\n}\n+// minSockAddrLen returns the minimum length in bytes of a socket address for\n+// the socket's family.\n+func (s *socketOpsCommon) minSockAddrLen() int {\n+ const addressFamilySize = 2\n+\n+ switch s.family {\n+ case linux.AF_UNIX:\n+ return addressFamilySize\n+ case linux.AF_INET:\n+ return sockAddrInetSize\n+ case linux.AF_INET6:\n+ return sockAddrInet6Size\n+ case linux.AF_PACKET:\n+ return sockAddrLinkSize\n+ case linux.AF_UNSPEC:\n+ return addressFamilySize\n+ default:\n+ panic(fmt.Sprintf(\"s.family unrecognized = %d\", s.family))\n+ }\n+}\n+\nfunc (s *socketOpsCommon) isPacketBased() bool {\nreturn s.skType == linux.SOCK_DGRAM || s.skType == linux.SOCK_SEQPACKET || s.skType == linux.SOCK_RDM || s.skType == linux.SOCK_RAW\n}\n@@ -545,16 +566,21 @@ func (s *socketOpsCommon) Readiness(mask waiter.EventMask) waiter.EventMask {\nreturn s.Endpoint.Readiness(mask)\n}\n-func (s *socketOpsCommon) checkFamily(family uint16, exact bool) *syserr.Error {\n+// checkFamily returns true iff the specified address family may be used with\n+// the socket.\n+//\n+// If exact is true, then the specified address family must be an exact match\n+// with the socket's family.\n+func (s *socketOpsCommon) checkFamily(family uint16, exact bool) bool {\nif family == uint16(s.family) {\n- return nil\n+ return true\n}\nif !exact && family == linux.AF_INET && s.family == linux.AF_INET6 {\nif !s.Endpoint.SocketOptions().GetV6Only() {\n- return nil\n+ return true\n}\n}\n- return syserr.ErrInvalidArgument\n+ return false\n}\n// mapFamily maps the AF_INET ANY address to the IPv4-mapped IPv6 ANY if the\n@@ -587,8 +613,8 @@ func (s *socketOpsCommon) Connect(t *kernel.Task, sockaddr []byte, blocking bool\nreturn syserr.TranslateNetstackError(err)\n}\n- if err := s.checkFamily(family, false /* exact */); err != nil {\n- return err\n+ if !s.checkFamily(family, false /* exact */) {\n+ return syserr.ErrInvalidArgument\n}\naddr = s.mapFamily(addr, family)\n@@ -655,14 +681,18 @@ func (s *socketOpsCommon) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\nAddr: tcpip.Address(a.HardwareAddr[:header.EthernetAddressSize]),\n}\n} else {\n+ if s.minSockAddrLen() > len(sockaddr) {\n+ return syserr.ErrInvalidArgument\n+ }\n+\nvar err *syserr.Error\naddr, family, err = socket.AddressAndFamily(sockaddr)\nif err != nil {\nreturn err\n}\n- if err = s.checkFamily(family, true /* exact */); err != nil {\n- return err\n+ if !s.checkFamily(family, true /* exact */) {\n+ return syserr.ErrAddressFamilyNotSupported\n}\naddr = s.mapFamily(addr, family)\n@@ -2872,8 +2902,8 @@ func (s *socketOpsCommon) SendMsg(t *kernel.Task, src usermem.IOSequence, to []b\nif err != nil {\nreturn 0, err\n}\n- if err := s.checkFamily(family, false /* exact */); err != nil {\n- return 0, err\n+ if !s.checkFamily(family, false /* exact */) {\n+ return 0, syserr.ErrInvalidArgument\n}\naddrBuf = s.mapFamily(addrBuf, family)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ping_socket.cc",
"new_path": "test/syscalls/linux/ping_socket.cc",
"diff": "@@ -155,43 +155,33 @@ std::vector<std::tuple<SocketKind, BindTestCase>> ICMPTestCases() {\n.bind_to = V4AddrStr(\"IPv4UnknownUnicast\", \"192.168.1.1\"),\n.want = EADDRNOTAVAIL,\n},\n- // TODO(gvisor.dev/issue/6021): Remove want_gvisor from all the test\n- // cases below once ICMP sockets return EAFNOSUPPORT when binding to\n- // IPv6 addresses.\n{\n.bind_to = V6Any(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6Loopback(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6Multicast(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6MulticastInterfaceLocalAllNodes(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6MulticastLinkLocalAllNodes(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6MulticastLinkLocalAllRouters(),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n{\n.bind_to = V6AddrStr(\"IPv6UnknownUnicast\", \"fc00::1\"),\n.want = EAFNOSUPPORT,\n- .want_gvisor = EINVAL,\n},\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "@@ -643,12 +643,12 @@ TEST_P(UdpSocketTest, DisconnectAfterBindToUnspecAndConnect) {\nsockaddr_storage unspec = {.ss_family = AF_UNSPEC};\nint bind_res = bind(sock_.get(), AsSockAddr(&unspec), sizeof(unspec));\n- if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {\n- // TODO(https://gvisor.dev/issue/6575): Match Linux's behaviour.\n- ASSERT_THAT(bind_res, SyscallFailsWithErrno(EINVAL));\n- } else if (GetFamily() == AF_INET) {\n+ if ((!IsRunningOnGvisor() || IsRunningWithHostinet()) &&\n+ GetFamily() == AF_INET) {\n// Linux allows this for undocumented compatibility reasons:\n// https://github.com/torvalds/linux/commit/29c486df6a208432b370bd4be99ae1369ede28d8.\n+ //\n+ // TODO(https://gvisor.dev/issue/6575): Match Linux's behaviour.\nASSERT_THAT(bind_res, SyscallSucceeds());\n} else {\nASSERT_THAT(bind_res, SyscallFailsWithErrno(EAFNOSUPPORT));\n"
}
] | Go | Apache License 2.0 | google/gvisor | [bind] Return EINVAL for under sized address
...and EAFNOSUPPORT for unexpected address family.
To comply with Linux.
Updates #6021, #6575.
PiperOrigin-RevId: 396893590 |
260,004 | 15.09.2021 23:48:05 | 25,200 | 477d7e5e10378e2f80f21ac9f536d12c4b94d7ce | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Also update the endpoint's state field to be accessed while the mutex is
held instead of requiring atomic operations as nothing needs to call the
State method while the mutex is held.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"new_path": "pkg/tcpip/transport/internal/network/endpoint.go",
"diff": "@@ -18,7 +18,6 @@ package network\nimport (\n\"fmt\"\n- \"sync/atomic\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -38,30 +37,40 @@ type Endpoint struct {\nnetProto tcpip.NetworkProtocolNumber\ntransProto tcpip.TransportProtocolNumber\n- // state holds a transport.DatagramBasedEndpointState.\n- //\n- // state must be read from/written to atomically.\n- state uint32\n-\n- // The following fields are protected by mu.\nmu sync.RWMutex `state:\"nosave\"`\n+ // +checklocks:mu\n+ state transport.DatagramEndpointState\n+ // +checklocks:mu\nwasBound bool\n+ // +checklocks:mu\ninfo stack.TransportEndpointInfo\n// owner is the owner of transmitted packets.\n+ //\n+ // +checklocks:mu\nowner tcpip.PacketOwner\n+ // +checklocks:mu\nwriteShutdown bool\n+ // +checklocks:mu\neffectiveNetProto tcpip.NetworkProtocolNumber\n+ // +checklocks:mu\nconnectedRoute *stack.Route `state:\"manual\"`\n+ // +checklocks:mu\nmulticastMemberships map[multicastMembership]struct{}\n// TODO(https://gvisor.dev/issue/6389): Use different fields for IPv4/IPv6.\n+ // +checklocks:mu\nttl uint8\n// TODO(https://gvisor.dev/issue/6389): Use different fields for IPv4/IPv6.\n+ // +checklocks:mu\nmulticastTTL uint8\n// TODO(https://gvisor.dev/issue/6389): Use different fields for IPv4/IPv6.\n+ // +checklocks:mu\nmulticastAddr tcpip.Address\n// TODO(https://gvisor.dev/issue/6389): Use different fields for IPv4/IPv6.\n+ // +checklocks:mu\nmulticastNICID tcpip.NICID\n+ // +checklocks:mu\nipv4TOS uint8\n+ // +checklocks:mu\nipv6TClass uint8\n}\n@@ -73,8 +82,11 @@ type multicastMembership struct {\n// Init initializes the endpoint.\nfunc (e *Endpoint) Init(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, ops *tcpip.SocketOptions) {\n- if e.multicastMemberships != nil {\n- panic(fmt.Sprintf(\"endpoint is already initialized; got e.multicastMemberships = %#v, want = nil\", e.multicastMemberships))\n+ e.mu.Lock()\n+ memberships := e.multicastMemberships\n+ e.mu.Unlock()\n+ if memberships != nil {\n+ panic(fmt.Sprintf(\"endpoint is already initialized; got e.multicastMemberships = %#v, want = nil\", memberships))\n}\nswitch netProto {\n@@ -89,8 +101,7 @@ func (e *Endpoint) Init(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, tr\nnetProto: netProto,\ntransProto: transProto,\n- state: uint32(transport.DatagramEndpointStateInitial),\n-\n+ state: transport.DatagramEndpointStateInitial,\ninfo: stack.TransportEndpointInfo{\nNetProto: netProto,\nTransProto: transProto,\n@@ -107,14 +118,11 @@ func (e *Endpoint) NetProto() tcpip.NetworkProtocolNumber {\nreturn e.netProto\n}\n-// setState sets the state of the endpoint.\n-func (e *Endpoint) setEndpointState(state transport.DatagramEndpointState) {\n- atomic.StoreUint32(&e.state, uint32(state))\n-}\n-\n// State returns the state of the endpoint.\nfunc (e *Endpoint) State() transport.DatagramEndpointState {\n- return transport.DatagramEndpointState(atomic.LoadUint32(&e.state))\n+ e.mu.RLock()\n+ defer e.mu.RUnlock()\n+ return e.state\n}\n// Close cleans the endpoint's resources and leaves the endpoint in a closed\n@@ -123,7 +131,7 @@ func (e *Endpoint) Close() {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- if e.State() == transport.DatagramEndpointStateClosed {\n+ if e.state == transport.DatagramEndpointStateClosed {\nreturn\n}\n@@ -137,7 +145,7 @@ func (e *Endpoint) Close() {\ne.connectedRoute = nil\n}\n- e.setEndpointState(transport.DatagramEndpointStateClosed)\n+ e.state = transport.DatagramEndpointStateClosed\n}\n// SetOwner sets the owner of transmitted packets.\n@@ -218,7 +226,7 @@ func (e *Endpoint) AcquireContextForWrite(opts tcpip.WriteOptions) (WriteContext\nreturn WriteContext{}, &tcpip.ErrInvalidOptionValue{}\n}\n- if e.State() == transport.DatagramEndpointStateClosed {\n+ if e.state == transport.DatagramEndpointStateClosed {\nreturn WriteContext{}, &tcpip.ErrInvalidEndpointState{}\n}\n@@ -230,7 +238,7 @@ func (e *Endpoint) AcquireContextForWrite(opts tcpip.WriteOptions) (WriteContext\nif opts.To == nil {\n// If the user doesn't specify a destination, they should have\n// connected to another address.\n- if e.State() != transport.DatagramEndpointStateConnected {\n+ if e.state != transport.DatagramEndpointStateConnected {\nreturn WriteContext{}, &tcpip.ErrDestinationRequired{}\n}\n@@ -253,12 +261,12 @@ func (e *Endpoint) AcquireContextForWrite(opts tcpip.WriteOptions) (WriteContext\nnicID = e.info.RegisterNICID\n}\n- dst, netProto, err := e.checkV4MappedLocked(*opts.To)\n+ dst, netProto, err := e.checkV4MappedRLocked(*opts.To)\nif err != nil {\nreturn WriteContext{}, err\n}\n- route, _, err = e.connectRoute(nicID, dst, netProto)\n+ route, _, err = e.connectRouteRLocked(nicID, dst, netProto)\nif err != nil {\nreturn WriteContext{}, err\n}\n@@ -293,7 +301,7 @@ func (e *Endpoint) Disconnect() {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- if e.State() != transport.DatagramEndpointStateConnected {\n+ if e.state != transport.DatagramEndpointStateConnected {\nreturn\n}\n@@ -302,20 +310,23 @@ func (e *Endpoint) Disconnect() {\ne.info.ID = stack.TransportEndpointID{\nLocalAddress: e.info.BindAddr,\n}\n- e.setEndpointState(transport.DatagramEndpointStateBound)\n+ e.state = transport.DatagramEndpointStateBound\n} else {\ne.info.ID = stack.TransportEndpointID{}\n- e.setEndpointState(transport.DatagramEndpointStateInitial)\n+ e.state = transport.DatagramEndpointStateInitial\n}\ne.connectedRoute.Release()\ne.connectedRoute = nil\n}\n-// connectRoute establishes a route to the specified interface or the\n+// connectRouteRLocked establishes a route to the specified interface or the\n// configured multicast interface if no interface is specified and the\n// specified address is a multicast address.\n-func (e *Endpoint) connectRoute(nicID tcpip.NICID, addr tcpip.FullAddress, netProto tcpip.NetworkProtocolNumber) (*stack.Route, tcpip.NICID, tcpip.Error) {\n+//\n+// TODO(https://gvisor.dev/issue/6590): Annotate read lock requirement.\n+// +checklocks:e.mu\n+func (e *Endpoint) connectRouteRLocked(nicID tcpip.NICID, addr tcpip.FullAddress, netProto tcpip.NetworkProtocolNumber) (*stack.Route, tcpip.NICID, tcpip.Error) {\nlocalAddr := e.info.ID.LocalAddress\nif e.isBroadcastOrMulticast(nicID, netProto, localAddr) {\n// A packet can only originate from a unicast address (i.e., an interface).\n@@ -360,7 +371,7 @@ func (e *Endpoint) ConnectAndThen(addr tcpip.FullAddress, f func(netProto tcpip.\ndefer e.mu.Unlock()\nnicID := addr.NIC\n- switch e.State() {\n+ switch e.state {\ncase transport.DatagramEndpointStateInitial:\ncase transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected:\nif e.info.BindNICID == 0 {\n@@ -376,12 +387,12 @@ func (e *Endpoint) ConnectAndThen(addr tcpip.FullAddress, f func(netProto tcpip.\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- addr, netProto, err := e.checkV4MappedLocked(addr)\n+ addr, netProto, err := e.checkV4MappedRLocked(addr)\nif err != nil {\nreturn err\n}\n- r, nicID, err := e.connectRoute(nicID, addr, netProto)\n+ r, nicID, err := e.connectRouteRLocked(nicID, addr, netProto)\nif err != nil {\nreturn err\n}\n@@ -390,7 +401,7 @@ func (e *Endpoint) ConnectAndThen(addr tcpip.FullAddress, f func(netProto tcpip.\nLocalAddress: e.info.ID.LocalAddress,\nRemoteAddress: r.RemoteAddress(),\n}\n- if e.State() == transport.DatagramEndpointStateInitial {\n+ if e.state == transport.DatagramEndpointStateInitial {\nid.LocalAddress = r.LocalAddress()\n}\n@@ -406,7 +417,7 @@ func (e *Endpoint) ConnectAndThen(addr tcpip.FullAddress, f func(netProto tcpip.\ne.info.ID = id\ne.info.RegisterNICID = nicID\ne.effectiveNetProto = netProto\n- e.setEndpointState(transport.DatagramEndpointStateConnected)\n+ e.state = transport.DatagramEndpointStateConnected\nreturn nil\n}\n@@ -415,7 +426,7 @@ func (e *Endpoint) Shutdown() tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- switch state := e.State(); state {\n+ switch state := e.state; state {\ncase transport.DatagramEndpointStateInitial, transport.DatagramEndpointStateClosed:\nreturn &tcpip.ErrNotConnected{}\ncase transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected:\n@@ -426,9 +437,12 @@ func (e *Endpoint) Shutdown() tcpip.Error {\n}\n}\n-// checkV4MappedLocked determines the effective network protocol and converts\n+// checkV4MappedRLocked determines the effective network protocol and converts\n// addr to its canonical form.\n-func (e *Endpoint) checkV4MappedLocked(addr tcpip.FullAddress) (tcpip.FullAddress, tcpip.NetworkProtocolNumber, tcpip.Error) {\n+//\n+// TODO(https://gvisor.dev/issue/6590): Annotate read lock requirement.\n+// +checklocks:e.mu\n+func (e *Endpoint) checkV4MappedRLocked(addr tcpip.FullAddress) (tcpip.FullAddress, tcpip.NetworkProtocolNumber, tcpip.Error) {\nunwrapped, netProto, err := e.info.AddrNetProtoLocked(addr, e.ops.GetV6Only())\nif err != nil {\nreturn tcpip.FullAddress{}, 0, err\n@@ -460,11 +474,11 @@ func (e *Endpoint) BindAndThen(addr tcpip.FullAddress, f func(tcpip.NetworkProto\n// Don't allow binding once endpoint is not in the initial state\n// anymore.\n- if e.State() != transport.DatagramEndpointStateInitial {\n+ if e.state != transport.DatagramEndpointStateInitial {\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- addr, netProto, err := e.checkV4MappedLocked(addr)\n+ addr, netProto, err := e.checkV4MappedRLocked(addr)\nif err != nil {\nreturn err\n}\n@@ -490,7 +504,7 @@ func (e *Endpoint) BindAndThen(addr tcpip.FullAddress, f func(tcpip.NetworkProto\ne.info.RegisterNICID = nicID\ne.info.BindAddr = addr.Addr\ne.effectiveNetProto = netProto\n- e.setEndpointState(transport.DatagramEndpointStateBound)\n+ e.state = transport.DatagramEndpointStateBound\nreturn nil\n}\n@@ -507,7 +521,7 @@ func (e *Endpoint) GetLocalAddress() tcpip.FullAddress {\ndefer e.mu.RUnlock()\naddr := e.info.BindAddr\n- if e.State() == transport.DatagramEndpointStateConnected {\n+ if e.state == transport.DatagramEndpointStateConnected {\naddr = e.connectedRoute.LocalAddress()\n}\n@@ -522,7 +536,7 @@ func (e *Endpoint) GetRemoteAddress() (tcpip.FullAddress, bool) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n- if e.State() != transport.DatagramEndpointStateConnected {\n+ if e.state != transport.DatagramEndpointStateConnected {\nreturn tcpip.FullAddress{}, false\n}\n@@ -610,7 +624,7 @@ func (e *Endpoint) SetSockOpt(opt tcpip.SettableSocketOption) tcpip.Error {\ndefer e.mu.Unlock()\nfa := tcpip.FullAddress{Addr: v.InterfaceAddr}\n- fa, netProto, err := e.checkV4MappedLocked(fa)\n+ fa, netProto, err := e.checkV4MappedRLocked(fa)\nif err != nil {\nreturn err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/endpoint_state.go",
"new_path": "pkg/tcpip/transport/internal/network/endpoint_state.go",
"diff": "@@ -35,7 +35,7 @@ func (e *Endpoint) Resume(s *stack.Stack) {\n}\n}\n- switch state := e.State(); state {\n+ switch e.state {\ncase transport.DatagramEndpointStateInitial, transport.DatagramEndpointStateClosed:\ncase transport.DatagramEndpointStateBound:\nif len(e.info.ID.LocalAddress) != 0 && !e.isBroadcastOrMulticast(e.info.RegisterNICID, e.effectiveNetProto, e.info.ID.LocalAddress) {\n@@ -51,6 +51,6 @@ func (e *Endpoint) Resume(s *stack.Stack) {\npanic(fmt.Sprintf(\"e.stack.FindRoute(%d, %s, %s, %d, %t): %s\", e.info.RegisterNICID, e.info.ID.LocalAddress, e.info.ID.RemoteAddress, e.effectiveNetProto, multicastLoop, err))\n}\ndefault:\n- panic(fmt.Sprintf(\"unhandled state = %s\", state))\n+ panic(fmt.Sprintf(\"unhandled state = %s\", e.state))\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Also update the endpoint's state field to be accessed while the mutex is
held instead of requiring atomic operations as nothing needs to call the
State method while the mutex is held.
Updates #6566.
PiperOrigin-RevId: 397010316 |
260,004 | 16.09.2021 11:50:51 | 25,200 | 282a4dd52b337dccfb578e9d32dd1005c864dd8d | Don't allow binding to broadcast on ICMP sockets
...to match Linux behaviour.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "@@ -688,9 +688,20 @@ func (e *endpoint) bindLocked(addr tcpip.FullAddress) tcpip.Error {\nreturn nil\n}\n+func (e *endpoint) isBroadcastOrMulticast(nicID tcpip.NICID, addr tcpip.Address) bool {\n+ return addr == header.IPv4Broadcast ||\n+ header.IsV4MulticastAddress(addr) ||\n+ header.IsV6MulticastAddress(addr) ||\n+ e.stack.IsSubnetBroadcast(nicID, e.NetProto, addr)\n+}\n+\n// Bind binds the endpoint to a specific local address and port.\n// Specifying a NIC is optional.\nfunc (e *endpoint) Bind(addr tcpip.FullAddress) tcpip.Error {\n+ if len(addr.Addr) != 0 && e.isBroadcastOrMulticast(addr.NIC, addr.Addr) {\n+ return &tcpip.ErrBadLocalAddress{}\n+ }\n+\ne.mu.Lock()\ndefer e.mu.Unlock()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ping_socket.cc",
"new_path": "test/syscalls/linux/ping_socket.cc",
"diff": "@@ -128,9 +128,6 @@ std::vector<std::tuple<SocketKind, BindTestCase>> ICMPTestCases() {\n{\n.bind_to = V4Broadcast(),\n.want = EADDRNOTAVAIL,\n- // TODO(gvisor.dev/issue/5711): Remove want_gvisor once ICMP\n- // sockets are no longer allowed to bind to broadcast addresses.\n- .want_gvisor = 0,\n},\n{\n.bind_to = V4Loopback(),\n@@ -139,9 +136,6 @@ std::vector<std::tuple<SocketKind, BindTestCase>> ICMPTestCases() {\n{\n.bind_to = V4LoopbackSubnetBroadcast(),\n.want = EADDRNOTAVAIL,\n- // TODO(gvisor.dev/issue/5711): Remove want_gvisor once ICMP\n- // sockets are no longer allowed to bind to broadcast addresses.\n- .want_gvisor = 0,\n},\n{\n.bind_to = V4Multicast(),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't allow binding to broadcast on ICMP sockets
...to match Linux behaviour.
Fixes #5711.
PiperOrigin-RevId: 397132671 |
260,004 | 16.09.2021 19:50:00 | 25,200 | 85bd3dd9b119cbc5a68b778a18ae73d3567ff610 | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Checklocks also pointed out a locking violation which is fixed
in this change.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_demuxer.go",
"new_path": "pkg/tcpip/stack/transport_demuxer.go",
"diff": "@@ -32,11 +32,13 @@ type protocolIDs struct {\n// transportEndpoints manages all endpoints of a given protocol. It has its own\n// mutex so as to reduce interference between protocols.\ntype transportEndpoints struct {\n- // mu protects all fields of the transportEndpoints.\nmu sync.RWMutex\n+ // +checklocks:mu\nendpoints map[TransportEndpointID]*endpointsByNIC\n// rawEndpoints contains endpoints for raw sockets, which receive all\n// traffic of a given protocol regardless of port.\n+ //\n+ // +checklocks:mu\nrawEndpoints []RawTransportEndpoint\n}\n@@ -69,7 +71,7 @@ func (eps *transportEndpoints) transportEndpoints() []TransportEndpoint {\n// descending order of match quality. If a call to yield returns false,\n// iterEndpointsLocked stops iteration and returns immediately.\n//\n-// Preconditions: eps.mu must be locked.\n+// +checklocks:eps.mu\nfunc (eps *transportEndpoints) iterEndpointsLocked(id TransportEndpointID, yield func(*endpointsByNIC) bool) {\n// Try to find a match with the id as provided.\nif ep, ok := eps.endpoints[id]; ok {\n@@ -110,7 +112,7 @@ func (eps *transportEndpoints) iterEndpointsLocked(id TransportEndpointID, yield\n// findAllEndpointsLocked returns all endpointsByNIC in eps that match id, in\n// descending order of match quality.\n//\n-// Preconditions: eps.mu must be locked.\n+// +checklocks:eps.mu\nfunc (eps *transportEndpoints) findAllEndpointsLocked(id TransportEndpointID) []*endpointsByNIC {\nvar matchedEPs []*endpointsByNIC\neps.iterEndpointsLocked(id, func(ep *endpointsByNIC) bool {\n@@ -122,7 +124,7 @@ func (eps *transportEndpoints) findAllEndpointsLocked(id TransportEndpointID) []\n// findEndpointLocked returns the endpoint that most closely matches the given id.\n//\n-// Preconditions: eps.mu must be locked.\n+// +checklocks:eps.mu\nfunc (eps *transportEndpoints) findEndpointLocked(id TransportEndpointID) *endpointsByNIC {\nvar matchedEP *endpointsByNIC\neps.iterEndpointsLocked(id, func(ep *endpointsByNIC) bool {\n@@ -133,10 +135,12 @@ func (eps *transportEndpoints) findEndpointLocked(id TransportEndpointID) *endpo\n}\ntype endpointsByNIC struct {\n- mu sync.RWMutex\n- endpoints map[tcpip.NICID]*multiPortEndpoint\n// seed is a random secret for a jenkins hash.\nseed uint32\n+\n+ mu sync.RWMutex\n+ // +checklocks:mu\n+ endpoints map[tcpip.NICID]*multiPortEndpoint\n}\nfunc (epsByNIC *endpointsByNIC) transportEndpoints() []TransportEndpoint {\n@@ -171,7 +175,7 @@ func (epsByNIC *endpointsByNIC) handlePacket(id TransportEndpointID, pkt *Packet\nreturn true\n}\n// multiPortEndpoints are guaranteed to have at least one element.\n- transEP := selectEndpoint(id, mpep, epsByNIC.seed)\n+ transEP := mpep.selectEndpoint(id, epsByNIC.seed)\nif queuedProtocol, mustQueue := mpep.demux.queuedProtocols[protocolIDs{mpep.netProto, mpep.transProto}]; mustQueue {\nqueuedProtocol.QueuePacket(transEP, id, pkt)\nepsByNIC.mu.RUnlock()\n@@ -200,7 +204,7 @@ func (epsByNIC *endpointsByNIC) handleError(n *nic, id TransportEndpointID, tran\n// broadcast like we are doing with handlePacket above?\n// multiPortEndpoints are guaranteed to have at least one element.\n- selectEndpoint(id, mpep, epsByNIC.seed).HandleError(transErr, pkt)\n+ mpep.selectEndpoint(id, epsByNIC.seed).HandleError(transErr, pkt)\n}\n// registerEndpoint returns true if it succeeds. It fails and returns\n@@ -333,15 +337,18 @@ func (d *transportDemuxer) checkEndpoint(netProtos []tcpip.NetworkProtocolNumber\n//\n// +stateify savable\ntype multiPortEndpoint struct {\n- mu sync.RWMutex `state:\"nosave\"`\ndemux *transportDemuxer\nnetProto tcpip.NetworkProtocolNumber\ntransProto tcpip.TransportProtocolNumber\n+ flags ports.FlagCounter\n+\n+ mu sync.RWMutex `state:\"nosave\"`\n// endpoints stores the transport endpoints in the order in which they\n// were bound. This is required for UDP SO_REUSEADDR.\n+ //\n+ // +checklocks:mu\nendpoints []TransportEndpoint\n- flags ports.FlagCounter\n}\nfunc (ep *multiPortEndpoint) transportEndpoints() []TransportEndpoint {\n@@ -362,13 +369,16 @@ func reciprocalScale(val, n uint32) uint32 {\n// selectEndpoint calculates a hash of destination and source addresses and\n// ports then uses it to select a socket. In this case, all packets from one\n// address will be sent to same endpoint.\n-func selectEndpoint(id TransportEndpointID, mpep *multiPortEndpoint, seed uint32) TransportEndpoint {\n- if len(mpep.endpoints) == 1 {\n- return mpep.endpoints[0]\n+func (ep *multiPortEndpoint) selectEndpoint(id TransportEndpointID, seed uint32) TransportEndpoint {\n+ ep.mu.RLock()\n+ defer ep.mu.RUnlock()\n+\n+ if len(ep.endpoints) == 1 {\n+ return ep.endpoints[0]\n}\n- if mpep.flags.SharedFlags().ToFlags().Effective().MostRecent {\n- return mpep.endpoints[len(mpep.endpoints)-1]\n+ if ep.flags.SharedFlags().ToFlags().Effective().MostRecent {\n+ return ep.endpoints[len(ep.endpoints)-1]\n}\npayload := []byte{\n@@ -384,8 +394,8 @@ func selectEndpoint(id TransportEndpointID, mpep *multiPortEndpoint, seed uint32\nh.Write([]byte(id.RemoteAddress))\nhash := h.Sum32()\n- idx := reciprocalScale(hash, uint32(len(mpep.endpoints)))\n- return mpep.endpoints[idx]\n+ idx := reciprocalScale(hash, uint32(len(ep.endpoints)))\n+ return ep.endpoints[idx]\n}\nfunc (ep *multiPortEndpoint) handlePacketAll(id TransportEndpointID, pkt *PacketBuffer) {\n@@ -657,7 +667,7 @@ func (d *transportDemuxer) findTransportEndpoint(netProto tcpip.NetworkProtocolN\n}\n}\n- ep := selectEndpoint(id, mpep, epsByNIC.seed)\n+ ep := mpep.selectEndpoint(id, epsByNIC.seed)\nepsByNIC.mu.RUnlock()\nreturn ep\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Checklocks also pointed out a locking violation which is fixed
in this change.
Updates #6566.
PiperOrigin-RevId: 397225322 |
260,004 | 16.09.2021 20:04:00 | 25,200 | b28bd31bb6d920c23b5036d94bc7123143369e24 | Allow creating packet socket bound to any protocol
...even protocols the stack is unaware of.
While I am here, annotate checklocks on stack.packetEndpointList. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -97,6 +97,8 @@ type packetEndpointList struct {\nmu sync.RWMutex\n// eps is protected by mu, but the contained PacketEndpoint values are not.\n+ //\n+ // +checklocks:mu\neps []PacketEndpoint\n}\n@@ -117,6 +119,12 @@ func (p *packetEndpointList) remove(ep PacketEndpoint) {\n}\n}\n+func (p *packetEndpointList) len() int {\n+ p.mu.RLock()\n+ defer p.mu.RUnlock()\n+ return len(p.eps)\n+}\n+\n// forEach calls fn with each endpoints in p while holding the read lock on p.\nfunc (p *packetEndpointList) forEach(fn func(PacketEndpoint)) {\np.mu.RLock()\n@@ -157,14 +165,8 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICC\nresolutionRequired := ep.Capabilities()&CapabilityResolutionRequired != 0\n- // Register supported packet and network endpoint protocols.\n- for _, netProto := range header.Ethertypes {\n- nic.packetEPs.eps[netProto] = new(packetEndpointList)\n- }\nfor _, netProto := range stack.networkProtocols {\nnetNum := netProto.Number()\n- nic.packetEPs.eps[netNum] = new(packetEndpointList)\n-\nnetEP := netProto.NewEndpoint(nic, nic)\nnic.networkEndpoints[netNum] = netEP\n@@ -974,7 +976,8 @@ func (n *nic) registerPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep Pa\neps, ok := n.packetEPs.eps[netProto]\nif !ok {\n- return &tcpip.ErrNotSupported{}\n+ eps = new(packetEndpointList)\n+ n.packetEPs.eps[netProto] = eps\n}\neps.add(ep)\n@@ -990,6 +993,9 @@ func (n *nic) unregisterPacketEndpoint(netProto tcpip.NetworkProtocolNumber, ep\nreturn\n}\neps.remove(ep)\n+ if eps.len() == 0 {\n+ delete(n.packetEPs.eps, netProto)\n+ }\n}\n// isValidForOutgoing returns true if the endpoint can be used to send out a\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -366,6 +366,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:packet_socket_raw_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:packet_socket_test\",\n+)\n+\nsyscall_test(\ntest = \"//test/syscalls/linux:partial_bad_buffer_test\",\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -7,6 +7,7 @@ package(\nexports_files(\n[\n+ \"packet_socket.cc\",\n\"packet_socket_dgram.cc\",\n\"packet_socket_raw.cc\",\n\"raw_socket.cc\",\n@@ -1480,6 +1481,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"packet_socket_test\",\n+ testonly = 1,\n+ srcs = [\"packet_socket.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:socket_util\",\n+ gtest,\n+ \"//test/util:test_main\",\n+ ],\n+)\n+\ncc_binary(\nname = \"pty_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <net/if.h>\n+#include <netinet/if_ether.h>\n+\n+#include <limits>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/socket_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+using ::testing::Combine;\n+using ::testing::Values;\n+\n+class PacketSocketTest : public ::testing::TestWithParam<std::tuple<int, int>> {\n+ protected:\n+ void SetUp() override {\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {\n+ const auto [type, protocol] = GetParam();\n+ ASSERT_THAT(socket(AF_PACKET, type, htons(protocol)),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP() << \"Missing packet socket capability\";\n+ }\n+ }\n+};\n+\n+TEST_P(PacketSocketTest, Create) {\n+ const auto [type, protocol] = GetParam();\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, type, htons(protocol)));\n+ EXPECT_GE(fd.get(), 0);\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketTest,\n+ Combine(Values(SOCK_DGRAM, SOCK_RAW),\n+ Values(0, 1, 255, ETH_P_IP, ETH_P_IPV6,\n+ std::numeric_limits<uint16_t>::max())));\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/capability_util.h",
"new_path": "test/util/capability_util.h",
"diff": "#ifndef GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_\n#define GVISOR_TEST_UTIL_CAPABILITY_UTIL_H_\n+#include \"test/util/posix_error.h\"\n+\n#if defined(__Fuchsia__)\n// Nothing to include.\n#elif defined(__linux__)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow creating packet socket bound to any protocol
...even protocols the stack is unaware of.
While I am here, annotate checklocks on stack.packetEndpointList.
PiperOrigin-RevId: 397226754 |
259,927 | 18.09.2021 05:57:28 | 25,200 | 09477db2bc0535c93a09442c6b5216497b3bc7db | Avoid ambient clock on ICMP Rate Limiter | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/icmp_rate_limit.go",
"new_path": "pkg/tcpip/stack/icmp_rate_limit.go",
"diff": "@@ -16,6 +16,7 @@ package stack\nimport (\n\"golang.org/x/time/rate\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n)\nconst (\n@@ -31,11 +32,41 @@ const (\n// ICMPRateLimiter is a global rate limiter that controls the generation of\n// ICMP messages generated by the stack.\ntype ICMPRateLimiter struct {\n- *rate.Limiter\n+ limiter *rate.Limiter\n+ clock tcpip.Clock\n}\n// NewICMPRateLimiter returns a global rate limiter for controlling the rate\n-// at which ICMP messages are generated by the stack.\n-func NewICMPRateLimiter() *ICMPRateLimiter {\n- return &ICMPRateLimiter{Limiter: rate.NewLimiter(icmpLimit, icmpBurst)}\n+// at which ICMP messages are generated by the stack. The returned limiter\n+// does not apply limits to any ICMP types by default.\n+func NewICMPRateLimiter(clock tcpip.Clock) *ICMPRateLimiter {\n+ return &ICMPRateLimiter{\n+ clock: clock,\n+ limiter: rate.NewLimiter(icmpLimit, icmpBurst),\n+ }\n+}\n+\n+// SetLimit sets a new Limit for the limiter.\n+func (l *ICMPRateLimiter) SetLimit(limit rate.Limit) {\n+ l.limiter.SetLimitAt(l.clock.Now(), limit)\n+}\n+\n+// Limit returns the maximum overall event rate.\n+func (l *ICMPRateLimiter) Limit() rate.Limit {\n+ return l.limiter.Limit()\n+}\n+\n+// SetBurst sets a new burst size for the limiter.\n+func (l *ICMPRateLimiter) SetBurst(burst int) {\n+ l.limiter.SetBurstAt(l.clock.Now(), burst)\n+}\n+\n+// Burst returns the maximum burst size.\n+func (l *ICMPRateLimiter) Burst() int {\n+ return l.limiter.Burst()\n+}\n+\n+// Allow reports whether one ICMP message may be sent now.\n+func (l *ICMPRateLimiter) Allow() bool {\n+ return l.limiter.AllowN(l.clock.Now(), 1)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -375,7 +375,7 @@ func New(opts Options) *Stack {\nstats: opts.Stats.FillIn(),\nhandleLocal: opts.HandleLocal,\ntables: opts.IPTables,\n- icmpRateLimiter: NewICMPRateLimiter(),\n+ icmpRateLimiter: NewICMPRateLimiter(clock),\nseed: seed,\nnudConfigs: opts.NUDConfigs,\nuniqueIDGenerator: opts.UniqueID,\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/BUILD",
"new_path": "pkg/tcpip/transport/udp/BUILD",
"diff": "@@ -63,5 +63,6 @@ go_test(\n\"//pkg/tcpip/transport/icmp\",\n\"//pkg/waiter\",\n\"@com_github_google_go_cmp//cmp:go_default_library\",\n+ \"@org_golang_x_time//rate:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/udp_test.go",
"new_path": "pkg/tcpip/transport/udp/udp_test.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n+ \"golang.org/x/time/rate\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/checker\"\n@@ -313,6 +314,9 @@ func newDualTestContextWithHandleLocal(t *testing.T, mtu uint32, handleLocal boo\nClock: &faketime.NullClock{},\n}\ns := stack.New(options)\n+ // Disable ICMP rate limiter because we're using Null clock, which never advances time and thus\n+ // never allows ICMP messages.\n+ s.SetICMPLimit(rate.Inf)\nep := channel.New(256, mtu, \"\")\nwep := stack.LinkEndpoint(ep)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Avoid ambient clock on ICMP Rate Limiter
PiperOrigin-RevId: 397496920 |
260,004 | 19.09.2021 13:13:29 | 25,200 | 89a0011c100d778cd8a0cc5e1b14996461c66629 | Support IPV6_RECVPKTINFO on UDP sockets | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/socket.go",
"new_path": "pkg/abi/linux/socket.go",
"diff": "@@ -542,6 +542,15 @@ type ControlMessageIPPacketInfo struct {\nDestinationAddr InetAddr\n}\n+// ControlMessageIPv6PacketInfo represents struct in6_pktinfo from linux/ipv6.h.\n+//\n+// +marshal\n+// +stateify savable\n+type ControlMessageIPv6PacketInfo struct {\n+ Addr Inet6Addr\n+ NIC uint32\n+}\n+\n// SizeOfControlMessageCredentials is the binary size of a\n// ControlMessageCredentials struct.\nvar SizeOfControlMessageCredentials = (*ControlMessageCredentials)(nil).SizeBytes()\n@@ -566,6 +575,10 @@ const SizeOfControlMessageTClass = 4\n// control message.\nconst SizeOfControlMessageIPPacketInfo = 12\n+// SizeOfControlMessageIPv6PacketInfo is the size of a\n+// ControlMessageIPv6PacketInfo.\n+const SizeOfControlMessageIPv6PacketInfo = 20\n+\n// SCM_MAX_FD is the maximum number of FDs accepted in a single sendmsg call.\n// From net/scm.h.\nconst SCM_MAX_FD = 253\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/control/control.go",
"new_path": "pkg/sentry/socket/control/control.go",
"diff": "@@ -355,6 +355,17 @@ func PackIPPacketInfo(t *kernel.Task, packetInfo *linux.ControlMessageIPPacketIn\n)\n}\n+// PackIPv6PacketInfo packs an IPV6_PKTINFO socket control message.\n+func PackIPv6PacketInfo(t *kernel.Task, packetInfo *linux.ControlMessageIPv6PacketInfo, buf []byte) []byte {\n+ return putCmsgStruct(\n+ buf,\n+ linux.SOL_IPV6,\n+ linux.IPV6_PKTINFO,\n+ t.Arch().Width(),\n+ packetInfo,\n+ )\n+}\n+\n// PackOriginalDstAddress packs an IP_RECVORIGINALDSTADDR socket control message.\nfunc PackOriginalDstAddress(t *kernel.Task, originalDstAddress linux.SockAddr, buf []byte) []byte {\nvar level uint32\n@@ -412,6 +423,10 @@ func PackControlMessages(t *kernel.Task, cmsgs socket.ControlMessages, buf []byt\nbuf = PackIPPacketInfo(t, &cmsgs.IP.PacketInfo, buf)\n}\n+ if cmsgs.IP.HasIPv6PacketInfo {\n+ buf = PackIPv6PacketInfo(t, &cmsgs.IP.IPv6PacketInfo, buf)\n+ }\n+\nif cmsgs.IP.OriginalDstAddress != nil {\nbuf = PackOriginalDstAddress(t, cmsgs.IP.OriginalDstAddress, buf)\n}\n@@ -453,6 +468,10 @@ func CmsgsSpace(t *kernel.Task, cmsgs socket.ControlMessages) int {\nspace += cmsgSpace(t, linux.SizeOfControlMessageIPPacketInfo)\n}\n+ if cmsgs.IP.HasIPv6PacketInfo {\n+ space += cmsgSpace(t, linux.SizeOfControlMessageIPv6PacketInfo)\n+ }\n+\nif cmsgs.IP.OriginalDstAddress != nil {\nspace += cmsgSpace(t, cmsgs.IP.OriginalDstAddress.SizeBytes())\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netstack/netstack.go",
"new_path": "pkg/sentry/socket/netstack/netstack.go",
"diff": "@@ -1371,6 +1371,14 @@ func getSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nv := primitive.Int32(boolToInt32(ep.SocketOptions().GetReceiveOriginalDstAddress()))\nreturn &v, nil\n+ case linux.IPV6_RECVPKTINFO:\n+ if outLen < sizeOfInt32 {\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ v := primitive.Int32(boolToInt32(ep.SocketOptions().GetIPv6ReceivePacketInfo()))\n+ return &v, nil\n+\ncase linux.IP6T_ORIGINAL_DST:\nif outLen < sockAddrInet6Size {\nreturn nil, syserr.ErrInvalidArgument\n@@ -2127,6 +2135,15 @@ func setSockOptIPv6(t *kernel.Task, s socket.SocketOps, ep commonEndpoint, name\nep.SocketOptions().SetReceiveOriginalDstAddress(v != 0)\nreturn nil\n+ case linux.IPV6_RECVPKTINFO:\n+ if len(optVal) < sizeOfInt32 {\n+ return syserr.ErrInvalidArgument\n+ }\n+ v := int32(hostarch.ByteOrder.Uint32(optVal))\n+\n+ ep.SocketOptions().SetIPv6ReceivePacketInfo(v != 0)\n+ return nil\n+\ncase linux.IPV6_TCLASS:\nif len(optVal) < sizeOfInt32 {\nreturn syserr.ErrInvalidArgument\n@@ -2516,7 +2533,6 @@ func emitUnimplementedEventIPv6(t *kernel.Task, name int) {\nlinux.IPV6_RECVHOPLIMIT,\nlinux.IPV6_RECVHOPOPTS,\nlinux.IPV6_RECVPATHMTU,\n- linux.IPV6_RECVPKTINFO,\nlinux.IPV6_RECVRTHDR,\nlinux.IPV6_RTHDR,\nlinux.IPV6_RTHDRDSTOPTS,\n@@ -2742,6 +2758,8 @@ func (s *socketOpsCommon) controlMessages(cm tcpip.ControlMessages) socket.Contr\nTClass: readCM.TClass,\nHasIPPacketInfo: readCM.HasIPPacketInfo,\nPacketInfo: readCM.PacketInfo,\n+ HasIPv6PacketInfo: readCM.HasIPv6PacketInfo,\n+ IPv6PacketInfo: readCM.IPv6PacketInfo,\nOriginalDstAddress: readCM.OriginalDstAddress,\nSockErr: readCM.SockErr,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/socket.go",
"new_path": "pkg/sentry/socket/socket.go",
"diff": "@@ -56,6 +56,17 @@ func packetInfoToLinux(packetInfo tcpip.IPPacketInfo) linux.ControlMessageIPPack\nreturn p\n}\n+// ipv6PacketInfoToLinux converts IPv6PacketInfo from tcpip format to Linux\n+// format.\n+func ipv6PacketInfoToLinux(packetInfo tcpip.IPv6PacketInfo) linux.ControlMessageIPv6PacketInfo {\n+ var p linux.ControlMessageIPv6PacketInfo\n+ if n := copy(p.Addr[:], []byte(packetInfo.Addr)); n != len(p.Addr) {\n+ panic(fmt.Sprintf(\"got copy(%x, %x) = %d, want = %d\", p.Addr, packetInfo.Addr, n, len(p.Addr)))\n+ }\n+ p.NIC = uint32(packetInfo.NIC)\n+ return p\n+}\n+\n// errOriginToLinux maps tcpip socket origin to Linux socket origin constants.\nfunc errOriginToLinux(origin tcpip.SockErrOrigin) uint8 {\nswitch origin {\n@@ -114,7 +125,7 @@ func NewIPControlMessages(family int, cmgs tcpip.ControlMessages) IPControlMessa\nif cmgs.HasOriginalDstAddress {\norgDstAddr, _ = ConvertAddress(family, cmgs.OriginalDstAddress)\n}\n- return IPControlMessages{\n+ cm := IPControlMessages{\nHasTimestamp: cmgs.HasTimestamp,\nTimestamp: cmgs.Timestamp,\nHasInq: cmgs.HasInq,\n@@ -125,9 +136,16 @@ func NewIPControlMessages(family int, cmgs tcpip.ControlMessages) IPControlMessa\nTClass: cmgs.TClass,\nHasIPPacketInfo: cmgs.HasIPPacketInfo,\nPacketInfo: packetInfoToLinux(cmgs.PacketInfo),\n+ HasIPv6PacketInfo: cmgs.HasIPv6PacketInfo,\nOriginalDstAddress: orgDstAddr,\nSockErr: sockErrCmsgToLinux(cmgs.SockErr),\n}\n+\n+ if cm.HasIPv6PacketInfo {\n+ cm.IPv6PacketInfo = ipv6PacketInfoToLinux(cmgs.IPv6PacketInfo)\n+ }\n+\n+ return cm\n}\n// IPControlMessages contains socket control messages for IP sockets.\n@@ -166,6 +184,12 @@ type IPControlMessages struct {\n// PacketInfo holds interface and address data on an incoming packet.\nPacketInfo linux.ControlMessageIPPacketInfo\n+ // HasIPv6PacketInfo indicates whether IPv6PacketInfo is set.\n+ HasIPv6PacketInfo bool\n+\n+ // PacketInfo holds interface and address data on an incoming packet.\n+ IPv6PacketInfo linux.ControlMessageIPv6PacketInfo\n+\n// OriginalDestinationAddress holds the original destination address\n// and port of the incoming packet.\nOriginalDstAddress linux.SockAddr\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/checker/checker.go",
"new_path": "pkg/tcpip/checker/checker.go",
"diff": "@@ -324,6 +324,19 @@ func ReceiveIPPacketInfo(want tcpip.IPPacketInfo) ControlMessagesChecker {\n}\n}\n+// ReceiveIPv6PacketInfo creates a checker that checks the IPv6PacketInfo field\n+// in ControlMessages.\n+func ReceiveIPv6PacketInfo(want tcpip.IPv6PacketInfo) ControlMessagesChecker {\n+ return func(t *testing.T, cm tcpip.ControlMessages) {\n+ t.Helper()\n+ if !cm.HasIPv6PacketInfo {\n+ t.Errorf(\"got cm.HasIPv6PacketInfo = %t, want = true\", cm.HasIPv6PacketInfo)\n+ } else if diff := cmp.Diff(want, cm.IPv6PacketInfo); diff != \"\" {\n+ t.Errorf(\"IPv6PacketInfo mismatch (-want +got):\\n%s\", diff)\n+ }\n+ }\n+}\n+\n// ReceiveOriginalDstAddr creates a checker that checks the OriginalDstAddress\n// field in ControlMessages.\nfunc ReceiveOriginalDstAddr(want tcpip.FullAddress) ControlMessagesChecker {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/socketops.go",
"new_path": "pkg/tcpip/socketops.go",
"diff": "@@ -170,10 +170,14 @@ type SocketOptions struct {\n// message is passed with incoming packets.\nreceiveTClassEnabled uint32\n- // receivePacketInfoEnabled is used to specify if more inforamtion is\n- // provided with incoming packets such as interface index and address.\n+ // receivePacketInfoEnabled is used to specify if more information is\n+ // provided with incoming IPv4 packets.\nreceivePacketInfoEnabled uint32\n+ // receivePacketInfoEnabled is used to specify if more information is\n+ // provided with incoming IPv6 packets.\n+ receiveIPv6PacketInfoEnabled uint32\n+\n// hdrIncludeEnabled is used to indicate for a raw endpoint that all packets\n// being written have an IP header and the endpoint should not attach an IP\n// header.\n@@ -360,6 +364,16 @@ func (so *SocketOptions) SetReceivePacketInfo(v bool) {\nstoreAtomicBool(&so.receivePacketInfoEnabled, v)\n}\n+// GetIPv6ReceivePacketInfo gets value for IPV6_RECVPKTINFO option.\n+func (so *SocketOptions) GetIPv6ReceivePacketInfo() bool {\n+ return atomic.LoadUint32(&so.receiveIPv6PacketInfoEnabled) != 0\n+}\n+\n+// SetIPv6ReceivePacketInfo sets value for IPV6_RECVPKTINFO option.\n+func (so *SocketOptions) SetIPv6ReceivePacketInfo(v bool) {\n+ storeAtomicBool(&so.receiveIPv6PacketInfoEnabled, v)\n+}\n+\n// GetHeaderIncluded gets value for IP_HDRINCL option.\nfunc (so *SocketOptions) GetHeaderIncluded() bool {\nreturn atomic.LoadUint32(&so.hdrIncludedEnabled) != 0\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -451,6 +451,12 @@ type ControlMessages struct {\n// PacketInfo holds interface and address data on an incoming packet.\nPacketInfo IPPacketInfo\n+ // HasIPv6PacketInfo indicates whether IPv6PacketInfo is set.\n+ HasIPv6PacketInfo bool\n+\n+ // IPv6PacketInfo holds interface and address data on an incoming packet.\n+ IPv6PacketInfo IPv6PacketInfo\n+\n// HasOriginalDestinationAddress indicates whether OriginalDstAddress is\n// set.\nHasOriginalDstAddress bool\n@@ -1164,6 +1170,14 @@ type IPPacketInfo struct {\nDestinationAddr Address\n}\n+// IPv6PacketInfo is the message structure for IPV6_PKTINFO.\n+//\n+// +stateify savable\n+type IPv6PacketInfo struct {\n+ Addr Address\n+ NIC NICID\n+}\n+\n// SendBufferSizeOption is used by stack.(Stack*).Option/SetOption to\n// get/set the default, min and max send buffer sizes.\ntype SendBufferSizeOption struct {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -243,19 +243,29 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\ncm.HasTOS = true\ncm.TOS = p.tos\n}\n+\n+ if e.ops.GetReceivePacketInfo() {\n+ cm.HasIPPacketInfo = true\n+ cm.PacketInfo = p.packetInfo\n+ }\ncase header.IPv6ProtocolNumber:\nif e.ops.GetReceiveTClass() {\ncm.HasTClass = true\n// Although TClass is an 8-bit value it's read in the CMsg as a uint32.\ncm.TClass = uint32(p.tos)\n}\n+\n+ if e.ops.GetIPv6ReceivePacketInfo() {\n+ cm.HasIPv6PacketInfo = true\n+ cm.IPv6PacketInfo = tcpip.IPv6PacketInfo{\n+ NIC: p.packetInfo.NIC,\n+ Addr: p.packetInfo.DestinationAddr,\n+ }\n+ }\ndefault:\npanic(fmt.Sprintf(\"unrecognized network protocol = %d\", p.netProto))\n}\n- if e.ops.GetReceivePacketInfo() {\n- cm.HasIPPacketInfo = true\n- cm.PacketInfo = p.packetInfo\n- }\n+\nif e.ops.GetReceiveOriginalDstAddress() {\ncm.HasOriginalDstAddress = true\ncm.OriginalDstAddress = p.destinationAddress\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/udp_test.go",
"new_path": "pkg/tcpip/transport/udp/udp_test.go",
"diff": "@@ -1372,61 +1372,67 @@ func TestReadIPPacketInfo(t *testing.T) {\nname string\nproto tcpip.NetworkProtocolNumber\nflow testFlow\n- expectedLocalAddr tcpip.Address\n- expectedDestAddr tcpip.Address\n+ checker func(tcpip.NICID) checker.ControlMessagesChecker\n}{\n{\nname: \"IPv4 unicast\",\nproto: header.IPv4ProtocolNumber,\nflow: unicastV4,\n- expectedLocalAddr: stackAddr,\n- expectedDestAddr: stackAddr,\n+ checker: func(id tcpip.NICID) checker.ControlMessagesChecker {\n+ return checker.ReceiveIPPacketInfo(tcpip.IPPacketInfo{\n+ NIC: id,\n+ LocalAddr: stackAddr,\n+ DestinationAddr: stackAddr,\n+ })\n+ },\n},\n{\nname: \"IPv4 multicast\",\nproto: header.IPv4ProtocolNumber,\nflow: multicastV4,\n- // This should actually be a unicast address assigned to the interface.\n- //\n- // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n- // behaviour. We still include the test so that once the bug is\n- // resolved, this test will start to fail and the individual tasked\n- // with fixing this bug knows to also fix this test :).\n- expectedLocalAddr: multicastAddr,\n- expectedDestAddr: multicastAddr,\n+ checker: func(id tcpip.NICID) checker.ControlMessagesChecker {\n+ return checker.ReceiveIPPacketInfo(tcpip.IPPacketInfo{\n+ NIC: id,\n+ // TODO(gvisor.dev/issue/3556): Check for a unicast address.\n+ LocalAddr: multicastAddr,\n+ DestinationAddr: multicastAddr,\n+ })\n+ },\n},\n{\nname: \"IPv4 broadcast\",\nproto: header.IPv4ProtocolNumber,\nflow: broadcast,\n- // This should actually be a unicast address assigned to the interface.\n- //\n- // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n- // behaviour. We still include the test so that once the bug is\n- // resolved, this test will start to fail and the individual tasked\n- // with fixing this bug knows to also fix this test :).\n- expectedLocalAddr: broadcastAddr,\n- expectedDestAddr: broadcastAddr,\n+ checker: func(id tcpip.NICID) checker.ControlMessagesChecker {\n+ return checker.ReceiveIPPacketInfo(tcpip.IPPacketInfo{\n+ NIC: id,\n+ // TODO(gvisor.dev/issue/3556): Check for a unicast address.\n+ LocalAddr: broadcastAddr,\n+ DestinationAddr: broadcastAddr,\n+ })\n+ },\n},\n{\nname: \"IPv6 unicast\",\nproto: header.IPv6ProtocolNumber,\nflow: unicastV6,\n- expectedLocalAddr: stackV6Addr,\n- expectedDestAddr: stackV6Addr,\n+ checker: func(id tcpip.NICID) checker.ControlMessagesChecker {\n+ return checker.ReceiveIPv6PacketInfo(tcpip.IPv6PacketInfo{\n+ NIC: id,\n+ Addr: stackV6Addr,\n+ })\n+ },\n},\n{\nname: \"IPv6 multicast\",\nproto: header.IPv6ProtocolNumber,\nflow: multicastV6,\n- // This should actually be a unicast address assigned to the interface.\n- //\n- // TODO(gvisor.dev/issue/3556): This check is validating incorrect\n- // behaviour. We still include the test so that once the bug is\n- // resolved, this test will start to fail and the individual tasked\n- // with fixing this bug knows to also fix this test :).\n- expectedLocalAddr: multicastV6Addr,\n- expectedDestAddr: multicastV6Addr,\n+ checker: func(id tcpip.NICID) checker.ControlMessagesChecker {\n+ return checker.ReceiveIPv6PacketInfo(tcpip.IPv6PacketInfo{\n+ NIC: id,\n+ Addr: multicastV6Addr,\n+ })\n+ },\n},\n}\n@@ -1449,13 +1455,16 @@ func TestReadIPPacketInfo(t *testing.T) {\n}\n}\n+ switch f := test.flow.netProto(); f {\n+ case header.IPv4ProtocolNumber:\nc.ep.SocketOptions().SetReceivePacketInfo(true)\n+ case header.IPv6ProtocolNumber:\n+ c.ep.SocketOptions().SetIPv6ReceivePacketInfo(true)\n+ default:\n+ t.Fatalf(\"unhandled protocol number = %d\", f)\n+ }\n- testRead(c, test.flow, checker.ReceiveIPPacketInfo(tcpip.IPPacketInfo{\n- NIC: 1,\n- LocalAddr: test.expectedLocalAddr,\n- DestinationAddr: test.expectedDestAddr,\n- }))\n+ testRead(c, test.flow, test.checker(c.nicID))\nif got := c.s.Stats().UDP.PacketsReceived.Value(); got != 1 {\nt.Fatalf(\"Read did not increment PacketsReceived: got = %d, want = 1\", got)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv6_udp_unbound.cc",
"new_path": "test/syscalls/linux/socket_ipv6_udp_unbound.cc",
"diff": "namespace gvisor {\nnamespace testing {\n+using ::testing::IsNull;\n+using ::testing::NotNull;\n+\n+TEST_P(IPv6UDPUnboundSocketTest, IPv6PacketInfo) {\n+ auto sender_socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ auto receiver_socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+\n+ auto sender_addr = V6Loopback();\n+ ASSERT_THAT(bind(sender_socket->get(), AsSockAddr(&sender_addr.addr),\n+ sender_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ auto receiver_addr = V6Loopback();\n+ ASSERT_THAT(bind(receiver_socket->get(), AsSockAddr(&receiver_addr.addr),\n+ receiver_addr.addr_len),\n+ SyscallSucceeds());\n+ socklen_t receiver_addr_len = receiver_addr.addr_len;\n+ ASSERT_THAT(getsockname(receiver_socket->get(),\n+ AsSockAddr(&receiver_addr.addr), &receiver_addr_len),\n+ SyscallSucceeds());\n+ ASSERT_EQ(receiver_addr_len, receiver_addr.addr_len);\n+\n+ // Make sure we get IPv6 packet information as control messages.\n+ constexpr int one = 1;\n+ ASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IPV6, IPV6_RECVPKTINFO,\n+ &one, sizeof(one)),\n+ SyscallSucceeds());\n+\n+ // Send a packet - we don't care about the packet itself, only the returned\n+ // IPV6_PKTINFO control message.\n+ char send_buf[200];\n+ RandomizeBuffer(send_buf, sizeof(send_buf));\n+ ASSERT_THAT(RetryEINTR(sendto)(\n+ sender_socket->get(), send_buf, sizeof(send_buf), 0,\n+ AsSockAddr(&receiver_addr.addr), receiver_addr.addr_len),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Check that we received the packet with the packet information control\n+ // message.\n+ char recv_buf[sizeof(send_buf) + 1];\n+ in6_pktinfo received_pktinfo;\n+ char recv_cmsg_buf[CMSG_SPACE(sizeof(received_pktinfo))];\n+ iovec recv_iov = {\n+ .iov_base = recv_buf,\n+ .iov_len = sizeof(recv_buf),\n+ };\n+ msghdr recv_msg = {\n+ .msg_iov = &recv_iov,\n+ .msg_iovlen = 1,\n+ .msg_control = recv_cmsg_buf,\n+ .msg_controllen = sizeof(recv_cmsg_buf),\n+ };\n+ ASSERT_THAT(\n+ RetryEINTR(recvmsg)(receiver_socket->get(), &recv_msg, 0 /* flags */),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+ EXPECT_EQ(memcmp(send_buf, recv_buf, sizeof(send_buf)), 0);\n+\n+ cmsghdr* cmsg = CMSG_FIRSTHDR(&recv_msg);\n+ ASSERT_THAT(cmsg, NotNull());\n+ EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(in6_pktinfo)));\n+ EXPECT_EQ(cmsg->cmsg_level, IPPROTO_IPV6);\n+ EXPECT_EQ(cmsg->cmsg_type, IPV6_PKTINFO);\n+ // As per cmsg(3) (https://www.man7.org/linux/man-pages/man3/cmsg.3.html),\n+ //\n+ // CMSG_DATA() returns a pointer to the data portion of a cmsghdr. The\n+ // pointer returned cannot be assumed to be suitably aligned for accessing\n+ // arbitrary payload data types. Applications should not cast it to a\n+ // pointer type matching the payload, but should instead use memcpy(3) to\n+ // copy data to or from a suitably declared object.\n+ memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(received_pktinfo));\n+ EXPECT_EQ(\n+ memcmp(&received_pktinfo.ipi6_addr,\n+ &(reinterpret_cast<sockaddr_in6*>(&sender_addr.addr)->sin6_addr),\n+ sizeof(received_pktinfo.ipi6_addr)),\n+ 0);\n+ EXPECT_EQ(received_pktinfo.ipi6_ifindex,\n+ ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));\n+ EXPECT_THAT(CMSG_NXTHDR(&recv_msg, cmsg), IsNull());\n+}\n+\n// Test that socket will receive IP_RECVORIGDSTADDR control message.\nTEST_P(IPv6UDPUnboundSocketTest, SetAndReceiveIPReceiveOrigDstAddr) {\nauto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support IPV6_RECVPKTINFO on UDP sockets
PiperOrigin-RevId: 397631833 |
260,004 | 20.09.2021 12:14:29 | 25,200 | 5951ec5bce17e7696d2fd53ce384839555dd3c79 | Do not allow unbinding network protocol
Once a packet socket is bound to a network protocol, it cannot be
unbound from that protocol; the network protocol binding may only be
updated to a different network protocol.
To comply with Linux. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/packet/endpoint.go",
"new_path": "pkg/tcpip/transport/packet/endpoint.go",
"diff": "@@ -82,11 +82,9 @@ type endpoint struct {\nmu sync.RWMutex `state:\"nosave\"`\n// +checklocks:mu\n- netProto tcpip.NetworkProtocolNumber\n- // +checklocks:mu\nclosed bool\n// +checklocks:mu\n- bound bool\n+ boundNetProto tcpip.NetworkProtocolNumber\n// +checklocks:mu\nboundNIC tcpip.NICID\n@@ -100,7 +98,7 @@ func NewEndpoint(s *stack.Stack, cooked bool, netProto tcpip.NetworkProtocolNumb\nep := &endpoint{\nstack: s,\ncooked: cooked,\n- netProto: netProto,\n+ boundNetProto: netProto,\nwaiterQueue: waiterQueue,\n}\nep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n@@ -137,7 +135,7 @@ func (ep *endpoint) Close() {\nreturn\n}\n- ep.stack.UnregisterPacketEndpoint(0, ep.netProto, ep)\n+ ep.stack.UnregisterPacketEndpoint(ep.boundNIC, ep.boundNetProto, ep)\nep.rcvMu.Lock()\ndefer ep.rcvMu.Unlock()\n@@ -150,7 +148,6 @@ func (ep *endpoint) Close() {\n}\nep.closed = true\n- ep.bound = false\nep.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)\n}\n@@ -211,7 +208,7 @@ func (ep *endpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tc\nep.mu.Lock()\nclosed := ep.closed\nnicID := ep.boundNIC\n- proto := ep.netProto\n+ proto := ep.boundNetProto\nep.mu.Unlock()\nif closed {\nreturn 0, &tcpip.ErrClosedForSend{}\n@@ -294,24 +291,29 @@ func (ep *endpoint) Bind(addr tcpip.FullAddress) tcpip.Error {\ndefer ep.mu.Unlock()\nnetProto := tcpip.NetworkProtocolNumber(addr.Port)\n- if ep.bound && ep.boundNIC == addr.NIC && ep.netProto == netProto {\n- // If the NIC being bound is the same then just return success.\n+ if netProto == 0 {\n+ // Do not allow unbinding the network protocol.\n+ netProto = ep.boundNetProto\n+ }\n+\n+ if ep.boundNIC == addr.NIC && ep.boundNetProto == netProto {\n+ // Already bound to the requested NIC and network protocol.\nreturn nil\n}\n- // Unregister endpoint with all the nics.\n- ep.stack.UnregisterPacketEndpoint(0, ep.netProto, ep)\n- ep.bound = false\n+ // TODO(https://gvisor.dev/issue/6618): Unregister after registering the new\n+ // binding.\n+ ep.stack.UnregisterPacketEndpoint(ep.boundNIC, ep.boundNetProto, ep)\n+ ep.boundNIC = 0\n+ ep.boundNetProto = 0\n// Bind endpoint to receive packets from specific interface.\nif err := ep.stack.RegisterPacketEndpoint(addr.NIC, netProto, ep); err != nil {\nreturn err\n}\n- ep.bound = true\nep.boundNIC = addr.NIC\n- ep.netProto = netProto\n-\n+ ep.boundNetProto = netProto\nreturn nil\n}\n@@ -473,7 +475,7 @@ func (*endpoint) State() uint32 {\nfunc (ep *endpoint) Info() tcpip.EndpointInfo {\nep.mu.RLock()\ndefer ep.mu.RUnlock()\n- return &stack.TransportEndpointInfo{NetProto: ep.netProto}\n+ return &stack.TransportEndpointInfo{NetProto: ep.boundNetProto}\n}\n// Stats returns a pointer to the endpoint stats.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/packet/endpoint_state.go",
"new_path": "pkg/tcpip/transport/packet/endpoint_state.go",
"diff": "package packet\nimport (\n+ \"fmt\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n@@ -57,9 +58,8 @@ func (ep *endpoint) afterLoad() {\nep.stack = stack.StackFromEnv\nep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n- // TODO(gvisor.dev/173): Once bind is supported, choose the right NIC.\n- if err := ep.stack.RegisterPacketEndpoint(0, ep.netProto, ep); err != nil {\n- panic(err)\n+ if err := ep.stack.RegisterPacketEndpoint(ep.boundNIC, ep.boundNetProto, ep); err != nil {\n+ panic(fmt.Sprintf(\"RegisterPacketEndpoint(%d, %d, _): %s\", ep.boundNIC, ep.boundNetProto, err))\n}\nep.rcvMu.Lock()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -214,6 +214,11 @@ TEST_P(PacketSocketTest, RebindProtocol) {\nASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(ETH_P_IP));\nASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));\nASSERT_NO_FATAL_FAILURE(test_recv(counter));\n+\n+ // A zero valued protocol number should not change the bound network protocol.\n+ ASSERT_NO_FATAL_FAILURE(bind_to_network_protocol(0));\n+ ASSERT_NO_FATAL_FAILURE(send_udp_message(++counter));\n+ ASSERT_NO_FATAL_FAILURE(test_recv(counter));\n}\nINSTANTIATE_TEST_SUITE_P(AllPacketSocketTests, PacketSocketTest,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Do not allow unbinding network protocol
Once a packet socket is bound to a network protocol, it cannot be
unbound from that protocol; the network protocol binding may only be
updated to a different network protocol.
To comply with Linux.
PiperOrigin-RevId: 397810878 |
260,004 | 20.09.2021 19:35:51 | 25,200 | 3fe8d7ecf193b4efd099ceabe2d39a119ffe4fbc | Support getsockname for packet sockets
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/packet/endpoint.go",
"new_path": "pkg/tcpip/transport/packet/endpoint.go",
"diff": "@@ -318,8 +318,14 @@ func (ep *endpoint) Bind(addr tcpip.FullAddress) tcpip.Error {\n}\n// GetLocalAddress implements tcpip.Endpoint.GetLocalAddress.\n-func (*endpoint) GetLocalAddress() (tcpip.FullAddress, tcpip.Error) {\n- return tcpip.FullAddress{}, &tcpip.ErrNotSupported{}\n+func (ep *endpoint) GetLocalAddress() (tcpip.FullAddress, tcpip.Error) {\n+ ep.mu.RLock()\n+ defer ep.mu.RUnlock()\n+\n+ return tcpip.FullAddress{\n+ NIC: ep.boundNIC,\n+ Port: uint16(ep.boundNetProto),\n+ }, nil\n}\n// GetRemoteAddress implements tcpip.Endpoint.GetRemoteAddress.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -77,6 +77,68 @@ class PacketSocketTest : public ::testing::TestWithParam<int> {\nFileDescriptor socket_;\n};\n+TEST_P(PacketSocketTest, GetSockName) {\n+ {\n+ // First check the local address of an unbound packet socket.\n+ sockaddr_ll addr;\n+ socklen_t addrlen = sizeof(addr);\n+ ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),\n+ &addrlen),\n+ SyscallSucceeds());\n+ // sockaddr_ll ends with an 8 byte physical address field, but only the\n+ // bytes that are used in the sockaddr_ll.sll_addr field are included in the\n+ // address length. Seems Linux used to return the size of sockaddr_ll, but\n+ // https://github.com/torvalds/linux/commit/0fb375fb9b93b7d822debc6a734052337ccfdb1f\n+ // changed things to only return `sizeof(sockaddr_ll) + sll.sll_addr`.\n+ ASSERT_THAT(addrlen, AnyOf(Eq(sizeof(addr)),\n+ Eq(sizeof(addr) - sizeof(addr.sll_addr))));\n+ EXPECT_EQ(addr.sll_family, AF_PACKET);\n+ EXPECT_EQ(addr.sll_ifindex, 0);\n+ if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {\n+ // TODO(https://gvisor.dev/issue/6530): Do not assume all interfaces have\n+ // an ethernet address.\n+ EXPECT_EQ(addr.sll_halen, ETH_ALEN);\n+ } else {\n+ EXPECT_EQ(addr.sll_halen, 0);\n+ }\n+ EXPECT_EQ(ntohs(addr.sll_protocol), 0);\n+ EXPECT_EQ(addr.sll_hatype, 0);\n+ }\n+ // Next we bind the socket to loopback before checking the local address.\n+ const sockaddr_ll bind_addr = {\n+ .sll_family = AF_PACKET,\n+ .sll_protocol = htons(ETH_P_IP),\n+ .sll_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()),\n+ };\n+ ASSERT_THAT(bind(socket_.get(), reinterpret_cast<const sockaddr*>(&bind_addr),\n+ sizeof(bind_addr)),\n+ SyscallSucceeds());\n+ {\n+ sockaddr_ll addr;\n+ socklen_t addrlen = sizeof(addr);\n+ ASSERT_THAT(getsockname(socket_.get(), reinterpret_cast<sockaddr*>(&addr),\n+ &addrlen),\n+ SyscallSucceeds());\n+ ASSERT_THAT(addrlen,\n+ AnyOf(Eq(sizeof(addr)),\n+ Eq(sizeof(addr) - sizeof(addr.sll_addr) + ETH_ALEN)));\n+ EXPECT_EQ(addr.sll_family, AF_PACKET);\n+ EXPECT_EQ(addr.sll_ifindex, bind_addr.sll_ifindex);\n+ EXPECT_EQ(addr.sll_halen, ETH_ALEN);\n+ // Bound to loopback which has the all zeroes address.\n+ for (int i = 0; i < addr.sll_halen; ++i) {\n+ EXPECT_EQ(addr.sll_addr[i], 0) << \"byte mismatch @ idx = \" << i;\n+ }\n+ EXPECT_EQ(ntohs(addr.sll_protocol), htons(addr.sll_protocol));\n+ if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {\n+ // TODO(https://gvisor.dev/issue/6621): Support populating sll_hatype.\n+ EXPECT_EQ(addr.sll_hatype, 0);\n+ } else {\n+ EXPECT_EQ(addr.sll_hatype, ARPHRD_LOOPBACK);\n+ }\n+ }\n+}\n+\nTEST_P(PacketSocketTest, RebindProtocol) {\nconst bool kEthHdrIncluded = GetParam() == SOCK_RAW;\n@@ -162,10 +224,9 @@ TEST_P(PacketSocketTest, RebindProtocol) {\n// addresses only use 6 bytes. Linux used to return sizeof(sockaddr_ll)-2\n// here, but returns sizeof(sockaddr_ll) since\n// https://github.com/torvalds/linux/commit/b2cf86e1563e33a14a1c69b3e508d15dc12f804c.\n- ASSERT_THAT(src_len, ::testing::AnyOf(\n- ::testing::Eq(sizeof(src)),\n- ::testing::Eq(sizeof(src) - sizeof(src.sll_addr) +\n- ETH_ALEN)));\n+ ASSERT_THAT(src_len,\n+ AnyOf(Eq(sizeof(src)),\n+ Eq(sizeof(src) - sizeof(src.sll_addr) + ETH_ALEN)));\nEXPECT_EQ(src.sll_family, AF_PACKET);\nEXPECT_EQ(src.sll_ifindex, loopback_index);\nEXPECT_EQ(src.sll_halen, ETH_ALEN);\n"
}
] | Go | Apache License 2.0 | google/gvisor | Support getsockname for packet sockets
Updates #6621
PiperOrigin-RevId: 397898852 |
259,853 | 21.09.2021 15:37:08 | 25,200 | c485602ded3982f8fd1078e34a4b298879f1807e | socket/unix: clean up socket queue after releasing a queue lock
A socket queue can contain sockets (others and this one). We have to avoid
taking locks of the same class where it is possible. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/queue.go",
"new_path": "pkg/sentry/socket/unix/transport/queue.go",
"diff": "@@ -59,12 +59,14 @@ func (q *queue) Close() {\n// q.WriterQueue.Notify(waiter.WritableEvents)\nfunc (q *queue) Reset(ctx context.Context) {\nq.mu.Lock()\n- for cur := q.dataList.Front(); cur != nil; cur = cur.Next() {\n- cur.Release(ctx)\n- }\n+ dataList := q.dataList\nq.dataList.Reset()\nq.used = 0\nq.mu.Unlock()\n+\n+ for cur := dataList.Front(); cur != nil; cur = cur.Next() {\n+ cur.Release(ctx)\n+ }\n}\n// DecRef implements RefCounter.DecRef.\n"
}
] | Go | Apache License 2.0 | google/gvisor | socket/unix: clean up socket queue after releasing a queue lock
A socket queue can contain sockets (others and this one). We have to avoid
taking locks of the same class where it is possible.
PiperOrigin-RevId: 398100744 |
259,951 | 21.09.2021 17:27:27 | 25,200 | 0ed53e5e92a065f63864ecfd0dd6d93c12daaef5 | Handle Shutdown on connecting tcp socket
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/connect.go",
"new_path": "pkg/tcpip/transport/tcp/connect.go",
"diff": "@@ -30,6 +30,10 @@ import (\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n+// InitialRTO is the initial retransmission timeout.\n+// https://github.com/torvalds/linux/blob/7c636d4d20f/include/net/tcp.h#L142\n+const InitialRTO = time.Second\n+\n// maxSegmentsPerWake is the maximum number of segments to process in the main\n// protocol goroutine per wake-up. Yielding [after this number of segments are\n// processed] allows other events to be processed as well (e.g., timeouts,\n@@ -532,7 +536,7 @@ func (h *handshake) complete() tcpip.Error {\ndefer s.Done()\n// Initialize the resend timer.\n- timer, err := newBackoffTimer(h.ep.stack.Clock(), time.Second, MaxRTO, resendWaker.Assert)\n+ timer, err := newBackoffTimer(h.ep.stack.Clock(), InitialRTO, MaxRTO, resendWaker.Assert)\nif err != nil {\nreturn err\n}\n@@ -578,6 +582,9 @@ func (h *handshake) complete() tcpip.Error {\nif (n¬ifyClose)|(n¬ifyAbort) != 0 {\nreturn &tcpip.ErrAborted{}\n}\n+ if n¬ifyShutdown != 0 {\n+ return &tcpip.ErrConnectionReset{}\n+ }\nif n¬ifyDrain != 0 {\nfor !h.ep.segmentQueue.empty() {\ns := h.ep.segmentQueue.dequeue()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -187,6 +187,8 @@ const (\n// say TIME_WAIT.\nnotifyTickleWorker\nnotifyError\n+ // notifyShutdown means that a connecting socket was shutdown.\n+ notifyShutdown\n)\n// SACKInfo holds TCP SACK related information for a given endpoint.\n@@ -2384,6 +2386,18 @@ func (*endpoint) ConnectEndpoint(tcpip.Endpoint) tcpip.Error {\nfunc (e *endpoint) Shutdown(flags tcpip.ShutdownFlags) tcpip.Error {\ne.LockUser()\ndefer e.UnlockUser()\n+\n+ if e.EndpointState().connecting() {\n+ // When calling shutdown(2) on a connecting socket, the endpoint must\n+ // enter the error state. But this logic cannot belong to the shutdownLocked\n+ // method because that method is called during a close(2) (and closing a\n+ // connecting socket is not an error).\n+ e.resetConnectionLocked(&tcpip.ErrConnectionReset{})\n+ e.notifyProtocolGoroutine(notifyShutdown)\n+ e.waiterQueue.Notify(waiter.WritableEvents | waiter.EventHUp | waiter.EventErr)\n+ return nil\n+ }\n+\nreturn e.shutdownLocked(flags)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/segment_test.go",
"new_path": "pkg/tcpip/transport/tcp/segment_test.go",
"diff": "@@ -34,7 +34,7 @@ func checkSegmentSize(t *testing.T, name string, seg *segment, want segmentSizeW\nDataSize: seg.data.Size(),\nSegMemSize: seg.segMemSize(),\n}\n- if diff := cmp.Diff(got, want); diff != \"\" {\n+ if diff := cmp.Diff(want, got); diff != \"\" {\nt.Errorf(\"%s differs (-want +got):\\n%s\", name, diff)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"new_path": "pkg/tcpip/transport/tcp/tcp_test.go",
"diff": "@@ -1656,6 +1656,71 @@ func TestConnectBindToDevice(t *testing.T) {\n}\n}\n+func TestShutdownConnectingSocket(t *testing.T) {\n+ for _, test := range []struct {\n+ name string\n+ shutdownMode tcpip.ShutdownFlags\n+ }{\n+ {\"ShutdownRead\", tcpip.ShutdownRead},\n+ {\"ShutdownWrite\", tcpip.ShutdownWrite},\n+ {\"ShutdownReadWrite\", tcpip.ShutdownRead | tcpip.ShutdownWrite},\n+ } {\n+ t.Run(test.name, func(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ // Create an endpoint, don't handshake because we want to interfere with\n+ // the handshake process.\n+ c.Create(-1)\n+\n+ waitEntry, ch := waiter.NewChannelEntry(nil)\n+ c.WQ.EventRegister(&waitEntry, waiter.EventHUp)\n+ defer c.WQ.EventUnregister(&waitEntry)\n+\n+ // Start connection attempt.\n+ addr := tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort}\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, c.EP.Connect(addr)); d != \"\" {\n+ t.Fatalf(\"Connect(...) mismatch (-want +got):\\n%s\", d)\n+ }\n+\n+ // Check the SYN packet.\n+ b := c.GetPacket()\n+ checker.IPv4(t, b,\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.TCPFlags(header.TCPFlagSyn),\n+ ),\n+ )\n+\n+ if got, want := tcp.EndpointState(c.EP.State()), tcp.StateSynSent; got != want {\n+ t.Fatalf(\"got State() = %s, want %s\", got, want)\n+ }\n+\n+ if err := c.EP.Shutdown(test.shutdownMode); err != nil {\n+ t.Fatalf(\"Shutdown failed: %s\", err)\n+ }\n+\n+ // The endpoint internal state is updated immediately.\n+ if got, want := tcp.EndpointState(c.EP.State()), tcp.StateError; got != want {\n+ t.Fatalf(\"got State() = %s, want %s\", got, want)\n+ }\n+\n+ select {\n+ case <-ch:\n+ default:\n+ t.Fatal(\"endpoint was not notified\")\n+ }\n+\n+ ept := endpointTester{c.EP}\n+ ept.CheckReadError(t, &tcpip.ErrConnectionReset{})\n+\n+ // If the endpoint is not properly shutdown, it'll re-attempt to connect\n+ // by sending another ACK packet.\n+ c.CheckNoPacketTimeout(\"got an unexpected packet\", tcp.InitialRTO+(500*time.Millisecond))\n+ })\n+ }\n+}\n+\nfunc TestSynSent(t *testing.T) {\nfor _, test := range []struct {\nname string\n@@ -1679,7 +1744,7 @@ func TestSynSent(t *testing.T) {\naddr := tcpip.FullAddress{Addr: context.TestAddr, Port: context.TestPort}\nerr := c.EP.Connect(addr)\n- if d := cmp.Diff(err, &tcpip.ErrConnectStarted{}); d != \"\" {\n+ if d := cmp.Diff(&tcpip.ErrConnectStarted{}, err); d != \"\" {\nt.Fatalf(\"Connect(...) mismatch (-want +got):\\n%s\", d)\n}\n@@ -1995,7 +2060,9 @@ func TestRstOnCloseWithUnreadDataFinConvertRst(t *testing.T) {\n)\n// Cause a FIN to be generated.\n- c.EP.Shutdown(tcpip.ShutdownWrite)\n+ if err := c.EP.Shutdown(tcpip.ShutdownWrite); err != nil {\n+ t.Fatalf(\"Shutdown failed: %s\", err)\n+ }\n// Make sure we get the FIN but DON't ACK IT.\nchecker.IPv4(t, c.GetPacket(),\n@@ -2011,7 +2078,9 @@ func TestRstOnCloseWithUnreadDataFinConvertRst(t *testing.T) {\n// Cause a RST to be generated by closing the read end now since we have\n// unread data.\n- c.EP.Shutdown(tcpip.ShutdownRead)\n+ if err := c.EP.Shutdown(tcpip.ShutdownRead); err != nil {\n+ t.Fatalf(\"Shutdown failed: %s\", err)\n+ }\n// Make sure we get the RST\nchecker.IPv4(t, c.GetPacket(),\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -2067,6 +2067,69 @@ TEST_P(SimpleTcpSocketTest, GetSocketAcceptConnWithShutdown) {\nEXPECT_EQ(got, 0);\n}\n+void ShutdownConnectingSocket(int domain, int shutdown_mode) {\n+ FileDescriptor bound_s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(domain, SOCK_STREAM, IPPROTO_TCP));\n+\n+ sockaddr_storage bound_addr =\n+ ASSERT_NO_ERRNO_AND_VALUE(InetLoopbackAddr(domain));\n+ socklen_t bound_addrlen = sizeof(bound_addr);\n+\n+ ASSERT_THAT(bind(bound_s.get(), AsSockAddr(&bound_addr), bound_addrlen),\n+ SyscallSucceeds());\n+\n+ // Start listening. Use a zero backlog to only allow one connection in the\n+ // accept queue.\n+ ASSERT_THAT(listen(bound_s.get(), 0), SyscallSucceeds());\n+\n+ // Get the addresses the socket is bound to because the port is chosen by the\n+ // stack.\n+ ASSERT_THAT(\n+ getsockname(bound_s.get(), AsSockAddr(&bound_addr), &bound_addrlen),\n+ SyscallSucceeds());\n+\n+ // Establish a connection. But do not accept it. That way, subsequent\n+ // connections will not get a SYN-ACK because the queue is full.\n+ FileDescriptor connected_s =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(domain, SOCK_STREAM, IPPROTO_TCP));\n+ ASSERT_THAT(connect(connected_s.get(),\n+ reinterpret_cast<const struct sockaddr*>(&bound_addr),\n+ bound_addrlen),\n+ SyscallSucceeds());\n+\n+ FileDescriptor connecting_s = ASSERT_NO_ERRNO_AND_VALUE(\n+ Socket(domain, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));\n+ ASSERT_THAT(connect(connecting_s.get(),\n+ reinterpret_cast<const struct sockaddr*>(&bound_addr),\n+ bound_addrlen),\n+ SyscallFailsWithErrno(EINPROGRESS));\n+\n+ // Now the test: when a connecting socket is shutdown, the socket should enter\n+ // an error state.\n+ EXPECT_THAT(shutdown(connecting_s.get(), shutdown_mode), SyscallSucceeds());\n+\n+ // We don't need to specify any events to get POLLHUP or POLLERR because these\n+ // are always tracked.\n+ struct pollfd poll_fd = {\n+ .fd = connecting_s.get(),\n+ };\n+\n+ EXPECT_THAT(RetryEINTR(poll)(&poll_fd, 1, 0), SyscallSucceedsWithValue(1));\n+ EXPECT_EQ(poll_fd.revents, POLLHUP | POLLERR);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, ShutdownReadConnectingSocket) {\n+ ShutdownConnectingSocket(GetParam(), SHUT_RD);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, ShutdownWriteConnectingSocket) {\n+ ShutdownConnectingSocket(GetParam(), SHUT_WR);\n+}\n+\n+TEST_P(SimpleTcpSocketTest, ShutdownReadWriteConnectingSocket) {\n+ ShutdownConnectingSocket(GetParam(), SHUT_RDWR);\n+}\n+\n// Tests that connecting to an unspecified address results in ECONNREFUSED.\nTEST_P(SimpleTcpSocketTest, ConnectUnspecifiedAddress) {\nsockaddr_storage addr;\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle Shutdown on connecting tcp socket
Fixes #6495
PiperOrigin-RevId: 398121921 |
259,992 | 22.09.2021 11:29:38 | 25,200 | cc095a6e4c26c6a818e92a7d1f5d2b59c2a2e163 | Remove terminal usage from `runsc spec`
Most usages of `runsc spec`+`runsc run` do not expect stdios to be a terminal.
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/spec.go",
"new_path": "runsc/cmd/spec.go",
"diff": "@@ -30,7 +30,6 @@ func writeSpec(w io.Writer, cwd string, netns string, args []string) error {\nspec := &specs.Spec{\nVersion: \"1.0.0\",\nProcess: &specs.Process{\n- Terminal: true,\nUser: specs.User{\nUID: 0,\nGID: 0,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove terminal usage from `runsc spec`
Most usages of `runsc spec`+`runsc run` do not expect stdios to be a terminal.
Updates #6619
PiperOrigin-RevId: 398288237 |
259,853 | 16.09.2021 22:52:17 | 0 | c1a726e8c5b751ab71500302d5700a9472c5cbd5 | kvm: fix tests on arm64 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/testutil/testutil_arm64.go",
"new_path": "pkg/sentry/platform/kvm/testutil/testutil_arm64.go",
"diff": "@@ -30,8 +30,8 @@ import (\nfunc TLSWorks() bool\n// SetTestTarget sets the rip appropriately.\n-func SetTestTarget(regs *arch.Registers, fn func()) {\n- regs.Pc = uint64(reflect.ValueOf(fn).Pointer())\n+func SetTestTarget(regs *arch.Registers, fn uintptr) {\n+ regs.Pc = uint64(fn)\n}\n// SetTouchTarget sets rax appropriately.\n"
}
] | Go | Apache License 2.0 | google/gvisor | kvm: fix tests on arm64 |
259,946 | 22.09.2021 14:56:26 | 25,200 | 4f67756752002dc72bb64cdecd1fa17746f8217f | Change EcdsaVerify to specifically P-384 and compute the SHA384 digest. | [
{
"change_type": "MODIFY",
"old_path": "pkg/crypto/crypto_stdlib.go",
"new_path": "pkg/crypto/crypto_stdlib.go",
"diff": "@@ -19,14 +19,21 @@ package crypto\nimport (\n\"crypto/ecdsa\"\n+ \"crypto/elliptic\"\n\"crypto/sha512\"\n+ \"fmt\"\n\"math/big\"\n)\n-// EcdsaVerify verifies the signature in r, s of hash using ECDSA and the\n-// public key, pub. Its return value records whether the signature is valid.\n-func EcdsaVerify(pub *ecdsa.PublicKey, hash []byte, r, s *big.Int) (bool, error) {\n- return ecdsa.Verify(pub, hash, r, s), nil\n+// EcdsaP384Sha384Verify verifies the signature in r, s of hash using ECDSA\n+// P384 + SHA 384 and the public key, pub. Its return value records whether\n+// the signature is valid.\n+func EcdsaP384Sha384Verify(pub *ecdsa.PublicKey, data []byte, r, s *big.Int) (bool, error) {\n+ if pub.Curve != elliptic.P384() {\n+ return false, fmt.Errorf(\"unsupported key curve: want P-384, got %v\", pub.Curve)\n+ }\n+ digest := sha512.Sum384(data)\n+ return ecdsa.Verify(pub, digest[:], r, s), nil\n}\n// SumSha384 returns the SHA384 checksum of the data.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change EcdsaVerify to specifically P-384 and compute the SHA384 digest.
PiperOrigin-RevId: 398336708 |
259,868 | 22.09.2021 17:12:57 | 25,200 | 6b7f58b2ac084088c8ef37ce041262be710404b1 | Add `NewCondition` helper in `bigquery.go`. | [
{
"change_type": "MODIFY",
"old_path": "tools/bigquery/bigquery.go",
"new_path": "tools/bigquery/bigquery.go",
"diff": "@@ -107,10 +107,7 @@ func (bm *Benchmark) AddMetric(metricName, unit string, sample float64) {\n// AddCondition adds a condition to an existing Benchmark.\nfunc (bm *Benchmark) AddCondition(name, value string) {\n- bm.Condition = append(bm.Condition, &Condition{\n- Name: name,\n- Value: value,\n- })\n+ bm.Condition = append(bm.Condition, NewCondition(name, value))\n}\n// NewBenchmark initializes a new benchmark.\n@@ -136,6 +133,14 @@ type Condition struct {\nValue string `bq:\"value\"`\n}\n+// NewCondition returns a new Condition with the given name and value.\n+func NewCondition(name, value string) *Condition {\n+ return &Condition{\n+ Name: name,\n+ Value: value,\n+ }\n+}\n+\nfunc (c *Condition) String() string {\nreturn fmt.Sprintf(\"Condition:\\nName: %s Value: %s\\n\", c.Name, c.Value)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add `NewCondition` helper in `bigquery.go`.
PiperOrigin-RevId: 398366805 |
259,868 | 22.09.2021 17:47:45 | 25,200 | 440fc07f70203caf517c5cbc3dcc3e83b7de3f05 | Make benchmark `String()` output prettier. | [
{
"change_type": "MODIFY",
"old_path": "tools/bigquery/bigquery.go",
"new_path": "tools/bigquery/bigquery.go",
"diff": "@@ -40,29 +40,45 @@ type Suite struct {\n}\nfunc (s *Suite) String() string {\n- conditions := make([]string, 0, len(s.Conditions))\n- for _, c := range s.Conditions {\n- conditions = append(conditions, c.String())\n- }\n- benchmarks := make([]string, 0, len(s.Benchmarks))\n- for _, b := range s.Benchmarks {\n- benchmarks = append(benchmarks, b.String())\n+ var sb strings.Builder\n+ s.debugString(&sb, \"\")\n+ return sb.String()\n}\n- format := `Suite:\n-Name: %s\n-Conditions: %s\n-Benchmarks: %s\n-Official: %t\n-Timestamp: %s\n-`\n+// writeLine writes a line of text to the given string builder with a prefix.\n+func writeLine(sb *strings.Builder, prefix string, format string, values ...interface{}) {\n+ if prefix != \"\" {\n+ sb.WriteString(prefix)\n+ }\n+ sb.WriteString(fmt.Sprintf(format, values...))\n+ sb.WriteString(\"\\n\")\n+}\n- return fmt.Sprintf(format,\n- s.Name,\n- strings.Join(conditions, \"\\n\"),\n- strings.Join(benchmarks, \"\\n\"),\n- s.Official,\n- s.Timestamp)\n+// debugString writes debug information to the given string builder with the\n+// given prefix.\n+func (s *Suite) debugString(sb *strings.Builder, prefix string) {\n+ writeLine(sb, prefix, \"Benchmark suite %s:\", s.Name)\n+ writeLine(sb, prefix, \"Timestamp: %v\", s.Timestamp)\n+ if !s.Official {\n+ writeLine(sb, prefix, \" **** NOTE: Data is not official. **** \")\n+ }\n+ if numConditions := len(s.Conditions); numConditions == 0 {\n+ writeLine(sb, prefix, \"Conditions: None.\")\n+ } else {\n+ writeLine(sb, prefix, \"Conditions (%d):\", numConditions)\n+ for _, condition := range s.Conditions {\n+ condition.debugString(sb, prefix+\" \")\n+ }\n+ }\n+ if numBenchmarks := len(s.Benchmarks); numBenchmarks == 0 {\n+ writeLine(sb, prefix, \"Benchmarks: None.\")\n+ } else {\n+ writeLine(sb, prefix, \"Benchmarks (%d):\", numBenchmarks)\n+ for _, benchmark := range s.Benchmarks {\n+ benchmark.debugString(sb, prefix+\" \")\n+ }\n+ }\n+ sb.WriteString(fmt.Sprintf(\"End of data for benchmark suite %s.\", s.Name))\n}\n// Benchmark represents an individual benchmark in a suite.\n@@ -74,25 +90,31 @@ type Benchmark struct {\n// String implements the String method for Benchmark\nfunc (bm *Benchmark) String() string {\n- conditions := make([]string, 0, len(bm.Condition))\n- for _, c := range bm.Condition {\n- conditions = append(conditions, c.String())\n- }\n- metrics := make([]string, 0, len(bm.Metric))\n- for _, m := range bm.Metric {\n- metrics = append(metrics, m.String())\n+ var sb strings.Builder\n+ bm.debugString(&sb, \"\")\n+ return sb.String()\n}\n- format := `Condition:\n-Name: %s\n-Conditions: %s\n-Metrics: %s\n-`\n-\n- return fmt.Sprintf(format,\n- bm.Name,\n- strings.Join(conditions, \"\\n\"),\n- strings.Join(metrics, \"\\n\"))\n+// debugString writes debug information to the given string builder with the\n+// given prefix.\n+func (bm *Benchmark) debugString(sb *strings.Builder, prefix string) {\n+ writeLine(sb, prefix, \"Benchmark: %s\", bm.Name)\n+ if numConditions := len(bm.Condition); numConditions == 0 {\n+ writeLine(sb, prefix, \" Conditions: None.\")\n+ } else {\n+ writeLine(sb, prefix, \" Conditions (%d):\", numConditions)\n+ for _, condition := range bm.Condition {\n+ condition.debugString(sb, prefix+\" \")\n+ }\n+ }\n+ if numMetrics := len(bm.Metric); numMetrics == 0 {\n+ writeLine(sb, prefix, \" Metrics: None.\")\n+ } else {\n+ writeLine(sb, prefix, \" Metrics (%d):\", numMetrics)\n+ for _, metric := range bm.Metric {\n+ metric.debugString(sb, prefix+\" \")\n+ }\n+ }\n}\n// AddMetric adds a metric to an existing Benchmark.\n@@ -142,7 +164,15 @@ func NewCondition(name, value string) *Condition {\n}\nfunc (c *Condition) String() string {\n- return fmt.Sprintf(\"Condition:\\nName: %s Value: %s\\n\", c.Name, c.Value)\n+ var sb strings.Builder\n+ c.debugString(&sb, \"\")\n+ return sb.String()\n+}\n+\n+// debugString writes debug information to the given string builder with the\n+// given prefix.\n+func (c *Condition) debugString(sb *strings.Builder, prefix string) {\n+ writeLine(sb, prefix, \"Condition: %s = %s\", c.Name, c.Value)\n}\n// Metric holds the actual metric data and unit information for this benchmark.\n@@ -153,7 +183,15 @@ type Metric struct {\n}\nfunc (m *Metric) String() string {\n- return fmt.Sprintf(\"Metric:\\nName: %s Unit: %s Sample: %e\\n\", m.Name, m.Unit, m.Sample)\n+ var sb strings.Builder\n+ m.debugString(&sb, \"\")\n+ return sb.String()\n+}\n+\n+// debugString writes debug information to the given string builder with the\n+// given prefix.\n+func (m *Metric) debugString(sb *strings.Builder, prefix string) {\n+ writeLine(sb, prefix, \"Metric %s: %f %s\", m.Name, m.Sample, m.Unit)\n}\n// InitBigQuery initializes a BigQuery dataset/table in the project. If the dataset/table already exists, it is not duplicated.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make benchmark `String()` output prettier.
PiperOrigin-RevId: 398372542 |
260,004 | 22.09.2021 17:52:43 | 25,200 | d8772545113ff941d34a4eae5f43df3f39d3547f | Track UDP connections
This will enable NAT to be performed on UDP packets that are sent
in response to packets sent by the stack.
This will also enable ICMP errors to be properly NAT-ed in response
to UDP packets
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -160,7 +160,13 @@ func (cn *conn) timedOut(now time.Time) bool {\n// update the connection tracking state.\n//\n// Precondition: cn.mu must be held.\n-func (cn *conn) updateLocked(tcpHeader header.TCP, hook Hook) {\n+func (cn *conn) updateLocked(pkt *PacketBuffer, hook Hook) {\n+ if pkt.TransportProtocolNumber != header.TCPProtocolNumber {\n+ return\n+ }\n+\n+ tcpHeader := header.TCP(pkt.TransportHeader().View())\n+\n// Update the state of tcb. tcb assumes it's always initialized on the\n// client. However, we only need to know whether the connection is\n// established or not, so the client/server distinction isn't important.\n@@ -209,27 +215,38 @@ type bucket struct {\ntuples tupleList\n}\n+func getTransportHeader(pkt *PacketBuffer) (header.ChecksummableTransport, bool) {\n+ switch pkt.TransportProtocolNumber {\n+ case header.TCPProtocolNumber:\n+ if tcpHeader := header.TCP(pkt.TransportHeader().View()); len(tcpHeader) >= header.TCPMinimumSize {\n+ return tcpHeader, true\n+ }\n+ case header.UDPProtocolNumber:\n+ if udpHeader := header.UDP(pkt.TransportHeader().View()); len(udpHeader) >= header.UDPMinimumSize {\n+ return udpHeader, true\n+ }\n+ }\n+\n+ return nil, false\n+}\n+\n// packetToTupleID converts packet to a tuple ID. It fails when pkt lacks a valid\n// TCP header.\n//\n// Preconditions: pkt.NetworkHeader() is valid.\nfunc packetToTupleID(pkt *PacketBuffer) (tupleID, tcpip.Error) {\nnetHeader := pkt.Network()\n- if netHeader.TransportProtocol() != header.TCPProtocolNumber {\n- return tupleID{}, &tcpip.ErrUnknownProtocol{}\n- }\n-\n- tcpHeader := header.TCP(pkt.TransportHeader().View())\n- if len(tcpHeader) < header.TCPMinimumSize {\n+ transportHeader, ok := getTransportHeader(pkt)\n+ if !ok {\nreturn tupleID{}, &tcpip.ErrUnknownProtocol{}\n}\nreturn tupleID{\nsrcAddr: netHeader.SourceAddress(),\n- srcPort: tcpHeader.SourcePort(),\n+ srcPort: transportHeader.SourcePort(),\ndstAddr: netHeader.DestinationAddress(),\n- dstPort: tcpHeader.DestinationPort(),\n- transProto: netHeader.TransportProtocol(),\n+ dstPort: transportHeader.DestinationPort(),\n+ transProto: pkt.TransportProtocolNumber,\nnetProto: pkt.NetworkProtocolNumber,\n}, nil\n}\n@@ -381,8 +398,8 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\nreturn false\n}\n- // TODO(gvisor.dev/issue/6168): Support UDP.\n- if pkt.Network().TransportProtocol() != header.TCPProtocolNumber {\n+ transportHeader, ok := getTransportHeader(pkt)\n+ if !ok {\nreturn false\n}\n@@ -396,10 +413,6 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n}\nnetHeader := pkt.Network()\n- tcpHeader := header.TCP(pkt.TransportHeader().View())\n- if len(tcpHeader) < header.TCPMinimumSize {\n- return false\n- }\n// TODO(gvisor.dev/issue/5748): TCP checksums on inbound packets should be\n// validated if checksum offloading is off. It may require IP defrag if the\n@@ -412,36 +425,31 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\nswitch hook {\ncase Prerouting, Output:\n- if conn.manip == manipDestination {\n- switch dir {\n- case dirOriginal:\n+ if conn.manip == manipDestination && dir == dirOriginal {\nnewPort = conn.reply.srcPort\nnewAddr = conn.reply.srcAddr\n- case dirReply:\n- newPort = conn.original.dstPort\n- newAddr = conn.original.dstAddr\n-\n- updateSRCFields = true\n- }\n+ pkt.NatDone = true\n+ } else if conn.manip == manipSource && dir == dirReply {\n+ newPort = conn.original.srcPort\n+ newAddr = conn.original.srcAddr\npkt.NatDone = true\n}\ncase Input, Postrouting:\n- if conn.manip == manipSource {\n- switch dir {\n- case dirOriginal:\n+ if conn.manip == manipSource && dir == dirOriginal {\nnewPort = conn.reply.dstPort\nnewAddr = conn.reply.dstAddr\n-\nupdateSRCFields = true\n- case dirReply:\n- newPort = conn.original.srcPort\n- newAddr = conn.original.srcAddr\n- }\n+ pkt.NatDone = true\n+ } else if conn.manip == manipDestination && dir == dirReply {\n+ newPort = conn.original.dstPort\n+ newAddr = conn.original.dstAddr\n+ updateSRCFields = true\npkt.NatDone = true\n}\ndefault:\npanic(fmt.Sprintf(\"unrecognized hook = %s\", hook))\n}\n+\nif !pkt.NatDone {\nreturn false\n}\n@@ -449,10 +457,15 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\nfullChecksum := false\nupdatePseudoHeader := false\nswitch hook {\n- case Prerouting, Input:\n+ case Prerouting:\n+ // Packet came from outside the stack so it must have a checksum set\n+ // already.\n+ fullChecksum = true\n+ updatePseudoHeader = true\n+ case Input:\ncase Output, Postrouting:\n// Calculate the TCP checksum and set it.\n- if pkt.GSOOptions.Type != GSONone && pkt.GSOOptions.NeedsCsum {\n+ if pkt.TransportProtocolNumber == header.TCPProtocolNumber && pkt.GSOOptions.Type != GSONone && pkt.GSOOptions.NeedsCsum {\nupdatePseudoHeader = true\n} else if r.RequiresTXTransportChecksum() {\nfullChecksum = true\n@@ -464,7 +477,7 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\nrewritePacket(\nnetHeader,\n- tcpHeader,\n+ transportHeader,\nupdateSRCFields,\nfullChecksum,\nupdatePseudoHeader,\n@@ -479,7 +492,7 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n// Mark the connection as having been used recently so it isn't reaped.\nconn.lastUsed = time.Now()\n// Update connection state.\n- conn.updateLocked(header.TCP(pkt.TransportHeader().View()), hook)\n+ conn.updateLocked(pkt, hook)\nreturn false\n}\n@@ -497,8 +510,11 @@ func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer, hook Hook) {\nreturn\n}\n- // We only track TCP connections.\n- if pkt.Network().TransportProtocol() != header.TCPProtocolNumber {\n+ switch pkt.TransportProtocolNumber {\n+ case header.TCPProtocolNumber, header.UDPProtocolNumber:\n+ default:\n+ // TODO(https://gvisor.dev/issue/5915): Track ICMP and other trackable\n+ // connections.\nreturn\n}\n@@ -510,7 +526,7 @@ func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer, hook Hook) {\nreturn\n}\nconn := newConn(tid, tid.reply(), manipNone, hook)\n- conn.updateLocked(header.TCP(pkt.TransportHeader().View()), hook)\n+ conn.updateLocked(pkt, hook)\nct.insertConn(conn)\n}\n@@ -632,7 +648,7 @@ func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bucket int, now time.Time) bo\nreturn true\n}\n-func (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.NetworkProtocolNumber) (tcpip.Address, uint16, tcpip.Error) {\n+func (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber) (tcpip.Address, uint16, tcpip.Error) {\n// Lookup the connection. The reply's original destination\n// describes the original address.\ntid := tupleID{\n@@ -640,7 +656,7 @@ func (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.Networ\nsrcPort: epID.LocalPort,\ndstAddr: epID.RemoteAddress,\ndstPort: epID.RemotePort,\n- transProto: header.TCPProtocolNumber,\n+ transProto: transProto,\nnetProto: netProto,\n}\nconn, _ := ct.connForTID(tid)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -482,11 +482,11 @@ func (it *IPTables) checkRule(hook Hook, pkt *PacketBuffer, table Table, ruleIdx\n// OriginalDst returns the original destination of redirected connections. It\n// returns an error if the connection doesn't exist or isn't redirected.\n-func (it *IPTables) OriginalDst(epID TransportEndpointID, netProto tcpip.NetworkProtocolNumber) (tcpip.Address, uint16, tcpip.Error) {\n+func (it *IPTables) OriginalDst(epID TransportEndpointID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber) (tcpip.Address, uint16, tcpip.Error) {\nit.mu.RLock()\ndefer it.mu.RUnlock()\nif !it.modified {\nreturn \"\", 0, &tcpip.ErrNotConnected{}\n}\n- return it.connections.originalDst(epID, netProto)\n+ return it.connections.originalDst(epID, netProto, transProto)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -206,35 +206,29 @@ func (st *SNATTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Rou\npanic(fmt.Sprintf(\"%s unrecognized\", hook))\n}\n+ port := st.Port\n+\n+ if port == 0 {\nswitch protocol := pkt.TransportProtocolNumber; protocol {\ncase header.UDPProtocolNumber:\n- // Only calculate the checksum if offloading isn't supported.\n- requiresChecksum := r.RequiresTXTransportChecksum()\n- rewritePacket(\n- pkt.Network(),\n- header.UDP(pkt.TransportHeader().View()),\n- true, /* updateSRCFields */\n- requiresChecksum,\n- requiresChecksum,\n- st.Port,\n- st.Addr,\n- )\n-\n- pkt.NatDone = true\n+ if port == 0 {\n+ port = header.UDP(pkt.TransportHeader().View()).SourcePort()\n+ }\ncase header.TCPProtocolNumber:\n- if ct == nil {\n- return RuleAccept, 0\n+ if port == 0 {\n+ port = header.TCP(pkt.TransportHeader().View()).SourcePort()\n+ }\n+ }\n}\n- // Set up conection for matching NAT rule. Only the first\n- // packet of the connection comes here. Other packets will be\n- // manipulated in connection tracking.\n- if conn := ct.insertSNATConn(pkt, hook, st.Port, st.Addr); conn != nil {\n+ // Set up conection for matching NAT rule. Only the first packet of the\n+ // connection comes here. Other packets will be manipulated in connection\n+ // tracking.\n+ //\n+ // Does nothing if the protocol does not support connection tracking.\n+ if conn := ct.insertSNATConn(pkt, hook, port, st.Addr); conn != nil {\nct.handlePacket(pkt, hook, r)\n}\n- default:\n- return RuleDrop, 0\n- }\nreturn RuleAccept, 0\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/packet_buffer.go",
"new_path": "pkg/tcpip/stack/packet_buffer.go",
"diff": "@@ -335,9 +335,7 @@ func (pk *PacketBuffer) CloneToInbound() *PacketBuffer {\n// tell if a noop connection should be inserted at Input hook. Once conntrack\n// redefines the manipulation field as mutable, we won't need the special noop\n// connection.\n- if pk.NatDone {\n- newPk.NatDone = true\n- }\n+ newPk.NatDone = pk.NatDone\nreturn newPk\n}\n@@ -347,7 +345,7 @@ func (pk *PacketBuffer) CloneToInbound() *PacketBuffer {\n// The returned packet buffer will have the network and transport headers\n// set if the original packet buffer did.\nfunc (pk *PacketBuffer) DeepCopyForForwarding(reservedHeaderBytes int) *PacketBuffer {\n- newPkt := NewPacketBuffer(PacketBufferOptions{\n+ newPk := NewPacketBuffer(PacketBufferOptions{\nReserveHeaderBytes: reservedHeaderBytes,\nData: PayloadSince(pk.NetworkHeader()).ToVectorisedView(),\nIsForwardedPacket: true,\n@@ -355,21 +353,28 @@ func (pk *PacketBuffer) DeepCopyForForwarding(reservedHeaderBytes int) *PacketBu\n{\nconsumeBytes := pk.NetworkHeader().View().Size()\n- if _, consumed := newPkt.NetworkHeader().Consume(consumeBytes); !consumed {\n+ if _, consumed := newPk.NetworkHeader().Consume(consumeBytes); !consumed {\npanic(fmt.Sprintf(\"expected to consume network header %d bytes from new packet\", consumeBytes))\n}\n- newPkt.NetworkProtocolNumber = pk.NetworkProtocolNumber\n+ newPk.NetworkProtocolNumber = pk.NetworkProtocolNumber\n}\n{\nconsumeBytes := pk.TransportHeader().View().Size()\n- if _, consumed := newPkt.TransportHeader().Consume(consumeBytes); !consumed {\n+ if _, consumed := newPk.TransportHeader().Consume(consumeBytes); !consumed {\npanic(fmt.Sprintf(\"expected to consume transport header %d bytes from new packet\", consumeBytes))\n}\n- newPkt.TransportProtocolNumber = pk.TransportProtocolNumber\n+ newPk.TransportProtocolNumber = pk.TransportProtocolNumber\n}\n- return newPkt\n+ // TODO(gvisor.dev/issue/5696): reimplement conntrack so that no need to\n+ // maintain this flag in the packet. Currently conntrack needs this flag to\n+ // tell if a noop connection should be inserted at Input hook. Once conntrack\n+ // redefines the manipulation field as mutable, we won't need the special noop\n+ // connection.\n+ newPk.NatDone = pk.NatDone\n+\n+ return newPk\n}\n// headerInfo stores metadata about a header in a packet.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/integration/BUILD",
"new_path": "pkg/tcpip/tests/integration/BUILD",
"diff": "@@ -34,12 +34,16 @@ go_test(\n\"//pkg/tcpip/checker\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/network/arp\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n\"//pkg/tcpip/stack\",\n\"//pkg/tcpip/tests/utils\",\n\"//pkg/tcpip/testutil\",\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/tests/integration/iptables_test.go",
"new_path": "pkg/tcpip/tests/integration/iptables_test.go",
"diff": "package iptables_test\nimport (\n+ \"bytes\"\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/checker\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/network/arp\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv4\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n\"gvisor.dev/gvisor/pkg/tcpip/tests/utils\"\n\"gvisor.dev/gvisor/pkg/tcpip/testutil\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/tcp\"\n\"gvisor.dev/gvisor/pkg/tcpip/transport/udp\"\n+ \"gvisor.dev/gvisor/pkg/waiter\"\n)\ntype inputIfNameMatcher struct {\n@@ -1156,3 +1161,286 @@ func TestInputHookWithLocalForwarding(t *testing.T) {\n})\n}\n}\n+\n+func TestSNAT(t *testing.T) {\n+ const listenPort = 8080\n+\n+ type endpointAndAddresses struct {\n+ serverEP tcpip.Endpoint\n+ serverAddr tcpip.Address\n+ serverReadableCH chan struct{}\n+\n+ clientEP tcpip.Endpoint\n+ clientAddr tcpip.Address\n+ clientReadableCH chan struct{}\n+\n+ nattedClientAddr tcpip.Address\n+ }\n+\n+ newEP := func(t *testing.T, s *stack.Stack, transProto tcpip.TransportProtocolNumber, netProto tcpip.NetworkProtocolNumber) (tcpip.Endpoint, chan struct{}) {\n+ t.Helper()\n+ var wq waiter.Queue\n+ we, ch := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.ReadableEvents)\n+ t.Cleanup(func() {\n+ wq.EventUnregister(&we)\n+ })\n+\n+ ep, err := s.NewEndpoint(transProto, netProto, &wq)\n+ if err != nil {\n+ t.Fatalf(\"s.NewEndpoint(%d, %d, _): %s\", transProto, netProto, err)\n+ }\n+ t.Cleanup(ep.Close)\n+\n+ return ep, ch\n+ }\n+\n+ tests := []struct {\n+ name string\n+ epAndAddrs func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses\n+ }{\n+ {\n+ name: \"IPv4 host1 server with host2 client\",\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n+\n+ ipt := routerStack.IPTables()\n+ filter := ipt.GetTable(stack.NATID, false /* ipv6 */)\n+ ruleIdx := filter.BuiltinChains[stack.Postrouting]\n+ filter.Rules[ruleIdx].Filter = stack.IPHeaderFilter{OutputInterface: utils.RouterNIC1Name}\n+ filter.Rules[ruleIdx].Target = &stack.SNATTarget{NetworkProtocol: ipv4.ProtocolNumber, Addr: utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address}\n+ // Make sure the packet is not dropped by the next rule.\n+ filter.Rules[ruleIdx+1].Target = &stack.AcceptTarget{}\n+ if err := ipt.ReplaceTable(stack.NATID, filter, false /* ipv6 */); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, false, err)\n+ }\n+\n+ ep1, ep1WECH := newEP(t, host1Stack, proto, ipv4.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv4.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: utils.Host1IPv4Addr.AddressWithPrefix.Address,\n+ serverReadableCH: ep1WECH,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv4Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+\n+ nattedClientAddr: utils.RouterNIC1IPv4Addr.AddressWithPrefix.Address,\n+ }\n+ },\n+ },\n+ {\n+ name: \"IPv6 host1 server with host2 client\",\n+ epAndAddrs: func(t *testing.T, host1Stack, routerStack, host2Stack *stack.Stack, proto tcpip.TransportProtocolNumber) endpointAndAddresses {\n+ t.Helper()\n+\n+ ipt := routerStack.IPTables()\n+ filter := ipt.GetTable(stack.NATID, true /* ipv6 */)\n+ ruleIdx := filter.BuiltinChains[stack.Postrouting]\n+ filter.Rules[ruleIdx].Filter = stack.IPHeaderFilter{OutputInterface: utils.RouterNIC1Name}\n+ filter.Rules[ruleIdx].Target = &stack.SNATTarget{NetworkProtocol: ipv6.ProtocolNumber, Addr: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address}\n+ // Make sure the packet is not dropped by the next rule.\n+ filter.Rules[ruleIdx+1].Target = &stack.AcceptTarget{}\n+ if err := ipt.ReplaceTable(stack.NATID, filter, true /* ipv6 */); err != nil {\n+ t.Fatalf(\"ipt.ReplaceTable(%d, _, %t): %s\", stack.NATID, true, err)\n+ }\n+\n+ ep1, ep1WECH := newEP(t, host1Stack, proto, ipv6.ProtocolNumber)\n+ ep2, ep2WECH := newEP(t, host2Stack, proto, ipv6.ProtocolNumber)\n+ return endpointAndAddresses{\n+ serverEP: ep1,\n+ serverAddr: utils.Host1IPv6Addr.AddressWithPrefix.Address,\n+ serverReadableCH: ep1WECH,\n+\n+ clientEP: ep2,\n+ clientAddr: utils.Host2IPv6Addr.AddressWithPrefix.Address,\n+ clientReadableCH: ep2WECH,\n+\n+ nattedClientAddr: utils.RouterNIC1IPv6Addr.AddressWithPrefix.Address,\n+ }\n+ },\n+ },\n+ }\n+\n+ subTests := []struct {\n+ name string\n+ proto tcpip.TransportProtocolNumber\n+ expectedConnectErr tcpip.Error\n+ setupServer func(t *testing.T, ep tcpip.Endpoint)\n+ setupServerConn func(t *testing.T, ep tcpip.Endpoint, ch <-chan struct{}, clientAddr tcpip.FullAddress) (tcpip.Endpoint, chan struct{})\n+ needRemoteAddr bool\n+ }{\n+ {\n+ name: \"UDP\",\n+ proto: udp.ProtocolNumber,\n+ expectedConnectErr: nil,\n+ setupServerConn: func(t *testing.T, ep tcpip.Endpoint, _ <-chan struct{}, clientAddr tcpip.FullAddress) (tcpip.Endpoint, chan struct{}) {\n+ t.Helper()\n+\n+ if err := ep.Connect(clientAddr); err != nil {\n+ t.Fatalf(\"ep.Connect(%#v): %s\", clientAddr, err)\n+ }\n+ return nil, nil\n+ },\n+ needRemoteAddr: true,\n+ },\n+ {\n+ name: \"TCP\",\n+ proto: tcp.ProtocolNumber,\n+ expectedConnectErr: &tcpip.ErrConnectStarted{},\n+ setupServer: func(t *testing.T, ep tcpip.Endpoint) {\n+ t.Helper()\n+\n+ if err := ep.Listen(1); err != nil {\n+ t.Fatalf(\"ep.Listen(1): %s\", err)\n+ }\n+ },\n+ setupServerConn: func(t *testing.T, ep tcpip.Endpoint, ch <-chan struct{}, clientAddr tcpip.FullAddress) (tcpip.Endpoint, chan struct{}) {\n+ t.Helper()\n+\n+ var addr tcpip.FullAddress\n+ for {\n+ newEP, wq, err := ep.Accept(&addr)\n+ if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ <-ch\n+ continue\n+ }\n+ if err != nil {\n+ t.Fatalf(\"ep.Accept(_): %s\", err)\n+ }\n+ if diff := cmp.Diff(clientAddr, addr, checker.IgnoreCmpPath(\n+ \"NIC\",\n+ )); diff != \"\" {\n+ t.Errorf(\"accepted address mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ we, newCH := waiter.NewChannelEntry(nil)\n+ wq.EventRegister(&we, waiter.ReadableEvents)\n+ return newEP, newCH\n+ }\n+ },\n+ needRemoteAddr: false,\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ for _, subTest := range subTests {\n+ t.Run(subTest.name, func(t *testing.T) {\n+ stackOpts := stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocol, ipv4.NewProtocol, ipv6.NewProtocol},\n+ TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, tcp.NewProtocol},\n+ }\n+\n+ host1Stack := stack.New(stackOpts)\n+ routerStack := stack.New(stackOpts)\n+ host2Stack := stack.New(stackOpts)\n+ utils.SetupRoutedStacks(t, host1Stack, routerStack, host2Stack)\n+\n+ epsAndAddrs := test.epAndAddrs(t, host1Stack, routerStack, host2Stack, subTest.proto)\n+ serverAddr := tcpip.FullAddress{Addr: epsAndAddrs.serverAddr, Port: listenPort}\n+ if err := epsAndAddrs.serverEP.Bind(serverAddr); err != nil {\n+ t.Fatalf(\"epsAndAddrs.serverEP.Bind(%#v): %s\", serverAddr, err)\n+ }\n+ clientAddr := tcpip.FullAddress{Addr: epsAndAddrs.clientAddr}\n+ if err := epsAndAddrs.clientEP.Bind(clientAddr); err != nil {\n+ t.Fatalf(\"epsAndAddrs.clientEP.Bind(%#v): %s\", clientAddr, err)\n+ }\n+\n+ if subTest.setupServer != nil {\n+ subTest.setupServer(t, epsAndAddrs.serverEP)\n+ }\n+ {\n+ err := epsAndAddrs.clientEP.Connect(serverAddr)\n+ if diff := cmp.Diff(subTest.expectedConnectErr, err); diff != \"\" {\n+ t.Fatalf(\"unexpected error from epsAndAddrs.clientEP.Connect(%#v), (-want, +got):\\n%s\", serverAddr, diff)\n+ }\n+ }\n+ nattedClientAddr := tcpip.FullAddress{Addr: epsAndAddrs.nattedClientAddr}\n+ if addr, err := epsAndAddrs.clientEP.GetLocalAddress(); err != nil {\n+ t.Fatalf(\"epsAndAddrs.clientEP.GetLocalAddress(): %s\", err)\n+ } else {\n+ nattedClientAddr.Port = addr.Port\n+ }\n+\n+ serverEP := epsAndAddrs.serverEP\n+ serverCH := epsAndAddrs.serverReadableCH\n+ if ep, ch := subTest.setupServerConn(t, serverEP, serverCH, nattedClientAddr); ep != nil {\n+ defer ep.Close()\n+ serverEP = ep\n+ serverCH = ch\n+ }\n+\n+ write := func(ep tcpip.Endpoint, data []byte) {\n+ t.Helper()\n+\n+ var r bytes.Reader\n+ r.Reset(data)\n+ var wOpts tcpip.WriteOptions\n+ n, err := ep.Write(&r, wOpts)\n+ if err != nil {\n+ t.Fatalf(\"ep.Write(_, %#v): %s\", wOpts, err)\n+ }\n+ if want := int64(len(data)); n != want {\n+ t.Fatalf(\"got ep.Write(_, %#v) = (%d, _), want = (%d, _)\", wOpts, n, want)\n+ }\n+ }\n+\n+ read := func(ch chan struct{}, ep tcpip.Endpoint, data []byte, expectedFrom tcpip.FullAddress) {\n+ t.Helper()\n+\n+ var buf bytes.Buffer\n+ var res tcpip.ReadResult\n+ for {\n+ var err tcpip.Error\n+ opts := tcpip.ReadOptions{NeedRemoteAddr: subTest.needRemoteAddr}\n+ res, err = ep.Read(&buf, opts)\n+ if _, ok := err.(*tcpip.ErrWouldBlock); ok {\n+ <-ch\n+ continue\n+ }\n+ if err != nil {\n+ t.Fatalf(\"ep.Read(_, %d, %#v): %s\", len(data), opts, err)\n+ }\n+ break\n+ }\n+\n+ readResult := tcpip.ReadResult{\n+ Count: len(data),\n+ Total: len(data),\n+ }\n+ if subTest.needRemoteAddr {\n+ readResult.RemoteAddr = expectedFrom\n+ }\n+ if diff := cmp.Diff(readResult, res, checker.IgnoreCmpPath(\n+ \"ControlMessages\",\n+ \"RemoteAddr.NIC\",\n+ )); diff != \"\" {\n+ t.Errorf(\"ep.Read: unexpected result (-want +got):\\n%s\", diff)\n+ }\n+ if diff := cmp.Diff(buf.Bytes(), data); diff != \"\" {\n+ t.Errorf(\"received data mismatch (-want +got):\\n%s\", diff)\n+ }\n+\n+ if t.Failed() {\n+ t.FailNow()\n+ }\n+ }\n+\n+ {\n+ data := []byte{1, 2, 3, 4}\n+ write(epsAndAddrs.clientEP, data)\n+ read(serverCH, serverEP, data, nattedClientAddr)\n+ }\n+\n+ {\n+ data := []byte{5, 6, 7, 8, 9, 10, 11, 12}\n+ write(serverEP, data)\n+ read(epsAndAddrs.clientReadableCH, epsAndAddrs.clientEP, data, serverAddr)\n+ }\n+ })\n+ }\n+ })\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tests/utils/utils.go",
"new_path": "pkg/tcpip/tests/utils/utils.go",
"diff": "@@ -40,6 +40,14 @@ const (\nHost2NICID = 4\n)\n+// Common NIC names used by tests.\n+const (\n+ Host1NICName = \"host1NIC\"\n+ RouterNIC1Name = \"routerNIC1\"\n+ RouterNIC2Name = \"routerNIC2\"\n+ Host2NICName = \"host2NIC\"\n+)\n+\n// Common link addresses used by tests.\nconst (\nLinkAddr1 = tcpip.LinkAddress(\"\\x02\\x03\\x03\\x04\\x05\\x06\")\n@@ -211,17 +219,29 @@ func SetupRoutedStacks(t *testing.T, host1Stack, routerStack, host2Stack *stack.\nhost1NIC, routerNIC1 := pipe.New(LinkAddr1, LinkAddr2)\nrouterNIC2, host2NIC := pipe.New(LinkAddr3, LinkAddr4)\n- if err := host1Stack.CreateNIC(Host1NICID, NewEthernetEndpoint(host1NIC)); err != nil {\n- t.Fatalf(\"host1Stack.CreateNIC(%d, _): %s\", Host1NICID, err)\n+ {\n+ opts := stack.NICOptions{Name: Host1NICName}\n+ if err := host1Stack.CreateNICWithOptions(Host1NICID, NewEthernetEndpoint(host1NIC), opts); err != nil {\n+ t.Fatalf(\"host1Stack.CreateNICWithOptions(%d, _, %#v): %s\", Host1NICID, opts, err)\n+ }\n}\n- if err := routerStack.CreateNIC(RouterNICID1, NewEthernetEndpoint(routerNIC1)); err != nil {\n- t.Fatalf(\"routerStack.CreateNIC(%d, _): %s\", RouterNICID1, err)\n+ {\n+ opts := stack.NICOptions{Name: RouterNIC1Name}\n+ if err := routerStack.CreateNICWithOptions(RouterNICID1, NewEthernetEndpoint(routerNIC1), opts); err != nil {\n+ t.Fatalf(\"routerStack.CreateNICWithOptions(%d, _, %#v): %s\", RouterNICID1, opts, err)\n}\n- if err := routerStack.CreateNIC(RouterNICID2, NewEthernetEndpoint(routerNIC2)); err != nil {\n- t.Fatalf(\"routerStack.CreateNIC(%d, _): %s\", RouterNICID2, err)\n}\n- if err := host2Stack.CreateNIC(Host2NICID, NewEthernetEndpoint(host2NIC)); err != nil {\n- t.Fatalf(\"host2Stack.CreateNIC(%d, _): %s\", Host2NICID, err)\n+ {\n+ opts := stack.NICOptions{Name: RouterNIC2Name}\n+ if err := routerStack.CreateNICWithOptions(RouterNICID2, NewEthernetEndpoint(routerNIC2), opts); err != nil {\n+ t.Fatalf(\"routerStack.CreateNICWithOptions(%d, _, %#v): %s\", RouterNICID2, opts, err)\n+ }\n+ }\n+ {\n+ opts := stack.NICOptions{Name: Host2NICName}\n+ if err := host2Stack.CreateNICWithOptions(Host2NICID, NewEthernetEndpoint(host2NIC), opts); err != nil {\n+ t.Fatalf(\"host2Stack.CreateNICWithOptions(%d, _, %#v): %s\", Host2NICID, opts, err)\n+ }\n}\nif err := routerStack.SetForwardingDefaultAndAllNICs(ipv4.ProtocolNumber, true); err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -2066,7 +2066,7 @@ func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) tcpip.Error {\ncase *tcpip.OriginalDestinationOption:\ne.LockUser()\nipt := e.stack.IPTables()\n- addr, port, err := ipt.OriginalDst(e.TransportEndpointInfo.ID, e.NetProto)\n+ addr, port, err := ipt.OriginalDst(e.TransportEndpointInfo.ID, e.NetProto, ProtocolNumber)\ne.UnlockUser()\nif err != nil {\nreturn err\n"
}
] | Go | Apache License 2.0 | google/gvisor | Track UDP connections
This will enable NAT to be performed on UDP packets that are sent
in response to packets sent by the stack.
This will also enable ICMP errors to be properly NAT-ed in response
to UDP packets (#5916).
Updates #5915.
PiperOrigin-RevId: 398373251 |
259,885 | 22.09.2021 18:09:49 | 25,200 | de750eb1d3ef2c8c60274c62c4463392b29b45c7 | Add Execve and ExitNotifyParent checkpoints.
Call sites for the two checkpoints aren't added yet. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/BUILD",
"new_path": "pkg/sentry/seccheck/BUILD",
"diff": "@@ -8,6 +8,8 @@ go_fieldenum(\nname = \"seccheck_fieldenum\",\nsrcs = [\n\"clone.go\",\n+ \"execve.go\",\n+ \"exit.go\",\n\"task.go\",\n],\nout = \"seccheck_fieldenum.go\",\n@@ -29,6 +31,8 @@ go_library(\nname = \"seccheck\",\nsrcs = [\n\"clone.go\",\n+ \"execve.go\",\n+ \"exit.go\",\n\"seccheck.go\",\n\"seccheck_fieldenum.go\",\n\"seqatomic_checkerslice_unsafe.go\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/execve.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package seccheck\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+)\n+\n+// ExecveInfo contains information used by the Execve checkpoint.\n+//\n+// +fieldenum Execve\n+type ExecveInfo struct {\n+ // Invoker identifies the invoking thread.\n+ Invoker TaskInfo\n+\n+ // Credentials are the invoking thread's credentials.\n+ Credentials *auth.Credentials\n+\n+ // BinaryPath is a path to the executable binary file being switched to in\n+ // the mount namespace in which it was opened.\n+ BinaryPath string\n+\n+ // Argv is the new process image's argument vector.\n+ Argv []string\n+\n+ // Env is the new process image's environment variables.\n+ Env []string\n+\n+ // BinaryMode is the executable binary file's mode.\n+ BinaryMode uint16\n+\n+ // BinarySHA256 is the SHA-256 hash of the executable binary file.\n+ //\n+ // Note that this requires reading the entire file into memory, which is\n+ // likely to be extremely slow.\n+ BinarySHA256 [32]byte\n+}\n+\n+// ExecveReq returns fields required by the Execve checkpoint.\n+func (s *state) ExecveReq() ExecveFieldSet {\n+ return s.execveReq.Load()\n+}\n+\n+// Execve is called at the Execve checkpoint.\n+func (s *state) Execve(ctx context.Context, mask ExecveFieldSet, info *ExecveInfo) error {\n+ for _, c := range s.getCheckers() {\n+ if err := c.Execve(ctx, mask, *info); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/sentry/seccheck/exit.go",
"diff": "+// Copyright 2021 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package seccheck\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/context\"\n+)\n+\n+// ExitNotifyParentInfo contains information used by the ExitNotifyParent\n+// checkpoint.\n+//\n+// +fieldenum ExitNotifyParent\n+type ExitNotifyParentInfo struct {\n+ // Exiter identifies the exiting thread. Note that by the checkpoint's\n+ // definition, Exiter.ThreadID == Exiter.ThreadGroupID and\n+ // Exiter.ThreadStartTime == Exiter.ThreadGroupStartTime, so requesting\n+ // ThreadGroup* fields is redundant.\n+ Exiter TaskInfo\n+\n+ // ExitStatus is the exiting thread group's exit status, as reported\n+ // by wait*().\n+ ExitStatus linux.WaitStatus\n+}\n+\n+// ExitNotifyParentReq returns fields required by the ExitNotifyParent\n+// checkpoint.\n+func (s *state) ExitNotifyParentReq() ExitNotifyParentFieldSet {\n+ return s.exitNotifyParentReq.Load()\n+}\n+\n+// ExitNotifyParent is called at the ExitNotifyParent checkpoint.\n+//\n+// The ExitNotifyParent checkpoint occurs when a zombied thread group leader,\n+// not waiting for exit acknowledgement from a non-parent ptracer, becomes the\n+// last non-dead thread in its thread group and notifies its parent of its\n+// exiting.\n+func (s *state) ExitNotifyParent(ctx context.Context, mask ExitNotifyParentFieldSet, info *ExitNotifyParentInfo) error {\n+ for _, c := range s.getCheckers() {\n+ if err := c.ExitNotifyParent(ctx, mask, *info); err != nil {\n+ return err\n+ }\n+ }\n+ return nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/seccheck/seccheck.go",
"new_path": "pkg/sentry/seccheck/seccheck.go",
"diff": "@@ -29,6 +29,8 @@ type Point uint\n// PointX represents the checkpoint X.\nconst (\nPointClone Point = iota\n+ PointExecve\n+ PointExitNotifyParent\n// Add new Points above this line.\npointLength\n@@ -47,6 +49,8 @@ const (\n// registered concurrently with invocations of checkpoints).\ntype Checker interface {\nClone(ctx context.Context, mask CloneFieldSet, info CloneInfo) error\n+ Execve(ctx context.Context, mask ExecveFieldSet, info ExecveInfo) error\n+ ExitNotifyParent(ctx context.Context, mask ExitNotifyParentFieldSet, info ExitNotifyParentInfo) error\n}\n// CheckerDefaults may be embedded by implementations of Checker to obtain\n@@ -58,6 +62,16 @@ func (CheckerDefaults) Clone(ctx context.Context, mask CloneFieldSet, info Clone\nreturn nil\n}\n+// Execve implements Checker.Execve.\n+func (CheckerDefaults) Execve(ctx context.Context, mask ExecveFieldSet, info ExecveInfo) error {\n+ return nil\n+}\n+\n+// ExitNotifyParent implements Checker.ExitNotifyParent.\n+func (CheckerDefaults) ExitNotifyParent(ctx context.Context, mask ExitNotifyParentFieldSet, info ExitNotifyParentInfo) error {\n+ return nil\n+}\n+\n// CheckerReq indicates what checkpoints a corresponding Checker runs at, and\n// what information it requires at those checkpoints.\ntype CheckerReq struct {\n@@ -70,6 +84,8 @@ type CheckerReq struct {\n// All of the following fields indicate what fields in the corresponding\n// XInfo struct will be requested at the corresponding checkpoint.\nClone CloneFields\n+ Execve ExecveFields\n+ ExitNotifyParent ExitNotifyParentFields\n}\n// Global is the method receiver of all seccheck functions.\n@@ -102,6 +118,8 @@ type state struct {\n// checker, are accessed using atomic memory operations, and are mutated\n// with registrationMu locked.\ncloneReq CloneFieldSet\n+ execveReq ExecveFieldSet\n+ exitNotifyParentReq ExitNotifyParentFieldSet\n}\n// AppendChecker registers the given Checker to execute at checkpoints. The\n@@ -110,7 +128,11 @@ type state struct {\nfunc (s *state) AppendChecker(c Checker, req *CheckerReq) {\ns.registrationMu.Lock()\ndefer s.registrationMu.Unlock()\n+\ns.cloneReq.AddFieldsLoadable(req.Clone)\n+ s.execveReq.AddFieldsLoadable(req.Execve)\n+ s.exitNotifyParentReq.AddFieldsLoadable(req.ExitNotifyParent)\n+\ns.appendCheckerLocked(c)\nfor _, p := range req.Points {\nword, bit := p/32, p%32\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/go_fieldenum/main.go",
"new_path": "tools/go_fieldenum/main.go",
"diff": "@@ -55,6 +55,7 @@ func main() {\n// Determine which types are marked \"+fieldenum\" and will consequently have\n// code generated.\n+ var typeNames []string\nfieldEnumTypes := make(map[string]fieldEnumTypeInfo)\nfor _, f := range inputFiles {\nfor _, decl := range f.Decls {\n@@ -75,6 +76,7 @@ func main() {\nif !ok {\nlog.Fatalf(\"Type %s is marked +fieldenum, but is not a struct\", name)\n}\n+ typeNames = append(typeNames, name)\nfieldEnumTypes[name] = fieldEnumTypeInfo{\nprefix: prefix,\nstructType: st,\n@@ -86,9 +88,10 @@ func main() {\n}\n// Collect information for each type for which code is being generated.\n- structInfos := make([]structInfo, 0, len(fieldEnumTypes))\n+ structInfos := make([]structInfo, 0, len(typeNames))\nneedSyncAtomic := false\n- for typeName, typeInfo := range fieldEnumTypes {\n+ for _, typeName := range typeNames {\n+ typeInfo := fieldEnumTypes[typeName]\nvar si structInfo\nsi.name = typeName\nsi.prefix = typeInfo.prefix\n@@ -204,13 +207,6 @@ func structFieldName(f *ast.Field) string {\n}\n}\n-// Workaround for Go defect (map membership test isn't usable in an\n-// expression).\n-func fetContains(xs map[string]*ast.StructType, x string) bool {\n- _, ok := xs[x]\n- return ok\n-}\n-\nfunc (si *structInfo) writeTo(b *strings.Builder) {\nfmt.Fprintf(b, \"// A %sField represents a field in %s.\\n\", si.prefix, si.name)\nfmt.Fprintf(b, \"type %sField uint\\n\\n\", si.prefix)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add Execve and ExitNotifyParent checkpoints.
Call sites for the two checkpoints aren't added yet.
PiperOrigin-RevId: 398375903 |
260,004 | 23.09.2021 11:37:51 | 25,200 | d480289adb9bd3421dd6275ff480f5e5743e326b | Introduce method per iptables hook
...to make it clear what arguments are needed per hook. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -426,7 +426,7 @@ func (e *endpoint) WritePacket(r *stack.Route, params stack.NetworkHeaderParams,\n// iptables filtering. All packets that reach here are locally\n// generated.\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Output, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckOutput(pkt, r, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesOutputDropped.Increment()\nreturn nil\n@@ -466,7 +466,7 @@ func (e *endpoint) writePacket(r *stack.Route, pkt *stack.PacketBuffer, headerIn\n// Postrouting NAT can only change the source address, and does not alter the\n// route or outgoing interface of the packet.\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Postrouting, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPostrouting(pkt, r, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesPostroutingDropped.Increment()\nreturn nil\n@@ -549,7 +549,7 @@ func (e *endpoint) WritePackets(r *stack.Route, pkts stack.PacketBufferList, par\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n// iptables filtering. All packets that reach here are locally\n// generated.\n- outputDropped, natPkts := e.protocol.stack.IPTables().CheckPackets(stack.Output, pkts, r, \"\" /* inNicName */, outNicName)\n+ outputDropped, natPkts := e.protocol.stack.IPTables().CheckOutputPackets(pkts, r, outNicName)\nstats.IPTablesOutputDropped.IncrementBy(uint64(len(outputDropped)))\nfor pkt := range outputDropped {\npkts.Remove(pkt)\n@@ -576,7 +576,7 @@ func (e *endpoint) WritePackets(r *stack.Route, pkts stack.PacketBufferList, par\n// We ignore the list of NAT-ed packets here because Postrouting NAT can only\n// change the source address, and does not alter the route or outgoing\n// interface of the packet.\n- postroutingDropped, _ := e.protocol.stack.IPTables().CheckPackets(stack.Postrouting, pkts, r, \"\" /* inNicName */, outNicName)\n+ postroutingDropped, _ := e.protocol.stack.IPTables().CheckPostroutingPackets(pkts, r, outNicName)\nstats.IPTablesPostroutingDropped.IncrementBy(uint64(len(postroutingDropped)))\nfor pkt := range postroutingDropped {\npkts.Remove(pkt)\n@@ -717,7 +717,7 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\nif ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\ninNicName := stk.FindNICNameFromID(e.nic.ID())\noutNicName := stk.FindNICNameFromID(ep.nic.ID())\n- if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ if ok := stk.IPTables().CheckForward(pkt, inNicName, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesForwardDropped.Increment()\nreturn nil\n@@ -744,7 +744,7 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\ninNicName := stk.FindNICNameFromID(e.nic.ID())\noutNicName := stk.FindNICNameFromID(r.NICID())\n- if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ if ok := stk.IPTables().CheckForward(pkt, inNicName, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesForwardDropped.Increment()\nreturn nil\n@@ -841,7 +841,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Prerouting, pkt, nil, e.MainAddress().Address, inNicName, \"\" /* outNicName */); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e.MainAddress().Address, inNicName); !ok {\n// iptables is telling us to drop the packet.\nstats.IPTablesPreroutingDropped.Increment()\nreturn\n@@ -940,7 +940,7 @@ func (e *endpoint) handleValidatedPacket(h header.IPv4, pkt *stack.PacketBuffer,\n// iptables filtering. All packets that reach here are intended for\n// this machine and will not be forwarded.\n- if ok := e.protocol.stack.IPTables().Check(stack.Input, pkt, nil, \"\" /* preroutingAddr */, inNICName, \"\" /* outNicName */); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckInput(pkt, inNICName); !ok {\n// iptables is telling us to drop the packet.\nstats.ip.IPTablesInputDropped.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -748,7 +748,7 @@ func (e *endpoint) WritePacket(r *stack.Route, params stack.NetworkHeaderParams,\n// iptables filtering. All packets that reach here are locally\n// generated.\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Output, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckOutput(pkt, r, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesOutputDropped.Increment()\nreturn nil\n@@ -788,7 +788,7 @@ func (e *endpoint) writePacket(r *stack.Route, pkt *stack.PacketBuffer, protocol\n// Postrouting NAT can only change the source address, and does not alter the\n// route or outgoing interface of the packet.\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Postrouting, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPostrouting(pkt, r, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesPostroutingDropped.Increment()\nreturn nil\n@@ -871,7 +871,7 @@ func (e *endpoint) WritePackets(r *stack.Route, pkts stack.PacketBufferList, par\n// iptables filtering. All packets that reach here are locally\n// generated.\noutNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- outputDropped, natPkts := e.protocol.stack.IPTables().CheckPackets(stack.Output, pkts, r, \"\" /* inNicName */, outNicName)\n+ outputDropped, natPkts := e.protocol.stack.IPTables().CheckOutputPackets(pkts, r, outNicName)\nstats.IPTablesOutputDropped.IncrementBy(uint64(len(outputDropped)))\nfor pkt := range outputDropped {\npkts.Remove(pkt)\n@@ -897,7 +897,7 @@ func (e *endpoint) WritePackets(r *stack.Route, pkts stack.PacketBufferList, par\n// We ignore the list of NAT-ed packets here because Postrouting NAT can only\n// change the source address, and does not alter the route or outgoing\n// interface of the packet.\n- postroutingDropped, _ := e.protocol.stack.IPTables().CheckPackets(stack.Postrouting, pkts, r, \"\" /* inNicName */, outNicName)\n+ postroutingDropped, _ := e.protocol.stack.IPTables().CheckPostroutingPackets(pkts, r, outNicName)\nstats.IPTablesPostroutingDropped.IncrementBy(uint64(len(postroutingDropped)))\nfor pkt := range postroutingDropped {\npkts.Remove(pkt)\n@@ -984,7 +984,7 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\nif ep := e.protocol.findEndpointWithAddress(dstAddr); ep != nil {\ninNicName := stk.FindNICNameFromID(e.nic.ID())\noutNicName := stk.FindNICNameFromID(ep.nic.ID())\n- if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ if ok := stk.IPTables().CheckForward(pkt, inNicName, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesForwardDropped.Increment()\nreturn nil\n@@ -1015,7 +1015,7 @@ func (e *endpoint) forwardPacket(pkt *stack.PacketBuffer) ip.ForwardingError {\ninNicName := stk.FindNICNameFromID(e.nic.ID())\noutNicName := stk.FindNICNameFromID(r.NICID())\n- if ok := stk.IPTables().Check(stack.Forward, pkt, nil, \"\" /* preroutingAddr */, inNicName, outNicName); !ok {\n+ if ok := stk.IPTables().CheckForward(pkt, inNicName, outNicName); !ok {\n// iptables is telling us to drop the packet.\ne.stats.ip.IPTablesForwardDropped.Increment()\nreturn nil\n@@ -1100,7 +1100,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().Check(stack.Prerouting, pkt, nil, e.MainAddress().Address, inNicName, \"\" /* outNicName */); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e.MainAddress().Address, inNicName); !ok {\n// iptables is telling us to drop the packet.\nstats.IPTablesPreroutingDropped.Increment()\nreturn\n@@ -1183,7 +1183,7 @@ func (e *endpoint) handleValidatedPacket(h header.IPv6, pkt *stack.PacketBuffer,\n// iptables filtering. All packets that reach here are intended for\n// this machine and need not be forwarded.\n- if ok := e.protocol.stack.IPTables().Check(stack.Input, pkt, nil, \"\" /* preroutingAddr */, inNICName, \"\" /* outNicName */); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckInput(pkt, inNICName); !ok {\n// iptables is telling us to drop the packet.\nstats.IPTablesInputDropped.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -264,12 +264,62 @@ const (\nchainReturn\n)\n-// Check runs pkt through the rules for hook. It returns true when the packet\n+// CheckPrerouting performs the prerouting hook on the packet.\n+//\n+// Returns true iff the packet may continue traversing the stack; the packet\n+// must be dropped if false is returned.\n+//\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, preroutingAddr tcpip.Address, inNicName string) bool {\n+ return it.check(Prerouting, pkt, nil /* route */, preroutingAddr, inNicName, \"\" /* outNicName */)\n+}\n+\n+// CheckInput performs the input hook on the packet.\n+//\n+// Returns true iff the packet may continue traversing the stack; the packet\n+// must be dropped if false is returned.\n+//\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n+ return it.check(Input, pkt, nil /* route */, \"\" /* preroutingAddr */, inNicName, \"\" /* outNicName */)\n+}\n+\n+// CheckForward performs the forward hook on the packet.\n+//\n+// Returns true iff the packet may continue traversing the stack; the packet\n+// must be dropped if false is returned.\n+//\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\n+ return it.check(Forward, pkt, nil /* route */, \"\" /* preroutingAddr */, inNicName, outNicName)\n+}\n+\n+// CheckOutput performs the output hook on the packet.\n+//\n+// Returns true iff the packet may continue traversing the stack; the packet\n+// must be dropped if false is returned.\n+//\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\n+ return it.check(Output, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName)\n+}\n+\n+// CheckPostrouting performs the postrouting hook on the packet.\n+//\n+// Returns true iff the packet may continue traversing the stack; the packet\n+// must be dropped if false is returned.\n+//\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, outNicName string) bool {\n+ return it.check(Postrouting, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName)\n+}\n+\n+// check runs pkt through the rules for hook. It returns true when the packet\n// should continue traversing the network stack and false when it should be\n// dropped.\n//\n-// Precondition: pkt.NetworkHeader is set.\n-func (it *IPTables) Check(hook Hook, pkt *PacketBuffer, r *Route, preroutingAddr tcpip.Address, inNicName, outNicName string) bool {\n+// Precondition: The packet's network and transport header must be set.\n+func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, preroutingAddr tcpip.Address, inNicName, outNicName string) bool {\nif pkt.NetworkProtocolNumber != header.IPv4ProtocolNumber && pkt.NetworkProtocolNumber != header.IPv6ProtocolNumber {\nreturn true\n}\n@@ -375,19 +425,35 @@ func (it *IPTables) startReaper(interval time.Duration) {\n}()\n}\n-// CheckPackets runs pkts through the rules for hook and returns a map of packets that\n-// should not go forward.\n+// CheckOutputPackets performs the output hook on the packets.\n//\n-// Preconditions:\n-// * pkt is a IPv4 packet of at least length header.IPv4MinimumSize.\n-// * pkt.NetworkHeader is not nil.\n+// Returns a map of packets that must be dropped.\n+//\n+// Precondition: The packets' network and transport header must be set.\n+func (it *IPTables) CheckOutputPackets(pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n+ return it.checkPackets(Output, pkts, r, outNicName)\n+}\n+\n+// CheckPostroutingPackets performs the postrouting hook on the packets.\n+//\n+// Returns a map of packets that must be dropped.\n+//\n+// Precondition: The packets' network and transport header must be set.\n+func (it *IPTables) CheckPostroutingPackets(pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n+ return it.checkPackets(Postrouting, pkts, r, outNicName)\n+}\n+\n+// checkPackets runs pkts through the rules for hook and returns a map of\n+// packets that should not go forward.\n//\n// NOTE: unlike the Check API the returned map contains packets that should be\n// dropped.\n-func (it *IPTables) CheckPackets(hook Hook, pkts PacketBufferList, r *Route, inNicName, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n+//\n+// Precondition: The packets' network and transport header must be set.\n+func (it *IPTables) checkPackets(hook Hook, pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\nif !pkt.NatDone {\n- if ok := it.Check(hook, pkt, r, \"\", inNicName, outNicName); !ok {\n+ if ok := it.check(hook, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\nif drop == nil {\ndrop = make(map[*PacketBuffer]struct{})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Introduce method per iptables hook
...to make it clear what arguments are needed per hook.
PiperOrigin-RevId: 398538776 |
260,004 | 23.09.2021 11:42:24 | 25,200 | 2e4f26ac5ed206e981f662326e19d60b5f05bd4c | Compose ICMP endpoint with datagram-based endpoint
An ICMP endpoint's write path can use the datagram-based endpoint.
Updates
Test: Datagram-based generic socket + ICMP/ping syscall tests. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/BUILD",
"new_path": "pkg/tcpip/transport/icmp/BUILD",
"diff": "@@ -33,6 +33,8 @@ go_library(\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/ports\",\n\"//pkg/tcpip/stack\",\n+ \"//pkg/tcpip/transport\",\n+ \"//pkg/tcpip/transport/internal/network\",\n\"//pkg/tcpip/transport/raw\",\n\"//pkg/tcpip/transport/tcp\",\n\"//pkg/waiter\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "package icmp\nimport (\n+ \"fmt\"\n\"io\"\n\"time\"\n@@ -24,6 +25,8 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/ports\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/internal/network\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -35,15 +38,6 @@ type icmpPacket struct {\nreceivedAt time.Time `state:\".(int64)\"`\n}\n-type endpointState int\n-\n-const (\n- stateInitial endpointState = iota\n- stateBound\n- stateConnected\n- stateClosed\n-)\n-\n// endpoint represents an ICMP endpoint. This struct serves as the interface\n// between users of the endpoint and the protocol implementation; it is legal to\n// have concurrent goroutines make calls into the endpoint, they are properly\n@@ -51,14 +45,18 @@ const (\n//\n// +stateify savable\ntype endpoint struct {\n- stack.TransportEndpointInfo\ntcpip.DefaultSocketOptionsHandler\n// The following fields are initialized at creation time and are\n// immutable.\nstack *stack.Stack `state:\"manual\"`\n+ transProto tcpip.TransportProtocolNumber\nwaiterQueue *waiter.Queue\nuniqueID uint64\n+ net network.Endpoint\n+ // TODO(b/142022063): Add ability to save and restore per endpoint stats.\n+ stats tcpip.TransportEndpointStats `state:\"nosave\"`\n+ ops tcpip.SocketOptions\n// The following fields are used to manage the receive queue, and are\n// protected by rcvMu.\n@@ -70,38 +68,23 @@ type endpoint struct {\n// The following fields are protected by the mu mutex.\nmu sync.RWMutex `state:\"nosave\"`\n- // shutdownFlags represent the current shutdown state of the endpoint.\n- shutdownFlags tcpip.ShutdownFlags\n- state endpointState\n- route *stack.Route `state:\"manual\"`\n- ttl uint8\n- stats tcpip.TransportEndpointStats `state:\"nosave\"`\n-\n- // owner is used to get uid and gid of the packet.\n- owner tcpip.PacketOwner\n-\n- // ops is used to get socket level options.\n- ops tcpip.SocketOptions\n-\n// frozen indicates if the packets should be delivered to the endpoint\n// during restore.\nfrozen bool\n+ ident uint16\n}\nfunc newEndpoint(s *stack.Stack, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber, waiterQueue *waiter.Queue) (tcpip.Endpoint, tcpip.Error) {\nep := &endpoint{\nstack: s,\n- TransportEndpointInfo: stack.TransportEndpointInfo{\n- NetProto: netProto,\n- TransProto: transProto,\n- },\n+ transProto: transProto,\nwaiterQueue: waiterQueue,\n- state: stateInitial,\nuniqueID: s.UniqueID(),\n}\nep.ops.InitHandler(ep, ep.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\nep.ops.SetSendBufferSize(32*1024, false /* notify */)\nep.ops.SetReceiveBufferSize(32*1024, false /* notify */)\n+ ep.net.Init(s, netProto, transProto, &ep.ops)\n// Override with stack defaults.\nvar ss tcpip.SendBufferSizeOption\n@@ -128,43 +111,48 @@ func (e *endpoint) Abort() {\n// Close puts the endpoint in a closed state and frees all resources\n// associated with it.\nfunc (e *endpoint) Close() {\n+ notify := func() bool {\ne.mu.Lock()\n- e.shutdownFlags = tcpip.ShutdownRead | tcpip.ShutdownWrite\n- switch e.state {\n- case stateBound, stateConnected:\n- bindToDevice := tcpip.NICID(e.ops.GetBindToDevice())\n- e.stack.UnregisterTransportEndpoint([]tcpip.NetworkProtocolNumber{e.NetProto}, e.TransProto, e.ID, e, ports.Flags{}, bindToDevice)\n+ defer e.mu.Unlock()\n+\n+ switch state := e.net.State(); state {\n+ case transport.DatagramEndpointStateInitial:\n+ case transport.DatagramEndpointStateClosed:\n+ return false\n+ case transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected:\n+ info := e.net.Info()\n+ info.ID.LocalPort = e.ident\n+ e.stack.UnregisterTransportEndpoint([]tcpip.NetworkProtocolNumber{info.NetProto}, e.transProto, info.ID, e, ports.Flags{}, tcpip.NICID(e.ops.GetBindToDevice()))\n+ default:\n+ panic(fmt.Sprintf(\"unhandled state = %s\", state))\n}\n- // Close the receive list and drain it.\n+ e.net.Shutdown()\n+ e.net.Close()\n+\ne.rcvMu.Lock()\n+ defer e.rcvMu.Unlock()\ne.rcvClosed = true\ne.rcvBufSize = 0\nfor !e.rcvList.Empty() {\np := e.rcvList.Front()\ne.rcvList.Remove(p)\n}\n- e.rcvMu.Unlock()\n- if e.route != nil {\n- e.route.Release()\n- e.route = nil\n- }\n-\n- // Update the state.\n- e.state = stateClosed\n-\n- e.mu.Unlock()\n+ return true\n+ }()\n+ if notify {\ne.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.ReadableEvents | waiter.WritableEvents)\n}\n+}\n// ModerateRecvBuf implements tcpip.Endpoint.ModerateRecvBuf.\nfunc (*endpoint) ModerateRecvBuf(int) {}\n// SetOwner implements tcpip.Endpoint.SetOwner.\nfunc (e *endpoint) SetOwner(owner tcpip.PacketOwner) {\n- e.owner = owner\n+ e.net.SetOwner(owner)\n}\n// Read implements tcpip.Endpoint.Read.\n@@ -214,13 +202,12 @@ func (e *endpoint) Read(dst io.Writer, opts tcpip.ReadOptions) (tcpip.ReadResult\n//\n// Returns true for retry if preparation should be retried.\n// +checklocks:e.mu\n-func (e *endpoint) prepareForWrite(to *tcpip.FullAddress) (retry bool, err tcpip.Error) {\n- switch e.state {\n- case stateInitial:\n- case stateConnected:\n+func (e *endpoint) prepareForWriteInner(to *tcpip.FullAddress) (retry bool, err tcpip.Error) {\n+ switch e.net.State() {\n+ case transport.DatagramEndpointStateInitial:\n+ case transport.DatagramEndpointStateConnected:\nreturn false, nil\n-\n- case stateBound:\n+ case transport.DatagramEndpointStateBound:\nif to == nil {\nreturn false, &tcpip.ErrDestinationRequired{}\n}\n@@ -235,7 +222,7 @@ func (e *endpoint) prepareForWrite(to *tcpip.FullAddress) (retry bool, err tcpip\n// The state changed when we released the shared locked and re-acquired\n// it in exclusive mode. Try again.\n- if e.state != stateInitial {\n+ if e.net.State() != transport.DatagramEndpointStateInitial {\nreturn true, nil\n}\n@@ -270,27 +257,15 @@ func (e *endpoint) Write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\nreturn n, err\n}\n-func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcpip.Error) {\n- // MSG_MORE is unimplemented. (This also means that MSG_EOR is a no-op.)\n- if opts.More {\n- return 0, &tcpip.ErrInvalidOptionValue{}\n- }\n-\n- to := opts.To\n-\n+func (e *endpoint) prepareForWrite(opts tcpip.WriteOptions) (network.WriteContext, uint16, tcpip.Error) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n- // If we've shutdown with SHUT_WR we are in an invalid state for sending.\n- if e.shutdownFlags&tcpip.ShutdownWrite != 0 {\n- return 0, &tcpip.ErrClosedForSend{}\n- }\n-\n// Prepare for write.\nfor {\n- retry, err := e.prepareForWrite(to)\n+ retry, err := e.prepareForWriteInner(opts.To)\nif err != nil {\n- return 0, err\n+ return network.WriteContext{}, 0, err\n}\nif !retry {\n@@ -298,36 +273,16 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\n}\n}\n- route := e.route\n- if to != nil {\n- // Reject destination address if it goes through a different\n- // NIC than the endpoint was bound to.\n- nicID := to.NIC\n- if nicID == 0 {\n- nicID = tcpip.NICID(e.ops.GetBindToDevice())\n- }\n- if e.BindNICID != 0 {\n- if nicID != 0 && nicID != e.BindNICID {\n- return 0, &tcpip.ErrNoRoute{}\n- }\n-\n- nicID = e.BindNICID\n+ ctx, err := e.net.AcquireContextForWrite(opts)\n+ return ctx, e.ident, err\n}\n- dst, netProto, err := e.checkV4MappedLocked(*to)\n- if err != nil {\n- return 0, err\n- }\n-\n- // Find the endpoint.\n- r, err := e.stack.FindRoute(nicID, e.BindAddr, dst.Addr, netProto, false /* multicastLoop */)\n+func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcpip.Error) {\n+ ctx, ident, err := e.prepareForWrite(opts)\nif err != nil {\nreturn 0, err\n}\n- defer r.Release()\n-\n- route = r\n- }\n+ defer ctx.Release()\n// TODO(https://gvisor.dev/issue/6538): Avoid this allocation.\nv := make([]byte, p.Len())\n@@ -335,18 +290,19 @@ func (e *endpoint) write(p tcpip.Payloader, opts tcpip.WriteOptions) (int64, tcp\nreturn 0, &tcpip.ErrBadBuffer{}\n}\n- var err tcpip.Error\n- switch e.NetProto {\n+ switch netProto, pktInfo := e.net.NetProto(), ctx.PacketInfo(); netProto {\ncase header.IPv4ProtocolNumber:\n- err = send4(route, e.ID.LocalPort, v, e.ttl, e.owner)\n-\n- case header.IPv6ProtocolNumber:\n- err = send6(route, e.ID.LocalPort, v, e.ttl)\n+ if err := send4(e.stack, &ctx, ident, v, pktInfo.MaxHeaderLength); err != nil {\n+ return 0, err\n}\n- if err != nil {\n+ case header.IPv6ProtocolNumber:\n+ if err := send6(e.stack, &ctx, ident, v, pktInfo.LocalAddress, pktInfo.RemoteAddress, pktInfo.MaxHeaderLength); err != nil {\nreturn 0, err\n}\n+ default:\n+ panic(fmt.Sprintf(\"unhandled network protocol = %d\", netProto))\n+ }\nreturn int64(len(v)), nil\n}\n@@ -358,24 +314,17 @@ func (e *endpoint) HasNIC(id int32) bool {\nreturn e.stack.HasNIC(tcpip.NICID(id))\n}\n-// SetSockOpt sets a socket option.\n-func (*endpoint) SetSockOpt(tcpip.SettableSocketOption) tcpip.Error {\n- return nil\n+// SetSockOpt implements tcpip.Endpoint.\n+func (e *endpoint) SetSockOpt(opt tcpip.SettableSocketOption) tcpip.Error {\n+ return e.net.SetSockOpt(opt)\n}\n-// SetSockOptInt sets a socket option. Currently not supported.\n+// SetSockOptInt implements tcpip.Endpoint.\nfunc (e *endpoint) SetSockOptInt(opt tcpip.SockOptInt, v int) tcpip.Error {\n- switch opt {\n- case tcpip.TTLOption:\n- e.mu.Lock()\n- e.ttl = uint8(v)\n- e.mu.Unlock()\n-\n- }\n- return nil\n+ return e.net.SetSockOptInt(opt, v)\n}\n-// GetSockOptInt implements tcpip.Endpoint.GetSockOptInt.\n+// GetSockOptInt implements tcpip.Endpoint.\nfunc (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, tcpip.Error) {\nswitch opt {\ncase tcpip.ReceiveQueueSizeOption:\n@@ -388,31 +337,24 @@ func (e *endpoint) GetSockOptInt(opt tcpip.SockOptInt) (int, tcpip.Error) {\ne.rcvMu.Unlock()\nreturn v, nil\n- case tcpip.TTLOption:\n- e.rcvMu.Lock()\n- v := int(e.ttl)\n- e.rcvMu.Unlock()\n- return v, nil\n-\ndefault:\n- return -1, &tcpip.ErrUnknownProtocolOption{}\n+ return e.net.GetSockOptInt(opt)\n}\n}\n-// GetSockOpt implements tcpip.Endpoint.GetSockOpt.\n-func (*endpoint) GetSockOpt(tcpip.GettableSocketOption) tcpip.Error {\n- return &tcpip.ErrUnknownProtocolOption{}\n+// GetSockOpt implements tcpip.Endpoint.\n+func (e *endpoint) GetSockOpt(opt tcpip.GettableSocketOption) tcpip.Error {\n+ return e.net.GetSockOpt(opt)\n}\n-func send4(r *stack.Route, ident uint16, data buffer.View, ttl uint8, owner tcpip.PacketOwner) tcpip.Error {\n+func send4(s *stack.Stack, ctx *network.WriteContext, ident uint16, data buffer.View, maxHeaderLength uint16) tcpip.Error {\nif len(data) < header.ICMPv4MinimumSize {\nreturn &tcpip.ErrInvalidEndpointState{}\n}\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.ICMPv4MinimumSize + int(r.MaxHeaderLength()),\n+ ReserveHeaderBytes: header.ICMPv4MinimumSize + int(maxHeaderLength),\n})\n- pkt.Owner = owner\nicmpv4 := header.ICMPv4(pkt.TransportHeader().Push(header.ICMPv4MinimumSize))\npkt.TransportProtocolNumber = header.ICMPv4ProtocolNumber\n@@ -427,36 +369,31 @@ func send4(r *stack.Route, ident uint16, data buffer.View, ttl uint8, owner tcpi\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- // Because this icmp endpoint is implemented in the transport layer, we can\n- // only increment the 'stack-wide' stats but we can't increment the\n- // 'per-NetworkEndpoint' stats.\n- sentStat := r.Stats().ICMP.V4.PacketsSent.EchoRequest\n-\nicmpv4.SetChecksum(0)\nicmpv4.SetChecksum(^header.Checksum(icmpv4, header.Checksum(data, 0)))\n-\npkt.Data().AppendView(data)\n- if ttl == 0 {\n- ttl = r.DefaultTTL()\n- }\n+ // Because this icmp endpoint is implemented in the transport layer, we can\n+ // only increment the 'stack-wide' stats but we can't increment the\n+ // 'per-NetworkEndpoint' stats.\n+ stats := s.Stats().ICMP.V4.PacketsSent\n- if err := r.WritePacket(stack.NetworkHeaderParams{Protocol: header.ICMPv4ProtocolNumber, TTL: ttl, TOS: stack.DefaultTOS}, pkt); err != nil {\n- r.Stats().ICMP.V4.PacketsSent.Dropped.Increment()\n+ if err := ctx.WritePacket(pkt, false /* headerIncluded */); err != nil {\n+ stats.Dropped.Increment()\nreturn err\n}\n- sentStat.Increment()\n+ stats.EchoRequest.Increment()\nreturn nil\n}\n-func send6(r *stack.Route, ident uint16, data buffer.View, ttl uint8) tcpip.Error {\n+func send6(s *stack.Stack, ctx *network.WriteContext, ident uint16, data buffer.View, src, dst tcpip.Address, maxHeaderLength uint16) tcpip.Error {\nif len(data) < header.ICMPv6EchoMinimumSize {\nreturn &tcpip.ErrInvalidEndpointState{}\n}\npkt := stack.NewPacketBuffer(stack.PacketBufferOptions{\n- ReserveHeaderBytes: header.ICMPv6MinimumSize + int(r.MaxHeaderLength()),\n+ ReserveHeaderBytes: header.ICMPv6MinimumSize + int(maxHeaderLength),\n})\nicmpv6 := header.ICMPv6(pkt.TransportHeader().Push(header.ICMPv6MinimumSize))\n@@ -469,43 +406,31 @@ func send6(r *stack.Route, ident uint16, data buffer.View, ttl uint8) tcpip.Erro\nif icmpv6.Type() != header.ICMPv6EchoRequest || icmpv6.Code() != 0 {\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- // Because this icmp endpoint is implemented in the transport layer, we can\n- // only increment the 'stack-wide' stats but we can't increment the\n- // 'per-NetworkEndpoint' stats.\n- sentStat := r.Stats().ICMP.V6.PacketsSent.EchoRequest\npkt.Data().AppendView(data)\ndataRange := pkt.Data().AsRange()\nicmpv6.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{\nHeader: icmpv6,\n- Src: r.LocalAddress(),\n- Dst: r.RemoteAddress(),\n+ Src: src,\n+ Dst: dst,\nPayloadCsum: dataRange.Checksum(),\nPayloadLen: dataRange.Size(),\n}))\n- if ttl == 0 {\n- ttl = r.DefaultTTL()\n- }\n+ // Because this icmp endpoint is implemented in the transport layer, we can\n+ // only increment the 'stack-wide' stats but we can't increment the\n+ // 'per-NetworkEndpoint' stats.\n+ stats := s.Stats().ICMP.V6.PacketsSent\n- if err := r.WritePacket(stack.NetworkHeaderParams{Protocol: header.ICMPv6ProtocolNumber, TTL: ttl, TOS: stack.DefaultTOS}, pkt); err != nil {\n- r.Stats().ICMP.V6.PacketsSent.Dropped.Increment()\n+ if err := ctx.WritePacket(pkt, false /* headerIncluded */); err != nil {\n+ stats.Dropped.Increment()\n+ return err\n}\n- sentStat.Increment()\n+ stats.EchoRequest.Increment()\nreturn nil\n}\n-// checkV4MappedLocked determines the effective network protocol and converts\n-// addr to its canonical form.\n-func (e *endpoint) checkV4MappedLocked(addr tcpip.FullAddress) (tcpip.FullAddress, tcpip.NetworkProtocolNumber, tcpip.Error) {\n- unwrapped, netProto, err := e.TransportEndpointInfo.AddrNetProtoLocked(addr, false /* v6only */)\n- if err != nil {\n- return tcpip.FullAddress{}, 0, err\n- }\n- return unwrapped, netProto, nil\n-}\n-\n// Disconnect implements tcpip.Endpoint.Disconnect.\nfunc (*endpoint) Disconnect() tcpip.Error {\nreturn &tcpip.ErrNotSupported{}\n@@ -516,59 +441,21 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- nicID := addr.NIC\n- localPort := uint16(0)\n- switch e.state {\n- case stateInitial:\n- case stateBound, stateConnected:\n- localPort = e.ID.LocalPort\n- if e.BindNICID == 0 {\n- break\n- }\n+ err := e.net.ConnectAndThen(addr, func(netProto tcpip.NetworkProtocolNumber, previousID, nextID stack.TransportEndpointID) tcpip.Error {\n+ nextID.LocalPort = e.ident\n- if nicID != 0 && nicID != e.BindNICID {\n- return &tcpip.ErrInvalidEndpointState{}\n- }\n-\n- nicID = e.BindNICID\n- default:\n- return &tcpip.ErrInvalidEndpointState{}\n- }\n-\n- addr, netProto, err := e.checkV4MappedLocked(addr)\n- if err != nil {\n- return err\n- }\n-\n- // Find a route to the desired destination.\n- r, err := e.stack.FindRoute(nicID, e.BindAddr, addr.Addr, netProto, false /* multicastLoop */)\n+ nextID, err := e.registerWithStack(netProto, nextID)\nif err != nil {\nreturn err\n}\n- id := stack.TransportEndpointID{\n- LocalAddress: r.LocalAddress(),\n- LocalPort: localPort,\n- RemoteAddress: r.RemoteAddress(),\n- }\n-\n- // Even if we're connected, this endpoint can still be used to send\n- // packets on a different network protocol, so we register both even if\n- // v6only is set to false and this is an ipv6 endpoint.\n- netProtos := []tcpip.NetworkProtocolNumber{netProto}\n-\n- id, err = e.registerWithStack(nicID, netProtos, id)\n+ e.ident = nextID.LocalPort\n+ return nil\n+ })\nif err != nil {\n- r.Release()\nreturn err\n}\n- e.ID = id\n- e.route = r\n- e.RegisterNICID = nicID\n-\n- e.state = stateConnected\n-\ne.rcvMu.Lock()\ne.rcvReady = true\ne.rcvMu.Unlock()\n@@ -586,10 +473,19 @@ func (*endpoint) ConnectEndpoint(tcpip.Endpoint) tcpip.Error {\nfunc (e *endpoint) Shutdown(flags tcpip.ShutdownFlags) tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- e.shutdownFlags |= flags\n- if e.state != stateConnected {\n+ switch state := e.net.State(); state {\n+ case transport.DatagramEndpointStateInitial, transport.DatagramEndpointStateClosed:\nreturn &tcpip.ErrNotConnected{}\n+ case transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected:\n+ default:\n+ panic(fmt.Sprintf(\"unhandled state = %s\", state))\n+ }\n+\n+ if flags&tcpip.ShutdownWrite != 0 {\n+ if err := e.net.Shutdown(); err != nil {\n+ return err\n+ }\n}\nif flags&tcpip.ShutdownRead != 0 {\n@@ -616,19 +512,18 @@ func (*endpoint) Accept(*tcpip.FullAddress) (tcpip.Endpoint, *waiter.Queue, tcpi\nreturn nil, nil, &tcpip.ErrNotSupported{}\n}\n-func (e *endpoint) registerWithStack(_ tcpip.NICID, netProtos []tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, tcpip.Error) {\n+func (e *endpoint) registerWithStack(netProto tcpip.NetworkProtocolNumber, id stack.TransportEndpointID) (stack.TransportEndpointID, tcpip.Error) {\nbindToDevice := tcpip.NICID(e.ops.GetBindToDevice())\nif id.LocalPort != 0 {\n// The endpoint already has a local port, just attempt to\n// register it.\n- err := e.stack.RegisterTransportEndpoint(netProtos, e.TransProto, id, e, ports.Flags{}, bindToDevice)\n- return id, err\n+ return id, e.stack.RegisterTransportEndpoint([]tcpip.NetworkProtocolNumber{netProto}, e.transProto, id, e, ports.Flags{}, bindToDevice)\n}\n// We need to find a port for the endpoint.\n_, err := e.stack.PickEphemeralPort(e.stack.Rand(), func(p uint16) (bool, tcpip.Error) {\nid.LocalPort = p\n- err := e.stack.RegisterTransportEndpoint(netProtos, e.TransProto, id, e, ports.Flags{}, bindToDevice)\n+ err := e.stack.RegisterTransportEndpoint([]tcpip.NetworkProtocolNumber{netProto}, e.transProto, id, e, ports.Flags{}, bindToDevice)\nswitch err.(type) {\ncase nil:\nreturn true, nil\n@@ -645,41 +540,26 @@ func (e *endpoint) registerWithStack(_ tcpip.NICID, netProtos []tcpip.NetworkPro\nfunc (e *endpoint) bindLocked(addr tcpip.FullAddress) tcpip.Error {\n// Don't allow binding once endpoint is not in the initial state\n// anymore.\n- if e.state != stateInitial {\n+ if e.net.State() != transport.DatagramEndpointStateInitial {\nreturn &tcpip.ErrInvalidEndpointState{}\n}\n- addr, netProto, err := e.checkV4MappedLocked(addr)\n- if err != nil {\n- return err\n- }\n-\n- // Expand netProtos to include v4 and v6 if the caller is binding to a\n- // wildcard (empty) address, and this is an IPv6 endpoint with v6only\n- // set to false.\n- netProtos := []tcpip.NetworkProtocolNumber{netProto}\n-\n- if len(addr.Addr) != 0 {\n- // A local address was specified, verify that it's valid.\n- if e.stack.CheckLocalAddress(addr.NIC, netProto, addr.Addr) == 0 {\n- return &tcpip.ErrBadLocalAddress{}\n- }\n- }\n-\n+ err := e.net.BindAndThen(addr, func(boundNetProto tcpip.NetworkProtocolNumber, boundAddr tcpip.Address) tcpip.Error {\nid := stack.TransportEndpointID{\nLocalPort: addr.Port,\nLocalAddress: addr.Addr,\n}\n- id, err = e.registerWithStack(addr.NIC, netProtos, id)\n+ id, err := e.registerWithStack(boundNetProto, id)\nif err != nil {\nreturn err\n}\n- e.ID = id\n- e.RegisterNICID = addr.NIC\n-\n- // Mark endpoint as bound.\n- e.state = stateBound\n+ e.ident = id.LocalPort\n+ return nil\n+ })\n+ if err != nil {\n+ return err\n+ }\ne.rcvMu.Lock()\ne.rcvReady = true\n@@ -692,7 +572,7 @@ func (e *endpoint) isBroadcastOrMulticast(nicID tcpip.NICID, addr tcpip.Address)\nreturn addr == header.IPv4Broadcast ||\nheader.IsV4MulticastAddress(addr) ||\nheader.IsV6MulticastAddress(addr) ||\n- e.stack.IsSubnetBroadcast(nicID, e.NetProto, addr)\n+ e.stack.IsSubnetBroadcast(nicID, e.net.NetProto(), addr)\n}\n// Bind binds the endpoint to a specific local address and port.\n@@ -705,15 +585,7 @@ func (e *endpoint) Bind(addr tcpip.FullAddress) tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- err := e.bindLocked(addr)\n- if err != nil {\n- return err\n- }\n-\n- e.BindNICID = addr.NIC\n- e.BindAddr = addr.Addr\n-\n- return nil\n+ return e.bindLocked(addr)\n}\n// GetLocalAddress returns the address to which the endpoint is bound.\n@@ -721,11 +593,9 @@ func (e *endpoint) GetLocalAddress() (tcpip.FullAddress, tcpip.Error) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n- return tcpip.FullAddress{\n- NIC: e.RegisterNICID,\n- Addr: e.ID.LocalAddress,\n- Port: e.ID.LocalPort,\n- }, nil\n+ addr := e.net.GetLocalAddress()\n+ addr.Port = e.ident\n+ return addr, nil\n}\n// GetRemoteAddress returns the address to which the endpoint is connected.\n@@ -733,15 +603,11 @@ func (e *endpoint) GetRemoteAddress() (tcpip.FullAddress, tcpip.Error) {\ne.mu.RLock()\ndefer e.mu.RUnlock()\n- if e.state != stateConnected {\n- return tcpip.FullAddress{}, &tcpip.ErrNotConnected{}\n+ if addr, connected := e.net.GetRemoteAddress(); connected {\n+ return addr, nil\n}\n- return tcpip.FullAddress{\n- NIC: e.RegisterNICID,\n- Addr: e.ID.RemoteAddress,\n- Port: e.ID.RemotePort,\n- }, nil\n+ return tcpip.FullAddress{}, &tcpip.ErrNotConnected{}\n}\n// Readiness returns the current readiness of the endpoint. For example, if\n@@ -766,7 +632,7 @@ func (e *endpoint) Readiness(mask waiter.EventMask) waiter.EventMask {\n// endpoint.\nfunc (e *endpoint) HandlePacket(id stack.TransportEndpointID, pkt *stack.PacketBuffer) {\n// Only accept echo replies.\n- switch e.NetProto {\n+ switch e.net.NetProto() {\ncase header.IPv4ProtocolNumber:\nh := header.ICMPv4(pkt.TransportHeader().View())\nif len(h) < header.ICMPv4MinimumSize || h.Type() != header.ICMPv4EchoReply {\n@@ -840,9 +706,9 @@ func (e *endpoint) State() uint32 {\n// Info returns a copy of the endpoint info.\nfunc (e *endpoint) Info() tcpip.EndpointInfo {\ne.mu.RLock()\n- // Make a copy of the endpoint info.\n- ret := e.TransportEndpointInfo\n- e.mu.RUnlock()\n+ defer e.mu.RUnlock()\n+ ret := e.net.Info()\n+ ret.ID.LocalPort = e.ident\nreturn &ret\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint_state.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint_state.go",
"diff": "package icmp\nimport (\n+ \"fmt\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport\"\n)\n// saveReceivedAt is invoked by stateify.\n@@ -61,29 +63,24 @@ func (e *endpoint) beforeSave() {\n// Resume implements tcpip.ResumableEndpoint.Resume.\nfunc (e *endpoint) Resume(s *stack.Stack) {\ne.thaw()\n+\n+ e.net.Resume(s)\n+\ne.stack = s\ne.ops.InitHandler(e, e.stack, tcpip.GetStackSendBufferLimits, tcpip.GetStackReceiveBufferLimits)\n- if e.state != stateBound && e.state != stateConnected {\n- return\n- }\n-\n+ switch state := e.net.State(); state {\n+ case transport.DatagramEndpointStateInitial, transport.DatagramEndpointStateClosed:\n+ case transport.DatagramEndpointStateBound, transport.DatagramEndpointStateConnected:\nvar err tcpip.Error\n- if e.state == stateConnected {\n- e.route, err = e.stack.FindRoute(e.RegisterNICID, e.BindAddr, e.ID.RemoteAddress, e.NetProto, false /* multicastLoop */)\n+ info := e.net.Info()\n+ info.ID.LocalPort = e.ident\n+ info.ID, err = e.registerWithStack(info.NetProto, info.ID)\nif err != nil {\n- panic(err)\n+ panic(fmt.Sprintf(\"e.registerWithStack(%d, %#v): %s\", info.NetProto, info.ID, err))\n}\n-\n- e.ID.LocalAddress = e.route.LocalAddress()\n- } else if len(e.ID.LocalAddress) != 0 { // stateBound\n- if e.stack.CheckLocalAddress(e.RegisterNICID, e.NetProto, e.ID.LocalAddress) == 0 {\n- panic(&tcpip.ErrBadLocalAddress{})\n- }\n- }\n-\n- e.ID, err = e.registerWithStack(e.RegisterNICID, []tcpip.NetworkProtocolNumber{e.NetProto}, e.ID)\n- if err != nil {\n- panic(err)\n+ e.ident = info.ID.LocalPort\n+ default:\n+ panic(fmt.Sprintf(\"unhandled state = %s\", state))\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/internal/network/BUILD",
"new_path": "pkg/tcpip/transport/internal/network/BUILD",
"diff": "@@ -9,6 +9,7 @@ go_library(\n\"endpoint_state.go\",\n],\nvisibility = [\n+ \"//pkg/tcpip/transport/icmp:__pkg__\",\n\"//pkg/tcpip/transport/raw:__pkg__\",\n\"//pkg/tcpip/transport/udp:__pkg__\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ipv4_datagram_based_socket_unbound_loopback.cc",
"new_path": "test/syscalls/linux/socket_ipv4_datagram_based_socket_unbound_loopback.cc",
"diff": "namespace gvisor {\nnamespace testing {\n-INSTANTIATE_TEST_SUITE_P(IPv4Sockets, IPv4DatagramBasedUnboundSocketTest,\n+INSTANTIATE_TEST_SUITE_P(\n+ IPv4Sockets, IPv4DatagramBasedUnboundSocketTest,\n::testing::ValuesIn(ApplyVecToVec<SocketKind>(\n- {IPv4UDPUnboundSocket, IPv4RawUDPUnboundSocket},\n- AllBitwiseCombinations(List<int>{\n- 0, SOCK_NONBLOCK}))));\n+ {IPv4UDPUnboundSocket, IPv4RawUDPUnboundSocket, ICMPUnboundSocket},\n+ AllBitwiseCombinations(List<int>{0, SOCK_NONBLOCK}))));\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Compose ICMP endpoint with datagram-based endpoint
An ICMP endpoint's write path can use the datagram-based endpoint.
Updates #6565.
Test: Datagram-based generic socket + ICMP/ping syscall tests.
PiperOrigin-RevId: 398539844 |
260,004 | 23.09.2021 13:09:30 | 25,200 | 8627db006bda75fd81d17bf4535b381abafaed8a | Pass AddressableEndpoint to IPTables
...instead of an address.
This allows a later change to more precisely select an address
based on the NAT type (source vs. destination NAT). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/targets.go",
"new_path": "pkg/sentry/socket/netfilter/targets.go",
"diff": "@@ -647,7 +647,7 @@ func (jt *JumpTarget) id() targetID {\n}\n// Action implements stack.Target.Action.\n-func (jt *JumpTarget) Action(*stack.PacketBuffer, *stack.ConnTrack, stack.Hook, *stack.Route, tcpip.Address) (stack.RuleVerdict, int) {\n+func (jt *JumpTarget) Action(*stack.PacketBuffer, *stack.ConnTrack, stack.Hook, *stack.Route, stack.AddressableEndpoint) (stack.RuleVerdict, int) {\nreturn stack.RuleJump, jt.RuleNum\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv4/ipv4.go",
"new_path": "pkg/tcpip/network/ipv4/ipv4.go",
"diff": "@@ -841,7 +841,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e.MainAddress().Address, inNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e, inNicName); !ok {\n// iptables is telling us to drop the packet.\nstats.IPTablesPreroutingDropped.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/ipv6.go",
"new_path": "pkg/tcpip/network/ipv6/ipv6.go",
"diff": "@@ -1100,7 +1100,7 @@ func (e *endpoint) HandlePacket(pkt *stack.PacketBuffer) {\n// Loopback traffic skips the prerouting chain.\ninNicName := e.protocol.stack.FindNICNameFromID(e.nic.ID())\n- if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e.MainAddress().Address, inNicName); !ok {\n+ if ok := e.protocol.stack.IPTables().CheckPrerouting(pkt, e, inNicName); !ok {\n// iptables is telling us to drop the packet.\nstats.IPTablesPreroutingDropped.Increment()\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -270,8 +270,8 @@ const (\n// must be dropped if false is returned.\n//\n// Precondition: The packet's network and transport header must be set.\n-func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, preroutingAddr tcpip.Address, inNicName string) bool {\n- return it.check(Prerouting, pkt, nil /* route */, preroutingAddr, inNicName, \"\" /* outNicName */)\n+func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\n+ return it.check(Prerouting, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */)\n}\n// CheckInput performs the input hook on the packet.\n@@ -281,7 +281,7 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, preroutingAddr tcpip.Addr\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n- return it.check(Input, pkt, nil /* route */, \"\" /* preroutingAddr */, inNicName, \"\" /* outNicName */)\n+ return it.check(Input, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */)\n}\n// CheckForward performs the forward hook on the packet.\n@@ -291,7 +291,7 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\n- return it.check(Forward, pkt, nil /* route */, \"\" /* preroutingAddr */, inNicName, outNicName)\n+ return it.check(Forward, pkt, nil /* route */, nil /* addressEP */, inNicName, outNicName)\n}\n// CheckOutput performs the output hook on the packet.\n@@ -301,7 +301,7 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\n- return it.check(Output, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName)\n+ return it.check(Output, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName)\n}\n// CheckPostrouting performs the postrouting hook on the packet.\n@@ -311,7 +311,7 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, outNicName string) bool {\n- return it.check(Postrouting, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName)\n+ return it.check(Postrouting, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName)\n}\n// check runs pkt through the rules for hook. It returns true when the packet\n@@ -319,7 +319,7 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, outNicName str\n// dropped.\n//\n// Precondition: The packet's network and transport header must be set.\n-func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, preroutingAddr tcpip.Address, inNicName, outNicName string) bool {\n+func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool {\nif pkt.NetworkProtocolNumber != header.IPv4ProtocolNumber && pkt.NetworkProtocolNumber != header.IPv6ProtocolNumber {\nreturn true\n}\n@@ -350,7 +350,7 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, preroutingAddr\ntable = it.v4Tables[tableID]\n}\nruleIdx := table.BuiltinChains[hook]\n- switch verdict := it.checkChain(hook, pkt, table, ruleIdx, r, preroutingAddr, inNicName, outNicName); verdict {\n+ switch verdict := it.checkChain(hook, pkt, table, ruleIdx, r, addressEP, inNicName, outNicName); verdict {\n// If the table returns Accept, move on to the next table.\ncase chainAccept:\ncontinue\n@@ -361,7 +361,7 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, preroutingAddr\n// Any Return from a built-in chain means we have to\n// call the underflow.\nunderflow := table.Rules[table.Underflows[hook]]\n- switch v, _ := underflow.Target.Action(pkt, &it.connections, hook, r, preroutingAddr); v {\n+ switch v, _ := underflow.Target.Action(pkt, &it.connections, hook, r, addressEP); v {\ncase RuleAccept:\ncontinue\ncase RuleDrop:\n@@ -453,7 +453,7 @@ func (it *IPTables) CheckPostroutingPackets(pkts PacketBufferList, r *Route, out\nfunc (it *IPTables) checkPackets(hook Hook, pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\nif !pkt.NatDone {\n- if ok := it.check(hook, pkt, r, \"\" /* preroutingAddr */, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := it.check(hook, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName); !ok {\nif drop == nil {\ndrop = make(map[*PacketBuffer]struct{})\n}\n@@ -473,11 +473,11 @@ func (it *IPTables) checkPackets(hook Hook, pkts PacketBufferList, r *Route, out\n// Preconditions:\n// * pkt is a IPv4 packet of at least length header.IPv4MinimumSize.\n// * pkt.NetworkHeader is not nil.\n-func (it *IPTables) checkChain(hook Hook, pkt *PacketBuffer, table Table, ruleIdx int, r *Route, preroutingAddr tcpip.Address, inNicName, outNicName string) chainVerdict {\n+func (it *IPTables) checkChain(hook Hook, pkt *PacketBuffer, table Table, ruleIdx int, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) chainVerdict {\n// Start from ruleIdx and walk the list of rules until a rule gives us\n// a verdict.\nfor ruleIdx < len(table.Rules) {\n- switch verdict, jumpTo := it.checkRule(hook, pkt, table, ruleIdx, r, preroutingAddr, inNicName, outNicName); verdict {\n+ switch verdict, jumpTo := it.checkRule(hook, pkt, table, ruleIdx, r, addressEP, inNicName, outNicName); verdict {\ncase RuleAccept:\nreturn chainAccept\n@@ -494,7 +494,7 @@ func (it *IPTables) checkChain(hook Hook, pkt *PacketBuffer, table Table, ruleId\nruleIdx++\ncontinue\n}\n- switch verdict := it.checkChain(hook, pkt, table, jumpTo, r, preroutingAddr, inNicName, outNicName); verdict {\n+ switch verdict := it.checkChain(hook, pkt, table, jumpTo, r, addressEP, inNicName, outNicName); verdict {\ncase chainAccept:\nreturn chainAccept\ncase chainDrop:\n@@ -520,7 +520,7 @@ func (it *IPTables) checkChain(hook Hook, pkt *PacketBuffer, table Table, ruleId\n// Preconditions:\n// * pkt is a IPv4 packet of at least length header.IPv4MinimumSize.\n// * pkt.NetworkHeader is not nil.\n-func (it *IPTables) checkRule(hook Hook, pkt *PacketBuffer, table Table, ruleIdx int, r *Route, preroutingAddr tcpip.Address, inNicName, outNicName string) (RuleVerdict, int) {\n+func (it *IPTables) checkRule(hook Hook, pkt *PacketBuffer, table Table, ruleIdx int, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) (RuleVerdict, int) {\nrule := table.Rules[ruleIdx]\n// Check whether the packet matches the IP header filter.\n@@ -543,7 +543,7 @@ func (it *IPTables) checkRule(hook Hook, pkt *PacketBuffer, table Table, ruleIdx\n}\n// All the matchers matched, so run the target.\n- return rule.Target.Action(pkt, &it.connections, hook, r, preroutingAddr)\n+ return rule.Target.Action(pkt, &it.connections, hook, r, addressEP)\n}\n// OriginalDst returns the original destination of redirected connections. It\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -29,7 +29,7 @@ type AcceptTarget struct {\n}\n// Action implements Target.Action.\n-func (*AcceptTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int) {\n+func (*AcceptTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\nreturn RuleAccept, 0\n}\n@@ -40,7 +40,7 @@ type DropTarget struct {\n}\n// Action implements Target.Action.\n-func (*DropTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int) {\n+func (*DropTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\nreturn RuleDrop, 0\n}\n@@ -52,7 +52,7 @@ type ErrorTarget struct {\n}\n// Action implements Target.Action.\n-func (*ErrorTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int) {\n+func (*ErrorTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\nlog.Debugf(\"ErrorTarget triggered.\")\nreturn RuleDrop, 0\n}\n@@ -67,7 +67,7 @@ type UserChainTarget struct {\n}\n// Action implements Target.Action.\n-func (*UserChainTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int) {\n+func (*UserChainTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\npanic(\"UserChainTarget should never be called.\")\n}\n@@ -79,7 +79,7 @@ type ReturnTarget struct {\n}\n// Action implements Target.Action.\n-func (*ReturnTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int) {\n+func (*ReturnTarget) Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\nreturn RuleReturn, 0\n}\n@@ -97,7 +97,7 @@ type RedirectTarget struct {\n}\n// Action implements Target.Action.\n-func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Route, address tcpip.Address) (RuleVerdict, int) {\n+func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n// Sanity check.\nif rt.NetworkProtocol != pkt.NetworkProtocolNumber {\npanic(fmt.Sprintf(\n@@ -117,6 +117,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r\n// Change the address to loopback (127.0.0.1 or ::1) in Output and to\n// the primary address of the incoming interface in Prerouting.\n+ var address tcpip.Address\nswitch hook {\ncase Output:\nif pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber {\n@@ -125,7 +126,8 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r\naddress = header.IPv6Loopback\n}\ncase Prerouting:\n- // No-op, as address is already set correctly.\n+ // addressEP is expected to be set for the prerouting hook.\n+ address = addressEP.MainAddress().Address\ndefault:\npanic(\"redirect target is supported only on output and prerouting hooks\")\n}\n@@ -180,7 +182,7 @@ type SNATTarget struct {\n}\n// Action implements Target.Action.\n-func (st *SNATTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Route, address tcpip.Address) (RuleVerdict, int) {\n+func (st *SNATTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Route, _ AddressableEndpoint) (RuleVerdict, int) {\n// Sanity check.\nif st.NetworkProtocol != pkt.NetworkProtocolNumber {\npanic(fmt.Sprintf(\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_types.go",
"new_path": "pkg/tcpip/stack/iptables_types.go",
"diff": "@@ -352,5 +352,5 @@ type Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n// Jump, it also returns the index of the rule to jump to.\n- Action(*PacketBuffer, *ConnTrack, Hook, *Route, tcpip.Address) (RuleVerdict, int)\n+ Action(*PacketBuffer, *ConnTrack, Hook, *Route, AddressableEndpoint) (RuleVerdict, int)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Pass AddressableEndpoint to IPTables
...instead of an address.
This allows a later change to more precisely select an address
based on the NAT type (source vs. destination NAT).
PiperOrigin-RevId: 398559901 |
259,907 | 23.09.2021 23:31:17 | 25,200 | 12175748aba75c0b3be5b3981763c1a1f5e73763 | Allow lisafs client to send more data than MaxMessageSize using chunks.
The p9 client does the same. This allows applications to read/write >= 2MB of
data. This enables the read write benchmarks to work with lisafs.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/client_file.go",
"new_path": "pkg/lisafs/client_file.go",
"diff": "package lisafs\nimport (\n+ \"fmt\"\n+\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/context\"\n@@ -121,34 +123,84 @@ func (f *ClientFD) Sync(ctx context.Context) error {\nreturn err\n}\n+// chunkify applies fn to buf in chunks based on chunkSize.\n+func chunkify(chunkSize uint64, buf []byte, fn func([]byte, uint64) (uint64, error)) (uint64, error) {\n+ toProcess := uint64(len(buf))\n+ var (\n+ totalProcessed uint64\n+ curProcessed uint64\n+ off uint64\n+ err error\n+ )\n+ for {\n+ if totalProcessed == toProcess {\n+ return totalProcessed, nil\n+ }\n+\n+ if totalProcessed+chunkSize > toProcess {\n+ curProcessed, err = fn(buf[totalProcessed:], off)\n+ } else {\n+ curProcessed, err = fn(buf[totalProcessed:totalProcessed+chunkSize], off)\n+ }\n+ totalProcessed += curProcessed\n+ off += curProcessed\n+\n+ if err != nil {\n+ return totalProcessed, err\n+ }\n+\n+ // Return partial result immediately.\n+ if curProcessed < chunkSize {\n+ return totalProcessed, nil\n+ }\n+\n+ // If we received more bytes than we ever requested, this is a problem.\n+ if totalProcessed > toProcess {\n+ panic(fmt.Sprintf(\"bytes completed (%d)) > requested (%d)\", totalProcessed, toProcess))\n+ }\n+ }\n+}\n+\n// Read makes the PRead RPC.\nfunc (f *ClientFD) Read(ctx context.Context, dst []byte, offset uint64) (uint64, error) {\n+ var resp PReadResp\n+ // maxDataReadSize represents the maximum amount of data we can read at once\n+ // (maximum message size - metadata size present in resp). Uninitialized\n+ // resp.SizeBytes() correctly returns the metadata size only (since the read\n+ // buffer is empty).\n+ maxDataReadSize := uint64(f.client.maxMessageSize) - uint64(resp.SizeBytes())\n+ return chunkify(maxDataReadSize, dst, func(buf []byte, curOff uint64) (uint64, error) {\nreq := PReadReq{\n- Offset: offset,\n+ Offset: offset + curOff,\nFD: f.fd,\n- Count: uint32(len(dst)),\n+ Count: uint32(len(buf)),\n}\n- resp := PReadResp{\n// This will be unmarshalled into. Already set Buf so that we don't need to\n// allocate a temporary buffer during unmarshalling.\n// PReadResp.UnmarshalBytes expects this to be set.\n- Buf: dst,\n- }\n-\n+ resp.Buf = buf\nctx.UninterruptibleSleepStart(false)\nerr := f.client.SndRcvMessage(PRead, uint32(req.SizeBytes()), req.MarshalUnsafe, resp.UnmarshalBytes, nil)\nctx.UninterruptibleSleepFinish(false)\nreturn uint64(resp.NumBytes), err\n+ })\n}\n// Write makes the PWrite RPC.\nfunc (f *ClientFD) Write(ctx context.Context, src []byte, offset uint64) (uint64, error) {\n- req := PWriteReq{\n- Offset: primitive.Uint64(offset),\n+ var req PWriteReq\n+ // maxDataWriteSize represents the maximum amount of data we can write at\n+ // once (maximum message size - metadata size present in req). Uninitialized\n+ // req.SizeBytes() correctly returns the metadata size only (since the write\n+ // buffer is empty).\n+ maxDataWriteSize := uint64(f.client.maxMessageSize) - uint64(req.SizeBytes())\n+ return chunkify(maxDataWriteSize, src, func(buf []byte, curOff uint64) (uint64, error) {\n+ req = PWriteReq{\n+ Offset: primitive.Uint64(offset + curOff),\nFD: f.fd,\n- NumBytes: primitive.Uint32(len(src)),\n- Buf: src,\n+ NumBytes: primitive.Uint32(len(buf)),\n+ Buf: buf,\n}\nvar resp PWriteResp\n@@ -156,6 +208,7 @@ func (f *ClientFD) Write(ctx context.Context, src []byte, offset uint64) (uint64\nerr := f.client.SndRcvMessage(PWrite, uint32(req.SizeBytes()), req.MarshalBytes, resp.UnmarshalUnsafe, nil)\nctx.UninterruptibleSleepFinish(false)\nreturn resp.Count, err\n+ })\n}\n// MkdirAt makes the MkdirAt RPC.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/lisafs/testsuite/testsuite.go",
"new_path": "pkg/lisafs/testsuite/testsuite.go",
"diff": "@@ -330,8 +330,8 @@ func testRegularFileIO(ctx context.Context, t *testing.T, tester Tester, root li\ndefer closeFD(ctx, t, fd)\ndefer unix.Close(hostFD)\n- // Test Read/Write RPCs.\n- data := make([]byte, 100)\n+ // Test Read/Write RPCs with 2MB of data to test IO in chunks.\n+ data := make([]byte, 1<<21)\nrand.Read(data)\nif err := writeFD(ctx, t, fd, 0, data); err != nil {\nt.Fatalf(\"write failed: %v\", err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow lisafs client to send more data than MaxMessageSize using chunks.
The p9 client does the same. This allows applications to read/write >= 2MB of
data. This enables the read write benchmarks to work with lisafs.
Updates #5466
PiperOrigin-RevId: 398659947 |
259,853 | 24.09.2021 11:22:56 | 25,200 | e3657847cb7edcecc3facc4c499fc0b154364487 | Update the comment for Task.netns
Task.netns can be accessed atomically, so Task.mu isn't needed to access it. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task.go",
"new_path": "pkg/sentry/kernel/task.go",
"diff": "@@ -511,8 +511,6 @@ type Task struct {\nnumaNodeMask uint64\n// netns is the task's network namespace. netns is never nil.\n- //\n- // netns is protected by mu.\nnetns inet.NamespaceAtomicPtr\n// If rseqPreempted is true, before the next call to p.Switch(),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update the comment for Task.netns
Task.netns can be accessed atomically, so Task.mu isn't needed to access it.
PiperOrigin-RevId: 398773947 |
259,929 | 27.09.2021 10:13:22 | 14,400 | b5ae22f201854698acfb64266bba662de5c5b12b | Minor documentation wording change | [
{
"change_type": "MODIFY",
"old_path": "g3doc/README.md",
"new_path": "g3doc/README.md",
"diff": "@@ -139,8 +139,8 @@ pipes, etc) are sent to the Gofer, described below.\nThe Gofer is a standard host process which is started with each container and\ncommunicates with the Sentry via the [9P protocol][9p] over a socket or shared\nmemory channel. The Sentry process is started in a restricted seccomp container\n-without access to file system resources. The Gofer mediates all access to the\n-these resources, providing an additional level of isolation.\n+without access to file system resources. The Gofer mediates all access to these\n+resources, providing an additional level of isolation.\n### Application {#application}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Minor documentation wording change |
259,868 | 27.09.2021 15:28:45 | 25,200 | e251f6cc5c2641e000846b35e4aa7f0d41c4b319 | Move `sighandling` package out of `sentry`. | [
{
"change_type": "RENAME",
"old_path": "pkg/sentry/sighandling/BUILD",
"new_path": "pkg/sighandling/BUILD",
"diff": "@@ -8,7 +8,7 @@ go_library(\n\"sighandling.go\",\n\"sighandling_unsafe.go\",\n],\n- visibility = [\"//pkg/sentry:internal\"],\n+ visibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/abi/linux\",\n\"@org_golang_x_sys//unix:go_default_library\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/sighandling/sighandling.go",
"new_path": "pkg/sighandling/sighandling.go",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "pkg/sentry/sighandling/sighandling_unsafe.go",
"new_path": "pkg/sighandling/sighandling_unsafe.go",
"diff": ""
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/BUILD",
"new_path": "runsc/boot/BUILD",
"diff": "@@ -80,7 +80,6 @@ go_library(\n\"//pkg/sentry/loader\",\n\"//pkg/sentry/pgalloc\",\n\"//pkg/sentry/platform\",\n- \"//pkg/sentry/sighandling\",\n\"//pkg/sentry/socket/hostinet\",\n\"//pkg/sentry/socket/netfilter\",\n\"//pkg/sentry/socket/netlink\",\n@@ -96,6 +95,7 @@ go_library(\n\"//pkg/sentry/usage\",\n\"//pkg/sentry/vfs\",\n\"//pkg/sentry/watchdog\",\n+ \"//pkg/sighandling\",\n\"//pkg/sync\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/link/ethernet\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -49,13 +49,13 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/loader\"\n\"gvisor.dev/gvisor/pkg/sentry/pgalloc\"\n\"gvisor.dev/gvisor/pkg/sentry/platform\"\n- \"gvisor.dev/gvisor/pkg/sentry/sighandling\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netfilter\"\n\"gvisor.dev/gvisor/pkg/sentry/syscalls/linux/vfs2\"\n\"gvisor.dev/gvisor/pkg/sentry/time\"\n\"gvisor.dev/gvisor/pkg/sentry/usage\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n\"gvisor.dev/gvisor/pkg/sentry/watchdog\"\n+ \"gvisor.dev/gvisor/pkg/sighandling\"\n\"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/ethernet\"\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -19,7 +19,7 @@ go_library(\n\"//pkg/cleanup\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n- \"//pkg/sentry/sighandling\",\n+ \"//pkg/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": "@@ -35,7 +35,7 @@ import (\n\"gvisor.dev/gvisor/pkg/cleanup\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n- \"gvisor.dev/gvisor/pkg/sentry/sighandling\"\n+ \"gvisor.dev/gvisor/pkg/sighandling\"\n\"gvisor.dev/gvisor/runsc/boot\"\n\"gvisor.dev/gvisor/runsc/cgroup\"\n\"gvisor.dev/gvisor/runsc/config\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move `sighandling` package out of `sentry`.
PiperOrigin-RevId: 399295737 |
259,868 | 28.09.2021 16:53:22 | 25,200 | 65698b627e81d0b078a5f993260f6359e22e7970 | Move `safecopy.ReplaceSignalHandler` into `sighandling` package. | [
{
"change_type": "MODIFY",
"old_path": "pkg/safecopy/BUILD",
"new_path": "pkg/safecopy/BUILD",
"diff": "@@ -18,9 +18,9 @@ go_library(\n],\nvisibility = [\"//:sandbox\"],\ndeps = [\n- \"//pkg/abi/linux\",\n\"//pkg/errors\",\n\"//pkg/errors/linuxerr\",\n+ \"//pkg/sighandling\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/safecopy/safecopy.go",
"new_path": "pkg/safecopy/safecopy.go",
"diff": "@@ -23,6 +23,7 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/errors\"\n\"gvisor.dev/gvisor/pkg/errors/linuxerr\"\n+ \"gvisor.dev/gvisor/pkg/sighandling\"\n)\n// SegvError is returned when a safecopy function receives SIGSEGV.\n@@ -132,10 +133,10 @@ func initializeAddresses() {\nfunc init() {\ninitializeAddresses()\n- if err := ReplaceSignalHandler(unix.SIGSEGV, addrOfSignalHandler(), &savedSigSegVHandler); err != nil {\n+ if err := sighandling.ReplaceSignalHandler(unix.SIGSEGV, addrOfSignalHandler(), &savedSigSegVHandler); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for SIGSEGV: %v\", err))\n}\n- if err := ReplaceSignalHandler(unix.SIGBUS, addrOfSignalHandler(), &savedSigBusHandler); err != nil {\n+ if err := sighandling.ReplaceSignalHandler(unix.SIGBUS, addrOfSignalHandler(), &savedSigBusHandler); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for SIGBUS: %v\", err))\n}\nlinuxerr.AddErrorUnwrapper(func(e error) (*errors.Error, bool) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/safecopy/safecopy_unsafe.go",
"new_path": "pkg/safecopy/safecopy_unsafe.go",
"diff": "@@ -20,7 +20,6 @@ import (\n\"unsafe\"\n\"golang.org/x/sys/unix\"\n- \"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n// maxRegisterSize is the maximum register size used in memcpy and memclr. It\n@@ -332,39 +331,3 @@ func errorFromFaultSignal(addr uintptr, sig int32) error {\npanic(fmt.Sprintf(\"safecopy got unexpected signal %d at address %#x\", sig, addr))\n}\n}\n-\n-// ReplaceSignalHandler replaces the existing signal handler for the provided\n-// signal with the one that handles faults in safecopy-protected functions.\n-//\n-// It stores the value of the previously set handler in previous.\n-//\n-// This function will be called on initialization in order to install safecopy\n-// handlers for appropriate signals. These handlers will call the previous\n-// handler however, and if this is function is being used externally then the\n-// same courtesy is expected.\n-func ReplaceSignalHandler(sig unix.Signal, handler uintptr, previous *uintptr) error {\n- var sa linux.SigAction\n- const maskLen = 8\n-\n- // Get the existing signal handler information, and save the current\n- // handler. Once we replace it, we will use this pointer to fall back to\n- // it when we receive other signals.\n- if _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(sig), 0, uintptr(unsafe.Pointer(&sa)), maskLen, 0, 0); e != 0 {\n- return e\n- }\n-\n- // Fail if there isn't a previous handler.\n- if sa.Handler == 0 {\n- return fmt.Errorf(\"previous handler for signal %x isn't set\", sig)\n- }\n-\n- *previous = uintptr(sa.Handler)\n-\n- // Install our own handler.\n- sa.Handler = uint64(handler)\n- if _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(sig), uintptr(unsafe.Pointer(&sa)), 0, maskLen, 0, 0); e != 0 {\n- return e\n- }\n-\n- return nil\n-}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/BUILD",
"new_path": "pkg/sentry/platform/kvm/BUILD",
"diff": "@@ -63,7 +63,6 @@ go_library(\n\"//pkg/procid\",\n\"//pkg/ring0\",\n\"//pkg/ring0/pagetables\",\n- \"//pkg/safecopy\",\n\"//pkg/seccomp\",\n\"//pkg/sentry/arch\",\n\"//pkg/sentry/arch/fpu\",\n@@ -71,6 +70,7 @@ go_library(\n\"//pkg/sentry/platform\",\n\"//pkg/sentry/platform/interrupt\",\n\"//pkg/sentry/time\",\n+ \"//pkg/sighandling\",\n\"//pkg/sync\",\n\"@org_golang_x_sys//unix:go_default_library\",\n],\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/bluepill.go",
"new_path": "pkg/sentry/platform/kvm/bluepill.go",
"diff": "@@ -19,8 +19,8 @@ import (\n\"golang.org/x/sys/unix\"\n\"gvisor.dev/gvisor/pkg/ring0\"\n- \"gvisor.dev/gvisor/pkg/safecopy\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sighandling\"\n)\n// bluepill enters guest mode.\n@@ -97,7 +97,7 @@ func (c *vCPU) die(context *arch.SignalContext64, msg string) {\nfunc init() {\n// Install the handler.\n- if err := safecopy.ReplaceSignalHandler(bluepillSignal, addrOfSighandler(), &savedHandler); err != nil {\n+ if err := sighandling.ReplaceSignalHandler(bluepillSignal, addrOfSighandler(), &savedHandler); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for signal %d: %v\", bluepillSignal, err))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/kvm/machine.go",
"new_path": "pkg/sentry/platform/kvm/machine.go",
"diff": "@@ -28,9 +28,9 @@ import (\n\"gvisor.dev/gvisor/pkg/procid\"\n\"gvisor.dev/gvisor/pkg/ring0\"\n\"gvisor.dev/gvisor/pkg/ring0/pagetables\"\n- \"gvisor.dev/gvisor/pkg/safecopy\"\n\"gvisor.dev/gvisor/pkg/seccomp\"\nktime \"gvisor.dev/gvisor/pkg/sentry/time\"\n+ \"gvisor.dev/gvisor/pkg/sighandling\"\n\"gvisor.dev/gvisor/pkg/sync\"\n)\n@@ -723,7 +723,7 @@ func addrOfSigsysHandler() uintptr\nfunc seccompMmapRules(m *machine) {\nseccompMmapRulesOnce.Do(func() {\n// Install the handler.\n- if err := safecopy.ReplaceSignalHandler(unix.SIGSYS, addrOfSigsysHandler(), &savedSigsysHandler); err != nil {\n+ if err := sighandling.ReplaceSignalHandler(unix.SIGSYS, addrOfSigsysHandler(), &savedSigsysHandler); err != nil {\npanic(fmt.Sprintf(\"Unable to set handler for signal %d: %v\", bluepillSignal, err))\n}\nrules := []seccomp.RuleSet{}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sighandling/sighandling_unsafe.go",
"new_path": "pkg/sighandling/sighandling_unsafe.go",
"diff": "package sighandling\nimport (\n+ \"fmt\"\n\"unsafe\"\n\"golang.org/x/sys/unix\"\n@@ -37,3 +38,36 @@ func IgnoreChildStop() error {\nreturn nil\n}\n+\n+// ReplaceSignalHandler replaces the existing signal handler for the provided\n+// signal with the function pointer at `handler`. This bypasses the Go runtime\n+// signal handlers, and should only be used for low-level signal handlers where\n+// use of signal.Notify is not appropriate.\n+//\n+// It stores the value of the previously set handler in previous.\n+func ReplaceSignalHandler(sig unix.Signal, handler uintptr, previous *uintptr) error {\n+ var sa linux.SigAction\n+ const maskLen = 8\n+\n+ // Get the existing signal handler information, and save the current\n+ // handler. Once we replace it, we will use this pointer to fall back to\n+ // it when we receive other signals.\n+ if _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(sig), 0, uintptr(unsafe.Pointer(&sa)), maskLen, 0, 0); e != 0 {\n+ return e\n+ }\n+\n+ // Fail if there isn't a previous handler.\n+ if sa.Handler == 0 {\n+ return fmt.Errorf(\"previous handler for signal %x isn't set\", sig)\n+ }\n+\n+ *previous = uintptr(sa.Handler)\n+\n+ // Install our own handler.\n+ sa.Handler = uint64(handler)\n+ if _, _, e := unix.RawSyscall6(unix.SYS_RT_SIGACTION, uintptr(sig), uintptr(unsafe.Pointer(&sa)), 0, maskLen, 0, 0); e != 0 {\n+ return e\n+ }\n+\n+ return nil\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move `safecopy.ReplaceSignalHandler` into `sighandling` package.
PiperOrigin-RevId: 399560357 |
259,881 | 30.09.2021 08:43:12 | 25,200 | b4d4f4bd861c98feb0e28d637ef701b9f7f1840e | Add timer_create and timer_settime to filters
Go 1.18 (as of golang.org/cl/324129) uses per-thread timers created and set
with timer_create/timer_settime for more accurate CPU pprof profiling.
Add these syscalls to the allowed syscall filters. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/filter/config.go",
"new_path": "runsc/boot/filter/config.go",
"diff": "@@ -304,6 +304,22 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.EqualTo(unix.SPLICE_F_NONBLOCK), /* flags */\n},\n},\n+ unix.SYS_TIMER_CREATE: []seccomp.Rule{\n+ {\n+ seccomp.EqualTo(unix.CLOCK_THREAD_CPUTIME_ID), /* which */\n+ seccomp.MatchAny{}, /* sevp */\n+ seccomp.MatchAny{}, /* timerid */\n+ },\n+ },\n+ unix.SYS_TIMER_DELETE: []seccomp.Rule{},\n+ unix.SYS_TIMER_SETTIME: []seccomp.Rule{\n+ {\n+ seccomp.MatchAny{}, /* timerid */\n+ seccomp.EqualTo(0), /* flags */\n+ seccomp.MatchAny{}, /* new_value */\n+ seccomp.EqualTo(0), /* old_value */\n+ },\n+ },\nunix.SYS_TGKILL: []seccomp.Rule{\n{\nseccomp.EqualTo(uint64(os.Getpid())),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add timer_create and timer_settime to filters
Go 1.18 (as of golang.org/cl/324129) uses per-thread timers created and set
with timer_create/timer_settime for more accurate CPU pprof profiling.
Add these syscalls to the allowed syscall filters.
PiperOrigin-RevId: 399941561 |
259,881 | 30.09.2021 14:45:28 | 25,200 | c122663548b9bf4bc46843cc662ea8d7e96e7676 | Skip analysis of standard library packages using generics
The upstream analysis packages we depend on do not yet support analysis of code
using Go 1.18 type parameter features, making analysis of the Go tip standard
library choke and crash. Skip these packages for now. | [
{
"change_type": "MODIFY",
"old_path": "tools/nogo/nogo.go",
"new_path": "tools/nogo/nogo.go",
"diff": "@@ -293,6 +293,19 @@ func CheckStdlib(config *StdlibConfig, analyzers []*analysis.Analyzer) (allFindi\nbreak\n}\n+ // Go standard library packages using Go 1.18 type parameter features.\n+ //\n+ // As of writing, analysis tooling is not updated to support type\n+ // parameters and will choke on these packages. We skip these packages\n+ // entirely for now.\n+ //\n+ // TODO(b/201686256): remove once tooling can handle type parameters.\n+ usesTypeParams := map[string]struct{}{\n+ \"constraints\": struct{}{}, // golang.org/issue/45458\n+ \"maps\": struct{}{}, // golang.org/issue/47649\n+ \"slices\": struct{}{}, // golang.org/issue/45955\n+ }\n+\n// Aggregate all files by directory.\npackages := make(map[string]*PackageConfig)\nfor _, file := range config.Srcs {\n@@ -306,10 +319,17 @@ func CheckStdlib(config *StdlibConfig, analyzers []*analysis.Analyzer) (allFindi\ncontinue // Not a file.\n}\npkg := d[len(rootSrcPrefix):]\n+\n// Skip cmd packages and obvious test files: see above.\nif strings.HasPrefix(pkg, \"cmd/\") || strings.HasSuffix(file, \"_test.go\") {\ncontinue\n}\n+\n+ if _, ok := usesTypeParams[pkg]; ok {\n+ log.Printf(\"WARNING: Skipping package %q: type param analysis not yet supported\", pkg)\n+ continue\n+ }\n+\nc, ok := packages[pkg]\nif !ok {\nc = &PackageConfig{\n"
}
] | Go | Apache License 2.0 | google/gvisor | Skip analysis of standard library packages using generics
The upstream analysis packages we depend on do not yet support analysis of code
using Go 1.18 type parameter features, making analysis of the Go tip standard
library choke and crash. Skip these packages for now.
PiperOrigin-RevId: 400030256 |
259,992 | 01.10.2021 09:20:14 | 25,200 | 94623ccf513ed21ec67e1fcb6800ee1250fe27b2 | Use root context to mount volumes
Fixes | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/vfs.go",
"new_path": "runsc/boot/vfs.go",
"diff": "@@ -173,7 +173,7 @@ func (c *containerMounter) mountAll(conf *config.Config, procArgs *kernel.Create\nrootProcArgs.Credentials = rootCreds\nrootProcArgs.Umask = 0022\nrootProcArgs.MaxSymlinkTraversals = linux.MaxSymlinkTraversals\n- rootCtx := procArgs.NewContext(c.k)\n+ rootCtx := rootProcArgs.NewContext(c.k)\nmns, err := c.createMountNamespaceVFS2(rootCtx, conf, rootCreds)\nif err != nil {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Use root context to mount volumes
Fixes #6643
PiperOrigin-RevId: 400218778 |
260,004 | 01.10.2021 11:02:02 | 25,200 | 8073370009aeccaffa7885ab073e630f644fafe6 | Let connection handle tracked packets
...to save a call to `ConnTrack.connFor` when callers already have a
reference to the ConnTrack entry. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -388,30 +388,35 @@ func (ct *ConnTrack) insertConn(conn *conn) {\n// connection exists. Returns whether, after the packet traverses the tables,\n// it should create a new entry in the table.\nfunc (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n- if pkt.NatDone {\n- return false\n- }\n-\nswitch hook {\ncase Prerouting, Input, Output, Postrouting:\ndefault:\nreturn false\n}\n- transportHeader, ok := getTransportHeader(pkt)\n- if !ok {\n+ if conn, dir := ct.connFor(pkt); conn != nil {\n+ conn.handlePacket(pkt, hook, dir, r)\nreturn false\n}\n- conn, dir := ct.connFor(pkt)\n// Connection not found for the packet.\n- if conn == nil {\n+ //\n// If this is the last hook in the data path for this packet (Input if\n// incoming, Postrouting if outgoing), indicate that a connection should be\n// inserted by the end of this hook.\nreturn hook == Input || hook == Postrouting\n}\n+func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, dir direction, r *Route) {\n+ if pkt.NatDone {\n+ return\n+ }\n+\n+ transportHeader, ok := getTransportHeader(pkt)\n+ if !ok {\n+ return\n+ }\n+\nnetHeader := pkt.Network()\n// TODO(gvisor.dev/issue/5748): TCP checksums on inbound packets should be\n@@ -425,24 +430,24 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\nswitch hook {\ncase Prerouting, Output:\n- if conn.manip == manipDestination && dir == dirOriginal {\n- newPort = conn.reply.srcPort\n- newAddr = conn.reply.srcAddr\n+ if cn.manip == manipDestination && dir == dirOriginal {\n+ newPort = cn.reply.srcPort\n+ newAddr = cn.reply.srcAddr\npkt.NatDone = true\n- } else if conn.manip == manipSource && dir == dirReply {\n- newPort = conn.original.srcPort\n- newAddr = conn.original.srcAddr\n+ } else if cn.manip == manipSource && dir == dirReply {\n+ newPort = cn.original.srcPort\n+ newAddr = cn.original.srcAddr\npkt.NatDone = true\n}\ncase Input, Postrouting:\n- if conn.manip == manipSource && dir == dirOriginal {\n- newPort = conn.reply.dstPort\n- newAddr = conn.reply.dstAddr\n+ if cn.manip == manipSource && dir == dirOriginal {\n+ newPort = cn.reply.dstPort\n+ newAddr = cn.reply.dstAddr\nupdateSRCFields = true\npkt.NatDone = true\n- } else if conn.manip == manipDestination && dir == dirReply {\n- newPort = conn.original.dstPort\n- newAddr = conn.original.dstAddr\n+ } else if cn.manip == manipDestination && dir == dirReply {\n+ newPort = cn.original.dstPort\n+ newAddr = cn.original.dstAddr\nupdateSRCFields = true\npkt.NatDone = true\n}\n@@ -451,7 +456,7 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n}\nif !pkt.NatDone {\n- return false\n+ return\n}\nfullChecksum := false\n@@ -486,15 +491,13 @@ func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n)\n// Update the state of tcb.\n- conn.mu.Lock()\n- defer conn.mu.Unlock()\n+ cn.mu.Lock()\n+ defer cn.mu.Unlock()\n// Mark the connection as having been used recently so it isn't reaped.\n- conn.lastUsed = time.Now()\n+ cn.lastUsed = time.Now()\n// Update connection state.\n- conn.updateLocked(pkt, hook)\n-\n- return false\n+ cn.updateLocked(pkt, hook)\n}\n// maybeInsertNoop tries to insert a no-op connection entry to keep connections\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_targets.go",
"new_path": "pkg/tcpip/stack/iptables_targets.go",
"diff": "@@ -162,7 +162,7 @@ func (rt *RedirectTarget) Action(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r\n// packet of the connection comes here. Other packets will be\n// manipulated in connection tracking.\nif conn := ct.insertRedirectConn(pkt, hook, rt.Port, address); conn != nil {\n- ct.handlePacket(pkt, hook, r)\n+ conn.handlePacket(pkt, hook, dirOriginal, r)\n}\ndefault:\nreturn RuleDrop, 0\n@@ -213,7 +213,7 @@ func snatAction(pkt *PacketBuffer, ct *ConnTrack, hook Hook, r *Route, port uint\n//\n// Does nothing if the protocol does not support connection tracking.\nif conn := ct.insertSNATConn(pkt, hook, port, address); conn != nil {\n- ct.handlePacket(pkt, hook, r)\n+ conn.handlePacket(pkt, hook, dirOriginal, r)\n}\nreturn RuleAccept, 0\n"
}
] | Go | Apache License 2.0 | google/gvisor | Let connection handle tracked packets
...to save a call to `ConnTrack.connFor` when callers already have a
reference to the ConnTrack entry.
PiperOrigin-RevId: 400244955 |
260,004 | 01.10.2021 11:47:11 | 25,200 | 788bbc2904983417efe430cc5c66b3af990d3bfe | Drop IPTables.checkPackets
...and have `CheckOutputPackets`, `CheckPostroutingPackets` call their
equivalent methods that operate on a single packet buffer directly.
This is so that the `Check{Output, Postrouting}Packets` methods may
leverage any hook-specific work that `Check{Output, Postrouting}`
may perform.
Note: Later changes will add hook-specific logic to the
`Check{Output, Postrouting}` methods. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -431,7 +431,9 @@ func (it *IPTables) startReaper(interval time.Duration) {\n//\n// Precondition: The packets' network and transport header must be set.\nfunc (it *IPTables) CheckOutputPackets(pkts PacketBufferList, r *Route, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n- return it.checkPackets(Output, pkts, r, nil /* addressEP */, outNicName)\n+ return checkPackets(pkts, func(pkt *PacketBuffer) bool {\n+ return it.CheckOutput(pkt, r, outNicName)\n+ })\n}\n// CheckPostroutingPackets performs the postrouting hook on the packets.\n@@ -440,20 +442,15 @@ func (it *IPTables) CheckOutputPackets(pkts PacketBufferList, r *Route, outNicNa\n//\n// Precondition: The packets' network and transport header must be set.\nfunc (it *IPTables) CheckPostroutingPackets(pkts PacketBufferList, r *Route, addressEP AddressableEndpoint, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n- return it.checkPackets(Postrouting, pkts, r, addressEP, outNicName)\n+ return checkPackets(pkts, func(pkt *PacketBuffer) bool {\n+ return it.CheckPostrouting(pkt, r, addressEP, outNicName)\n+ })\n}\n-// checkPackets runs pkts through the rules for hook and returns a map of\n-// packets that should not go forward.\n-//\n-// NOTE: unlike the Check API the returned map contains packets that should be\n-// dropped.\n-//\n-// Precondition: The packets' network and transport header must be set.\n-func (it *IPTables) checkPackets(hook Hook, pkts PacketBufferList, r *Route, addressEP AddressableEndpoint, outNicName string) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\n+func checkPackets(pkts PacketBufferList, f func(*PacketBuffer) bool) (drop map[*PacketBuffer]struct{}, natPkts map[*PacketBuffer]struct{}) {\nfor pkt := pkts.Front(); pkt != nil; pkt = pkt.Next() {\nif !pkt.NatDone {\n- if ok := it.check(hook, pkt, r, addressEP, \"\" /* inNicName */, outNicName); !ok {\n+ if ok := f(pkt); !ok {\nif drop == nil {\ndrop = make(map[*PacketBuffer]struct{})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop IPTables.checkPackets
...and have `CheckOutputPackets`, `CheckPostroutingPackets` call their
equivalent methods that operate on a single packet buffer directly.
This is so that the `Check{Output, Postrouting}Packets` methods may
leverage any hook-specific work that `Check{Output, Postrouting}`
may perform.
Note: Later changes will add hook-specific logic to the
`Check{Output, Postrouting}` methods.
PiperOrigin-RevId: 400255651 |
260,004 | 01.10.2021 12:33:13 | 25,200 | 8603cce51d6d930aed128fff873591520dcb0853 | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -117,15 +117,18 @@ type conn struct {\n// update the state of tcb. It is immutable.\ntcbHook Hook\n- // mu protects all mutable state.\nmu sync.Mutex `state:\"nosave\"`\n// tcb is TCB control block. It is used to keep track of states\n- // of tcp connection and is protected by mu.\n+ // of tcp connection.\n+ //\n+ // +checklocks:mu\ntcb tcpconntrack.TCB\n// lastUsed is the last time the connection saw a relevant packet, and\n- // is updated by each packet on the connection. It is protected by mu.\n+ // is updated by each packet on the connection.\n//\n// TODO(gvisor.dev/issue/5939): do not use the ambient clock.\n+ //\n+ // +checklocks:mu\nlastUsed time.Time `state:\".(unixTime)\"`\n}\n@@ -159,7 +162,8 @@ func (cn *conn) timedOut(now time.Time) bool {\n// update the connection tracking state.\n//\n-// Precondition: cn.mu must be held.\n+// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n+// +checklocks:cn.mu\nfunc (cn *conn) updateLocked(pkt *PacketBuffer, hook Hook) {\nif pkt.TransportProtocolNumber != header.TCPProtocolNumber {\nreturn\n@@ -200,18 +204,18 @@ type ConnTrack struct {\n// It is immutable.\nseed uint32\n+ mu sync.RWMutex `state:\"nosave\"`\n// mu protects the buckets slice, but not buckets' contents. Only take\n// the write lock if you are modifying the slice or saving for S/R.\n- mu sync.RWMutex `state:\"nosave\"`\n-\n- // buckets is protected by mu.\n+ //\n+ // +checklocks:mu\nbuckets []bucket\n}\n// +stateify savable\ntype bucket struct {\n- // mu protects tuples.\nmu sync.Mutex `state:\"nosave\"`\n+ // +checklocks:mu\ntuples tupleList\n}\n@@ -270,19 +274,20 @@ func (ct *ConnTrack) connFor(pkt *PacketBuffer) (*conn, direction) {\n}\nfunc (ct *ConnTrack) connForTID(tid tupleID) (*conn, direction) {\n- bucket := ct.bucket(tid)\n+ bktID := ct.bucket(tid)\nnow := time.Now()\nct.mu.RLock()\ndefer ct.mu.RUnlock()\n- ct.buckets[bucket].mu.Lock()\n- defer ct.buckets[bucket].mu.Unlock()\n+ bkt := &ct.buckets[bktID]\n+ bkt.mu.Lock()\n+ defer bkt.mu.Unlock()\n// Iterate over the tuples in a bucket, cleaning up any unused\n// connections we find.\n- for other := ct.buckets[bucket].tuples.Front(); other != nil; other = other.Next() {\n+ for other := bkt.tuples.Front(); other != nil; other = other.Next() {\n// Clean up any timed-out connections we happen to find.\n- if ct.reapTupleLocked(other, bucket, now) {\n+ if ct.reapTupleLocked(other, bktID, bkt, now) {\n// The tuple expired.\ncontinue\n}\n@@ -344,27 +349,46 @@ func (ct *ConnTrack) insertSNATConn(pkt *PacketBuffer, hook Hook, port uint16, a\n// insertConn inserts conn into the appropriate table bucket.\nfunc (ct *ConnTrack) insertConn(conn *conn) {\n- // Lock the buckets in the correct order.\n- tupleBucket := ct.bucket(conn.original.tupleID)\n- replyBucket := ct.bucket(conn.reply.tupleID)\n+ tupleBktID := ct.bucket(conn.original.tupleID)\n+ replyBktID := ct.bucket(conn.reply.tupleID)\n+\nct.mu.RLock()\ndefer ct.mu.RUnlock()\n- if tupleBucket < replyBucket {\n- ct.buckets[tupleBucket].mu.Lock()\n- ct.buckets[replyBucket].mu.Lock()\n- } else if tupleBucket > replyBucket {\n- ct.buckets[replyBucket].mu.Lock()\n- ct.buckets[tupleBucket].mu.Lock()\n- } else {\n+\n+ tupleBkt := &ct.buckets[tupleBktID]\n+ if tupleBktID == replyBktID {\n// Both tuples are in the same bucket.\n- ct.buckets[tupleBucket].mu.Lock()\n+ tupleBkt.mu.Lock()\n+ defer tupleBkt.mu.Unlock()\n+ insertConn(tupleBkt, tupleBkt, conn)\n+ return\n+ }\n+\n+ // Lock the buckets in the correct order.\n+ replyBkt := &ct.buckets[replyBktID]\n+ if tupleBktID < replyBktID {\n+ tupleBkt.mu.Lock()\n+ defer tupleBkt.mu.Unlock()\n+ replyBkt.mu.Lock()\n+ defer replyBkt.mu.Unlock()\n+ } else {\n+ replyBkt.mu.Lock()\n+ defer replyBkt.mu.Unlock()\n+ tupleBkt.mu.Lock()\n+ defer tupleBkt.mu.Unlock()\n+ }\n+ insertConn(tupleBkt, replyBkt, conn)\n}\n+// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n+// +checklocks:tupleBkt.mu\n+// +checklocks:replyBkt.mu\n+func insertConn(tupleBkt *bucket, replyBkt *bucket, conn *conn) {\n// Now that we hold the locks, ensure the tuple hasn't been inserted by\n// another thread.\n// TODO(gvisor.dev/issue/5773): Should check conn.reply.tupleID, too?\nalreadyInserted := false\n- for other := ct.buckets[tupleBucket].tuples.Front(); other != nil; other = other.Next() {\n+ for other := tupleBkt.tuples.Front(); other != nil; other = other.Next() {\nif other.tupleID == conn.original.tupleID {\nalreadyInserted = true\nbreak\n@@ -373,14 +397,8 @@ func (ct *ConnTrack) insertConn(conn *conn) {\nif !alreadyInserted {\n// Add the tuple to the map.\n- ct.buckets[tupleBucket].tuples.PushFront(&conn.original)\n- ct.buckets[replyBucket].tuples.PushFront(&conn.reply)\n- }\n-\n- // Unlocking can happen in any order.\n- ct.buckets[tupleBucket].mu.Unlock()\n- if tupleBucket != replyBucket {\n- ct.buckets[replyBucket].mu.Unlock() // +checklocksforce\n+ tupleBkt.tuples.PushFront(&conn.original)\n+ replyBkt.tuples.PushFront(&conn.reply)\n}\n}\n@@ -529,8 +547,10 @@ func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer, hook Hook) {\nreturn\n}\nconn := newConn(tid, tid.reply(), manipNone, hook)\n- conn.updateLocked(pkt, hook)\nct.insertConn(conn)\n+ conn.mu.Lock()\n+ defer conn.mu.Unlock()\n+ conn.updateLocked(pkt, hook)\n}\n// bucket gets the conntrack bucket for a tupleID.\n@@ -582,14 +602,15 @@ func (ct *ConnTrack) reapUnused(start int, prevInterval time.Duration) (int, tim\ndefer ct.mu.RUnlock()\nfor i := 0; i < len(ct.buckets)/fractionPerReaping; i++ {\nidx = (i + start) % len(ct.buckets)\n- ct.buckets[idx].mu.Lock()\n- for tuple := ct.buckets[idx].tuples.Front(); tuple != nil; tuple = tuple.Next() {\n+ bkt := &ct.buckets[idx]\n+ bkt.mu.Lock()\n+ for tuple := bkt.tuples.Front(); tuple != nil; tuple = tuple.Next() {\nchecked++\n- if ct.reapTupleLocked(tuple, idx, now) {\n+ if ct.reapTupleLocked(tuple, idx, bkt, now) {\nexpired++\n}\n}\n- ct.buckets[idx].mu.Unlock()\n+ bkt.mu.Unlock()\n}\n// We already checked buckets[idx].\nidx++\n@@ -614,41 +635,45 @@ func (ct *ConnTrack) reapUnused(start int, prevInterval time.Duration) (int, tim\n// reapTupleLocked tries to remove tuple and its reply from the table. It\n// returns whether the tuple's connection has timed out.\n//\n-// Preconditions:\n-// * ct.mu is locked for reading.\n-// * bucket is locked.\n-func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bucket int, now time.Time) bool {\n+// Precondition: ct.mu is read locked and bkt.mu is write locked.\n+// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n+// +checklocks:ct.mu\n+// +checklocks:bkt.mu\n+func (ct *ConnTrack) reapTupleLocked(tuple *tuple, bktID int, bkt *bucket, now time.Time) bool {\nif !tuple.conn.timedOut(now) {\nreturn false\n}\n// To maintain lock order, we can only reap these tuples if the reply\n// appears later in the table.\n- replyBucket := ct.bucket(tuple.reply())\n- if bucket > replyBucket {\n+ replyBktID := ct.bucket(tuple.reply())\n+ if bktID > replyBktID {\nreturn true\n}\n// Don't re-lock if both tuples are in the same bucket.\n- differentBuckets := bucket != replyBucket\n- if differentBuckets {\n- ct.buckets[replyBucket].mu.Lock()\n+ if bktID != replyBktID {\n+ replyBkt := &ct.buckets[replyBktID]\n+ replyBkt.mu.Lock()\n+ removeConnFromBucket(replyBkt, tuple)\n+ replyBkt.mu.Unlock()\n+ } else {\n+ removeConnFromBucket(bkt, tuple)\n}\n// We have the buckets locked and can remove both tuples.\n- if tuple.direction == dirOriginal {\n- ct.buckets[replyBucket].tuples.Remove(&tuple.conn.reply)\n- } else {\n- ct.buckets[replyBucket].tuples.Remove(&tuple.conn.original)\n+ bkt.tuples.Remove(tuple)\n+ return true\n}\n- ct.buckets[bucket].tuples.Remove(tuple)\n- // Don't re-unlock if both tuples are in the same bucket.\n- if differentBuckets {\n- ct.buckets[replyBucket].mu.Unlock() // +checklocksforce\n+// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n+// +checklocks:b.mu\n+func removeConnFromBucket(b *bucket, tuple *tuple) {\n+ if tuple.direction == dirOriginal {\n+ b.tuples.Remove(&tuple.conn.reply)\n+ } else {\n+ b.tuples.Remove(&tuple.conn.original)\n}\n-\n- return true\n}\nfunc (ct *ConnTrack) originalDst(epID TransportEndpointID, netProto tcpip.NetworkProtocolNumber, transProto tcpip.TransportProtocolNumber) (tcpip.Address, uint16, tcpip.Error) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_state.go",
"new_path": "pkg/tcpip/stack/iptables_state.go",
"diff": "@@ -26,11 +26,15 @@ type unixTime struct {\n// saveLastUsed is invoked by stateify.\nfunc (cn *conn) saveLastUsed() unixTime {\n+ cn.mu.Lock()\n+ defer cn.mu.Unlock()\nreturn unixTime{cn.lastUsed.Unix(), cn.lastUsed.UnixNano()}\n}\n// loadLastUsed is invoked by stateify.\nfunc (cn *conn) loadLastUsed(unix unixTime) {\n+ cn.mu.Lock()\n+ defer cn.mu.Unlock()\ncn.lastUsed = time.Unix(unix.second, unix.nano)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables_types.go",
"new_path": "pkg/tcpip/stack/iptables_types.go",
"diff": "@@ -81,17 +81,6 @@ const (\n//\n// +stateify savable\ntype IPTables struct {\n- // mu protects v4Tables, v6Tables, and modified.\n- mu sync.RWMutex\n- // v4Tables and v6tables map tableIDs to tables. They hold builtin\n- // tables only, not user tables. mu must be locked for accessing.\n- v4Tables [NumTables]Table\n- v6Tables [NumTables]Table\n- // modified is whether tables have been modified at least once. It is\n- // used to elide the iptables performance overhead for workloads that\n- // don't utilize iptables.\n- modified bool\n-\n// priorities maps each hook to a list of table names. The order of the\n// list is the order in which each table should be visited for that\n// hook. It is immutable.\n@@ -101,6 +90,21 @@ type IPTables struct {\n// reaperDone can be signaled to stop the reaper goroutine.\nreaperDone chan struct{}\n+\n+ mu sync.RWMutex\n+ // v4Tables and v6tables map tableIDs to tables. They hold builtin\n+ // tables only, not user tables.\n+ //\n+ // +checklocks:mu\n+ v4Tables [NumTables]Table\n+ // +checklocks:mu\n+ v6Tables [NumTables]Table\n+ // modified is whether tables have been modified at least once. It is\n+ // used to elide the iptables performance overhead for workloads that\n+ // don't utilize iptables.\n+ //\n+ // +checklocks:mu\n+ modified bool\n}\n// VisitTargets traverses all the targets of all tables and replaces each with\n"
}
] | Go | Apache License 2.0 | google/gvisor | Annotate checklocks on mutex protected fields
...to catch lock-related bugs in nogo tests.
Updates #6566.
PiperOrigin-RevId: 400265818 |
260,004 | 01.10.2021 13:35:04 | 25,200 | 6e83c4b751c60652247d0ebbe559261352b2131f | Drop conn.tcbHook
...as the packet's direction gives us the information that tcbHook is
used to derive. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -113,10 +113,6 @@ type conn struct {\n// TODO(gvisor.dev/issue/5696): Support updating manipulation type.\nmanip manipType\n- // tcbHook indicates if the packet is inbound or outbound to\n- // update the state of tcb. It is immutable.\n- tcbHook Hook\n-\nmu sync.Mutex `state:\"nosave\"`\n// tcb is TCB control block. It is used to keep track of states\n// of tcp connection.\n@@ -133,10 +129,9 @@ type conn struct {\n}\n// newConn creates new connection.\n-func newConn(orig, reply tupleID, manip manipType, hook Hook) *conn {\n+func newConn(orig, reply tupleID, manip manipType) *conn {\nconn := conn{\nmanip: manip,\n- tcbHook: hook,\nlastUsed: time.Now(),\n}\nconn.original = tuple{conn: &conn, tupleID: orig}\n@@ -164,7 +159,7 @@ func (cn *conn) timedOut(now time.Time) bool {\n//\n// TODO(https://gvisor.dev/issue/6590): annotate r/w locking requirements.\n// +checklocks:cn.mu\n-func (cn *conn) updateLocked(pkt *PacketBuffer, hook Hook) {\n+func (cn *conn) updateLocked(pkt *PacketBuffer, dir direction) {\nif pkt.TransportProtocolNumber != header.TCPProtocolNumber {\nreturn\n}\n@@ -176,10 +171,16 @@ func (cn *conn) updateLocked(pkt *PacketBuffer, hook Hook) {\n// established or not, so the client/server distinction isn't important.\nif cn.tcb.IsEmpty() {\ncn.tcb.Init(tcpHeader)\n- } else if hook == cn.tcbHook {\n+ return\n+ }\n+\n+ switch dir {\n+ case dirOriginal:\ncn.tcb.UpdateStateOutbound(tcpHeader)\n- } else {\n+ case dirReply:\ncn.tcb.UpdateStateInbound(tcpHeader)\n+ default:\n+ panic(fmt.Sprintf(\"unhandled dir = %d\", dir))\n}\n}\n@@ -318,7 +319,7 @@ func (ct *ConnTrack) insertRedirectConn(pkt *PacketBuffer, hook Hook, port uint1\n// TODO(gvisor.dev/issue/5696): Support updating an existing connection.\nreturn nil\n}\n- conn = newConn(tid, replyTID, manipDestination, hook)\n+ conn = newConn(tid, replyTID, manipDestination)\nct.insertConn(conn)\nreturn conn\n}\n@@ -342,7 +343,7 @@ func (ct *ConnTrack) insertSNATConn(pkt *PacketBuffer, hook Hook, port uint16, a\n// TODO(gvisor.dev/issue/5696): Support updating an existing connection.\nreturn nil\n}\n- conn = newConn(tid, replyTID, manipSource, hook)\n+ conn = newConn(tid, replyTID, manipSource)\nct.insertConn(conn)\nreturn conn\n}\n@@ -515,7 +516,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, dir direction, r *Rou\n// Mark the connection as having been used recently so it isn't reaped.\ncn.lastUsed = time.Now()\n// Update connection state.\n- cn.updateLocked(pkt, hook)\n+ cn.updateLocked(pkt, dir)\n}\n// maybeInsertNoop tries to insert a no-op connection entry to keep connections\n@@ -524,7 +525,7 @@ func (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, dir direction, r *Rou\n//\n// This should be called after traversing iptables rules only, to ensure that\n// pkt.NatDone is set correctly.\n-func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer, hook Hook) {\n+func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer) {\n// If there were a rule applying to this packet, it would be marked\n// with NatDone.\nif pkt.NatDone {\n@@ -546,11 +547,11 @@ func (ct *ConnTrack) maybeInsertNoop(pkt *PacketBuffer, hook Hook) {\nif err != nil {\nreturn\n}\n- conn := newConn(tid, tid.reply(), manipNone, hook)\n+ conn := newConn(tid, tid.reply(), manipNone)\nct.insertConn(conn)\nconn.mu.Lock()\ndefer conn.mu.Unlock()\n- conn.updateLocked(pkt, hook)\n+ conn.updateLocked(pkt, dirOriginal)\n}\n// bucket gets the conntrack bucket for a tupleID.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -388,7 +388,7 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP Addr\n// binding is created: this usually does not map the packet, but exists\n// to ensure we don't map another stream over an existing one.\"\nif shouldTrack {\n- it.connections.maybeInsertNoop(pkt, hook)\n+ it.connections.maybeInsertNoop(pkt)\n}\n// Every table returned Accept.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop conn.tcbHook
...as the packet's direction gives us the information that tcbHook is
used to derive.
PiperOrigin-RevId: 400280102 |
260,004 | 01.10.2021 14:56:29 | 25,200 | 51c4fbb840b98380b4016bac030f0adbd5725d70 | Drop ConnTrack.handlePacket
Move the hook specific logic to the IPTables hook functions.
This lets us avoid having to perform checks on the hook to determine
what action to take.
Later changes will drop the need for handlePacket's return value,
reducing the value of this function that all hooks call into. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -403,29 +403,6 @@ func insertConn(tupleBkt *bucket, replyBkt *bucket, conn *conn) {\n}\n}\n-// handlePacket will manipulate the port and address of the packet if the\n-// connection exists. Returns whether, after the packet traverses the tables,\n-// it should create a new entry in the table.\n-func (ct *ConnTrack) handlePacket(pkt *PacketBuffer, hook Hook, r *Route) bool {\n- switch hook {\n- case Prerouting, Input, Output, Postrouting:\n- default:\n- return false\n- }\n-\n- if conn, dir := ct.connFor(pkt); conn != nil {\n- conn.handlePacket(pkt, hook, dir, r)\n- return false\n- }\n-\n- // Connection not found for the packet.\n- //\n- // If this is the last hook in the data path for this packet (Input if\n- // incoming, Postrouting if outgoing), indicate that a connection should be\n- // inserted by the end of this hook.\n- return hook == Input || hook == Postrouting\n-}\n-\nfunc (cn *conn) handlePacket(pkt *PacketBuffer, hook Hook, dir direction, r *Route) {\nif pkt.NatDone {\nreturn\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/iptables.go",
"new_path": "pkg/tcpip/stack/iptables.go",
"diff": "@@ -271,7 +271,17 @@ const (\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndpoint, inNicName string) bool {\n- return it.check(Prerouting, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */)\n+ const hook = Prerouting\n+\n+ if it.shouldSkip(pkt.NetworkProtocolNumber) {\n+ return true\n+ }\n+\n+ if conn, dir := it.connections.connFor(pkt); conn != nil {\n+ conn.handlePacket(pkt, hook, dir, nil /* route */)\n+ }\n+\n+ return it.check(hook, pkt, nil /* route */, addressEP, inNicName, \"\" /* outNicName */)\n}\n// CheckInput performs the input hook on the packet.\n@@ -281,7 +291,26 @@ func (it *IPTables) CheckPrerouting(pkt *PacketBuffer, addressEP AddressableEndp\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n- return it.check(Input, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */)\n+ const hook = Input\n+\n+ if it.shouldSkip(pkt.NetworkProtocolNumber) {\n+ return true\n+ }\n+\n+ shouldTrack := true\n+ if conn, dir := it.connections.connFor(pkt); conn != nil {\n+ conn.handlePacket(pkt, hook, dir, nil /* route */)\n+ shouldTrack = false\n+ }\n+\n+ if !it.check(hook, pkt, nil /* route */, nil /* addressEP */, inNicName, \"\" /* outNicName */) {\n+ return false\n+ }\n+\n+ // This is the last hook a packet will perform so if the packet's\n+ // connection is not tracked, we may need to add a no-op entry.\n+ it.maybeinsertNoopConn(pkt, hook, shouldTrack)\n+ return true\n}\n// CheckForward performs the forward hook on the packet.\n@@ -291,6 +320,10 @@ func (it *IPTables) CheckInput(pkt *PacketBuffer, inNicName string) bool {\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string) bool {\n+ if it.shouldSkip(pkt.NetworkProtocolNumber) {\n+ return true\n+ }\n+\nreturn it.check(Forward, pkt, nil /* route */, nil /* addressEP */, inNicName, outNicName)\n}\n@@ -301,7 +334,17 @@ func (it *IPTables) CheckForward(pkt *PacketBuffer, inNicName, outNicName string\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string) bool {\n- return it.check(Output, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName)\n+ const hook = Output\n+\n+ if it.shouldSkip(pkt.NetworkProtocolNumber) {\n+ return true\n+ }\n+\n+ if conn, dir := it.connections.connFor(pkt); conn != nil {\n+ conn.handlePacket(pkt, hook, dir, r)\n+ }\n+\n+ return it.check(hook, pkt, r, nil /* addressEP */, \"\" /* inNicName */, outNicName)\n}\n// CheckPostrouting performs the postrouting hook on the packet.\n@@ -311,7 +354,41 @@ func (it *IPTables) CheckOutput(pkt *PacketBuffer, r *Route, outNicName string)\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, outNicName string) bool {\n- return it.check(Postrouting, pkt, r, addressEP, \"\" /* inNicName */, outNicName)\n+ const hook = Postrouting\n+\n+ if it.shouldSkip(pkt.NetworkProtocolNumber) {\n+ return true\n+ }\n+\n+ shouldTrack := true\n+ if conn, dir := it.connections.connFor(pkt); conn != nil {\n+ conn.handlePacket(pkt, hook, dir, r)\n+ shouldTrack = false\n+ }\n+\n+ if !it.check(hook, pkt, r, addressEP, \"\" /* inNicName */, outNicName) {\n+ return false\n+ }\n+\n+ // This is the last hook a packet will perform so if the packet's\n+ // connection is not tracked, we may need to add a no-op entry.\n+ it.maybeinsertNoopConn(pkt, hook, shouldTrack)\n+ return true\n+}\n+\n+func (it *IPTables) shouldSkip(netProto tcpip.NetworkProtocolNumber) bool {\n+ switch netProto {\n+ case header.IPv4ProtocolNumber, header.IPv6ProtocolNumber:\n+ default:\n+ // IPTables only supports IPv4/IPv6.\n+ return true\n+ }\n+\n+ it.mu.RLock()\n+ defer it.mu.RUnlock()\n+ // Many users never configure iptables. Spare them the cost of rule\n+ // traversal if rules have never been set.\n+ return !it.modified\n}\n// check runs pkt through the rules for hook. It returns true when the packet\n@@ -320,20 +397,8 @@ func (it *IPTables) CheckPostrouting(pkt *PacketBuffer, r *Route, addressEP Addr\n//\n// Precondition: The packet's network and transport header must be set.\nfunc (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP AddressableEndpoint, inNicName, outNicName string) bool {\n- if pkt.NetworkProtocolNumber != header.IPv4ProtocolNumber && pkt.NetworkProtocolNumber != header.IPv6ProtocolNumber {\n- return true\n- }\n- // Many users never configure iptables. Spare them the cost of rule\n- // traversal if rules have never been set.\nit.mu.RLock()\ndefer it.mu.RUnlock()\n- if !it.modified {\n- return true\n- }\n-\n- // Packets are manipulated only if connection and matching\n- // NAT rule exists.\n- shouldTrack := it.connections.handlePacket(pkt, hook, r)\n// Go through each table containing the hook.\npriorities := it.priorities[hook]\n@@ -377,6 +442,10 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP Addr\n}\n}\n+ return true\n+}\n+\n+func (it *IPTables) maybeinsertNoopConn(pkt *PacketBuffer, hook Hook, shouldTrack bool) {\n// If this connection should be tracked, try to add an entry for it. If\n// traversing the nat table didn't end in adding an entry,\n// maybeInsertNoop will add a no-op entry for the connection. This is\n@@ -390,9 +459,6 @@ func (it *IPTables) check(hook Hook, pkt *PacketBuffer, r *Route, addressEP Addr\nif shouldTrack {\nit.connections.maybeInsertNoop(pkt)\n}\n-\n- // Every table returned Accept.\n- return true\n}\n// beforeSave is invoked by stateify.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop ConnTrack.handlePacket
Move the hook specific logic to the IPTables hook functions.
This lets us avoid having to perform checks on the hook to determine
what action to take.
Later changes will drop the need for handlePacket's return value,
reducing the value of this function that all hooks call into.
PiperOrigin-RevId: 400298023 |
260,004 | 01.10.2021 17:00:24 | 25,200 | 3bab5e56677942c19d0777a1d6aee38a25a05bbb | Read lock when getting connections
We should avoid taking the write lock to avoid contention when looking
for a packet's tracked connection.
No need to reap timed out connections when looking for connections
as the reaper (which runs periodically) will handle that. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/conntrack.go",
"new_path": "pkg/tcpip/stack/conntrack.go",
"diff": "@@ -113,7 +113,7 @@ type conn struct {\n// TODO(gvisor.dev/issue/5696): Support updating manipulation type.\nmanip manipType\n- mu sync.Mutex `state:\"nosave\"`\n+ mu sync.RWMutex `state:\"nosave\"`\n// tcb is TCB control block. It is used to keep track of states\n// of tcp connection.\n//\n@@ -143,8 +143,8 @@ func newConn(orig, reply tupleID, manip manipType) *conn {\nfunc (cn *conn) timedOut(now time.Time) bool {\nconst establishedTimeout = 5 * 24 * time.Hour\nconst defaultTimeout = 120 * time.Second\n- cn.mu.Lock()\n- defer cn.mu.Unlock()\n+ cn.mu.RLock()\n+ defer cn.mu.RUnlock()\nif cn.tcb.State() == tcpconntrack.ResultAlive {\n// Use the same default as Linux, which doesn't delete\n// established connections for 5(!) days.\n@@ -215,7 +215,7 @@ type ConnTrack struct {\n// +stateify savable\ntype bucket struct {\n- mu sync.Mutex `state:\"nosave\"`\n+ mu sync.RWMutex `state:\"nosave\"`\n// +checklocks:mu\ntuples tupleList\n}\n@@ -279,20 +279,13 @@ func (ct *ConnTrack) connForTID(tid tupleID) (*conn, direction) {\nnow := time.Now()\nct.mu.RLock()\n- defer ct.mu.RUnlock()\nbkt := &ct.buckets[bktID]\n- bkt.mu.Lock()\n- defer bkt.mu.Unlock()\n+ ct.mu.RUnlock()\n- // Iterate over the tuples in a bucket, cleaning up any unused\n- // connections we find.\n+ bkt.mu.RLock()\n+ defer bkt.mu.RUnlock()\nfor other := bkt.tuples.Front(); other != nil; other = other.Next() {\n- // Clean up any timed-out connections we happen to find.\n- if ct.reapTupleLocked(other, bktID, bkt, now) {\n- // The tuple expired.\n- continue\n- }\n- if tid == other.tupleID {\n+ if tid == other.tupleID && !other.conn.timedOut(now) {\nreturn other.conn, other.direction\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Read lock when getting connections
We should avoid taking the write lock to avoid contention when looking
for a packet's tracked connection.
No need to reap timed out connections when looking for connections
as the reaper (which runs periodically) will handle that.
PiperOrigin-RevId: 400322514 |
259,951 | 04.10.2021 09:50:18 | 25,200 | 429821b0a91091db71509276855e5919d4d90a49 | Test listener receiving an invalid ACK while the accept queue is full
Updates | [
{
"change_type": "MODIFY",
"old_path": "test/packetimpact/tests/tcp_listen_backlog_test.go",
"new_path": "test/packetimpact/tests/tcp_listen_backlog_test.go",
"diff": "@@ -144,13 +144,33 @@ func TestTCPListenBacklog(t *testing.T) {\n}\n}\n+ // While the accept queue is still full, send an unexpected ACK from a new\n+ // socket. The listener should reply with an RST.\n+ func() {\n+ conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{})\n+ defer conn.Close(t)\n+ conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagAck)})\n+ if !dut.Uname.IsLinux() {\n+ // TODO(https://gvisor.dev/issues/6683): Expect a RST.\n+ if got, err := conn.Expect(t, testbench.TCP{}, time.Second); err == nil {\n+ t.Errorf(\"expected no TCP frame, got %s\", got)\n+ }\n+ } else {\n+ if got, err := conn.Expect(t, testbench.TCP{}, time.Second); err != nil {\n+ t.Errorf(\"expected TCP frame: %s\", err)\n+ } else if got, want := *got.Flags, header.TCPFlagRst; got != want {\n+ t.Errorf(\"got %s, want %s\", got, want)\n+ }\n+ }\n+ }()\n+\nfunc() {\n// Now initiate a new connection when the accept queue is full.\n- connectingConn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{})\n- defer connectingConn.Close(t)\n+ conn := dut.Net.NewTCPIPv4(t, testbench.TCP{DstPort: &remotePort}, testbench.TCP{})\n+ defer conn.Close(t)\n// Expect dut connection to drop the SYN.\n- connectingConn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})\n- if got, err := connectingConn.Expect(t, testbench.TCP{}, time.Second); err == nil {\n+ conn.Send(t, testbench.TCP{Flags: testbench.TCPFlags(header.TCPFlagSyn)})\n+ if got, err := conn.Expect(t, testbench.TCP{}, time.Second); err == nil {\nt.Fatalf(\"expected no TCP frame, got %s\", got)\n}\n}()\n"
}
] | Go | Apache License 2.0 | google/gvisor | Test listener receiving an invalid ACK while the accept queue is full
Updates #6683
PiperOrigin-RevId: 400745768 |
Subsets and Splits