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,853 | 16.08.2019 19:30:59 | 25,200 | 3e4102b2ead18aa768e1b8082d9865a9c567ce4e | netstack: disconnect an unix socket only if the address family is AF_UNSPEC
Linux allows to call connect for ANY and the zero port. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -291,18 +291,22 @@ func bytesToIPAddress(addr []byte) tcpip.Address {\nreturn tcpip.Address(addr)\n}\n-// GetAddress reads an sockaddr struct from the given address and converts it\n-// to the FullAddress format. It supports AF_UNIX, AF_INET and AF_INET6\n-// addresses.\n-func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syserr.Error) {\n+// AddressAndFamily reads an sockaddr struct from the given address and\n+// converts it to the FullAddress format. It supports AF_UNIX, AF_INET and\n+// AF_INET6 addresses.\n+//\n+// strict indicates whether addresses with the AF_UNSPEC family are accepted of not.\n+//\n+// AddressAndFamily returns an address, its family.\n+func AddressAndFamily(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, uint16, *syserr.Error) {\n// Make sure we have at least 2 bytes for the address family.\nif len(addr) < 2 {\n- return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n+ return tcpip.FullAddress{}, 0, syserr.ErrInvalidArgument\n}\nfamily := usermem.ByteOrder.Uint16(addr)\nif family != uint16(sfamily) && (!strict && family != linux.AF_UNSPEC) {\n- return tcpip.FullAddress{}, syserr.ErrAddressFamilyNotSupported\n+ return tcpip.FullAddress{}, family, syserr.ErrAddressFamilyNotSupported\n}\n// Get the rest of the fields based on the address family.\n@@ -310,7 +314,7 @@ func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syse\ncase linux.AF_UNIX:\npath := addr[2:]\nif len(path) > linux.UnixPathMax {\n- return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n}\n// Drop the terminating NUL (if one exists) and everything after\n// it for filesystem (non-abstract) addresses.\n@@ -321,12 +325,12 @@ func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syse\n}\nreturn tcpip.FullAddress{\nAddr: tcpip.Address(path),\n- }, nil\n+ }, family, nil\ncase linux.AF_INET:\nvar a linux.SockAddrInet\nif len(addr) < sockAddrInetSize {\n- return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n}\nbinary.Unmarshal(addr[:sockAddrInetSize], usermem.ByteOrder, &a)\n@@ -334,12 +338,12 @@ func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syse\nAddr: bytesToIPAddress(a.Addr[:]),\nPort: ntohs(a.Port),\n}\n- return out, nil\n+ return out, family, nil\ncase linux.AF_INET6:\nvar a linux.SockAddrInet6\nif len(addr) < sockAddrInet6Size {\n- return tcpip.FullAddress{}, syserr.ErrInvalidArgument\n+ return tcpip.FullAddress{}, family, syserr.ErrInvalidArgument\n}\nbinary.Unmarshal(addr[:sockAddrInet6Size], usermem.ByteOrder, &a)\n@@ -350,13 +354,13 @@ func GetAddress(sfamily int, addr []byte, strict bool) (tcpip.FullAddress, *syse\nif isLinkLocal(out.Addr) {\nout.NIC = tcpip.NICID(a.Scope_id)\n}\n- return out, nil\n+ return out, family, nil\ncase linux.AF_UNSPEC:\n- return tcpip.FullAddress{}, nil\n+ return tcpip.FullAddress{}, family, nil\ndefault:\n- return tcpip.FullAddress{}, syserr.ErrAddressFamilyNotSupported\n+ return tcpip.FullAddress{}, 0, syserr.ErrAddressFamilyNotSupported\n}\n}\n@@ -482,11 +486,18 @@ func (s *SocketOperations) Readiness(mask waiter.EventMask) waiter.EventMask {\n// Connect implements the linux syscall connect(2) for sockets backed by\n// tpcip.Endpoint.\nfunc (s *SocketOperations) Connect(t *kernel.Task, sockaddr []byte, blocking bool) *syserr.Error {\n- addr, err := GetAddress(s.family, sockaddr, false /* strict */)\n+ addr, family, err := AddressAndFamily(s.family, sockaddr, false /* strict */)\nif err != nil {\nreturn err\n}\n+ if family == linux.AF_UNSPEC {\n+ err := s.Endpoint.Disconnect()\n+ if err == tcpip.ErrNotSupported {\n+ return syserr.ErrAddressFamilyNotSupported\n+ }\n+ return syserr.TranslateNetstackError(err)\n+ }\n// Always return right away in the non-blocking case.\nif !blocking {\nreturn syserr.TranslateNetstackError(s.Endpoint.Connect(addr))\n@@ -515,7 +526,7 @@ func (s *SocketOperations) Connect(t *kernel.Task, sockaddr []byte, blocking boo\n// Bind implements the linux syscall bind(2) for sockets backed by\n// tcpip.Endpoint.\nfunc (s *SocketOperations) Bind(t *kernel.Task, sockaddr []byte) *syserr.Error {\n- addr, err := GetAddress(s.family, sockaddr, true /* strict */)\n+ addr, _, err := AddressAndFamily(s.family, sockaddr, true /* strict */)\nif err != nil {\nreturn err\n}\n@@ -2023,7 +2034,7 @@ func (s *SocketOperations) SendMsg(t *kernel.Task, src usermem.IOSequence, to []\nvar addr *tcpip.FullAddress\nif len(to) > 0 {\n- addrBuf, err := GetAddress(s.family, to, true /* strict */)\n+ addrBuf, _, err := AddressAndFamily(s.family, to, true /* strict */)\nif err != nil {\nreturn 0, err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/unix.go",
"new_path": "pkg/sentry/socket/unix/unix.go",
"diff": "@@ -116,7 +116,7 @@ func (s *SocketOperations) Endpoint() transport.Endpoint {\n// extractPath extracts and validates the address.\nfunc extractPath(sockaddr []byte) (string, *syserr.Error) {\n- addr, err := epsocket.GetAddress(linux.AF_UNIX, sockaddr, true /* strict */)\n+ addr, _, err := epsocket.AddressAndFamily(linux.AF_UNIX, sockaddr, true /* strict */)\nif err != nil {\nreturn \"\", err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/strace/socket.go",
"new_path": "pkg/sentry/strace/socket.go",
"diff": "@@ -332,7 +332,7 @@ func sockAddr(t *kernel.Task, addr usermem.Addr, length uint32) string {\nswitch family {\ncase linux.AF_INET, linux.AF_INET6, linux.AF_UNIX:\n- fa, err := epsocket.GetAddress(int(family), b, true /* strict */)\n+ fa, _, err := epsocket.AddressAndFamily(int(family), b, true /* strict */)\nif err != nil {\nreturn fmt.Sprintf(\"%#x {Family: %s, error extracting address: %v}\", addr, familyStr, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/transport_test.go",
"new_path": "pkg/tcpip/stack/transport_test.go",
"diff": "@@ -105,6 +105,11 @@ func (*fakeTransportEndpoint) GetSockOpt(opt interface{}) *tcpip.Error {\nreturn tcpip.ErrInvalidEndpointState\n}\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (*fakeTransportEndpoint) Disconnect() *tcpip.Error {\n+ return tcpip.ErrNotSupported\n+}\n+\nfunc (f *fakeTransportEndpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nf.peerAddr = addr.Addr\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -358,6 +358,9 @@ type Endpoint interface {\n// ErrAddressFamilyNotSupported must be returned.\nConnect(address FullAddress) *Error\n+ // Disconnect disconnects the endpoint from its peer.\n+ Disconnect() *Error\n+\n// Shutdown closes the read and/or write end of the endpoint connection\n// to its peer.\nShutdown(flags ShutdownFlags) *Error\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/icmp/endpoint.go",
"new_path": "pkg/tcpip/transport/icmp/endpoint.go",
"diff": "@@ -428,16 +428,16 @@ func (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress, allowMismatch bool) (t\nreturn netProto, nil\n}\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (*endpoint) Disconnect() *tcpip.Error {\n+ return tcpip.ErrNotSupported\n+}\n+\n// Connect connects the endpoint to its peer. Specifying a NIC is optional.\nfunc (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n- if addr.Addr == \"\" {\n- // AF_UNSPEC isn't supported.\n- return tcpip.ErrAddressFamilyNotSupported\n- }\n-\nnicid := addr.NIC\nlocalPort := uint16(0)\nswitch e.state {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/raw/endpoint.go",
"new_path": "pkg/tcpip/transport/raw/endpoint.go",
"diff": "@@ -349,16 +349,16 @@ func (ep *endpoint) Peek([][]byte) (int64, tcpip.ControlMessages, *tcpip.Error)\nreturn 0, tcpip.ControlMessages{}, nil\n}\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (*endpoint) Disconnect() *tcpip.Error {\n+ return tcpip.ErrNotSupported\n+}\n+\n// Connect implements tcpip.Endpoint.Connect.\nfunc (ep *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nep.mu.Lock()\ndefer ep.mu.Unlock()\n- if addr.Addr == \"\" {\n- // AF_UNSPEC isn't supported.\n- return tcpip.ErrAddressFamilyNotSupported\n- }\n-\nif ep.closed {\nreturn tcpip.ErrInvalidEndpointState\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/endpoint.go",
"new_path": "pkg/tcpip/transport/tcp/endpoint.go",
"diff": "@@ -1362,13 +1362,13 @@ func (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress) (tcpip.NetworkProtocol\nreturn netProto, nil\n}\n-// Connect connects the endpoint to its peer.\n-func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\n- if addr.Addr == \"\" && addr.Port == 0 {\n- // AF_UNSPEC isn't supported.\n- return tcpip.ErrAddressFamilyNotSupported\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (*endpoint) Disconnect() *tcpip.Error {\n+ return tcpip.ErrNotSupported\n}\n+// Connect connects the endpoint to its peer.\n+func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nreturn e.connect(addr, true, true)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/udp/endpoint.go",
"new_path": "pkg/tcpip/transport/udp/endpoint.go",
"diff": "@@ -711,7 +711,8 @@ func (e *endpoint) checkV4Mapped(addr *tcpip.FullAddress, allowMismatch bool) (t\nreturn netProto, nil\n}\n-func (e *endpoint) disconnect() *tcpip.Error {\n+// Disconnect implements tcpip.Endpoint.Disconnect.\n+func (e *endpoint) Disconnect() *tcpip.Error {\ne.mu.Lock()\ndefer e.mu.Unlock()\n@@ -750,9 +751,6 @@ func (e *endpoint) Connect(addr tcpip.FullAddress) *tcpip.Error {\nif err != nil {\nreturn err\n}\n- if addr.Addr == \"\" {\n- return e.disconnect()\n- }\nif addr.Port == 0 {\n// We don't support connecting to port zero.\nreturn tcpip.ErrInvalidEndpointState\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/udp_socket.cc",
"new_path": "test/syscalls/linux/udp_socket.cc",
"diff": "@@ -378,16 +378,17 @@ TEST_P(UdpSocketTest, Connect) {\nEXPECT_EQ(memcmp(&peer, addr_[2], addrlen_), 0);\n}\n-TEST_P(UdpSocketTest, ConnectAny) {\n+void ConnectAny(AddressFamily family, int sockfd, uint16_t port) {\nstruct sockaddr_storage addr = {};\n// Precondition check.\n{\nsocklen_t addrlen = sizeof(addr);\n- EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ EXPECT_THAT(\n+ getsockname(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\nSyscallSucceeds());\n- if (GetParam() == AddressFamily::kIpv4) {\n+ if (family == AddressFamily::kIpv4) {\nauto addr_out = reinterpret_cast<struct sockaddr_in*>(&addr);\nEXPECT_EQ(addrlen, sizeof(*addr_out));\nEXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_ANY));\n@@ -400,21 +401,24 @@ TEST_P(UdpSocketTest, ConnectAny) {\n{\nsocklen_t addrlen = sizeof(addr);\n- EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ EXPECT_THAT(\n+ getpeername(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\nSyscallFailsWithErrno(ENOTCONN));\n}\nstruct sockaddr_storage baddr = {};\n- if (GetParam() == AddressFamily::kIpv4) {\n+ if (family == AddressFamily::kIpv4) {\nauto addr_in = reinterpret_cast<struct sockaddr_in*>(&baddr);\naddrlen = sizeof(*addr_in);\naddr_in->sin_family = AF_INET;\naddr_in->sin_addr.s_addr = htonl(INADDR_ANY);\n+ addr_in->sin_port = port;\n} else {\nauto addr_in = reinterpret_cast<struct sockaddr_in6*>(&baddr);\naddrlen = sizeof(*addr_in);\naddr_in->sin6_family = AF_INET6;\n- if (GetParam() == AddressFamily::kIpv6) {\n+ addr_in->sin6_port = port;\n+ if (family == AddressFamily::kIpv6) {\naddr_in->sin6_addr = IN6ADDR_ANY_INIT;\n} else {\nTestAddress const& v4_mapped_any = V4MappedAny();\n@@ -424,21 +428,23 @@ TEST_P(UdpSocketTest, ConnectAny) {\n}\n}\n- ASSERT_THAT(connect(s_, reinterpret_cast<sockaddr*>(&baddr), addrlen),\n- SyscallSucceeds());\n+ // TODO(b/138658473): gVisor doesn't allow connecting to the zero port.\n+ if (port == 0) {\n+ SKIP_IF(IsRunningOnGvisor());\n}\n- // TODO(b/138658473): gVisor doesn't return the correct local address after\n- // connecting to the any address.\n- SKIP_IF(IsRunningOnGvisor());\n+ ASSERT_THAT(connect(sockfd, reinterpret_cast<sockaddr*>(&baddr), addrlen),\n+ SyscallSucceeds());\n+ }\n// Postcondition check.\n{\nsocklen_t addrlen = sizeof(addr);\n- EXPECT_THAT(getsockname(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ EXPECT_THAT(\n+ getsockname(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\nSyscallSucceeds());\n- if (GetParam() == AddressFamily::kIpv4) {\n+ if (family == AddressFamily::kIpv4) {\nauto addr_out = reinterpret_cast<struct sockaddr_in*>(&addr);\nEXPECT_EQ(addrlen, sizeof(*addr_out));\nEXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_LOOPBACK));\n@@ -446,7 +452,7 @@ TEST_P(UdpSocketTest, ConnectAny) {\nauto addr_out = reinterpret_cast<struct sockaddr_in6*>(&addr);\nEXPECT_EQ(addrlen, sizeof(*addr_out));\nstruct in6_addr loopback;\n- if (GetParam() == AddressFamily::kIpv6) {\n+ if (family == AddressFamily::kIpv6) {\nloopback = IN6ADDR_LOOPBACK_INIT;\n} else {\nTestAddress const& v4_mapped_loopback = V4MappedLoopback();\n@@ -459,9 +465,89 @@ TEST_P(UdpSocketTest, ConnectAny) {\n}\naddrlen = sizeof(addr);\n- EXPECT_THAT(getpeername(s_, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ if (port == 0) {\n+ EXPECT_THAT(\n+ getpeername(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\nSyscallFailsWithErrno(ENOTCONN));\n+ } else {\n+ EXPECT_THAT(\n+ getpeername(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+ }\n+ }\n}\n+\n+TEST_P(UdpSocketTest, ConnectAny) { ConnectAny(GetParam(), s_, 0); }\n+\n+TEST_P(UdpSocketTest, ConnectAnyWithPort) {\n+ auto port = *Port(reinterpret_cast<struct sockaddr_storage*>(addr_[1]));\n+ ConnectAny(GetParam(), s_, port);\n+}\n+\n+void DisconnectAfterConnectAny(AddressFamily family, int sockfd, int port) {\n+ struct sockaddr_storage addr = {};\n+\n+ socklen_t addrlen = sizeof(addr);\n+ struct sockaddr_storage baddr = {};\n+ if (family == AddressFamily::kIpv4) {\n+ auto addr_in = reinterpret_cast<struct sockaddr_in*>(&baddr);\n+ addrlen = sizeof(*addr_in);\n+ addr_in->sin_family = AF_INET;\n+ addr_in->sin_addr.s_addr = htonl(INADDR_ANY);\n+ addr_in->sin_port = port;\n+ } else {\n+ auto addr_in = reinterpret_cast<struct sockaddr_in6*>(&baddr);\n+ addrlen = sizeof(*addr_in);\n+ addr_in->sin6_family = AF_INET6;\n+ addr_in->sin6_port = port;\n+ if (family == AddressFamily::kIpv6) {\n+ addr_in->sin6_addr = IN6ADDR_ANY_INIT;\n+ } else {\n+ TestAddress const& v4_mapped_any = V4MappedAny();\n+ addr_in->sin6_addr =\n+ reinterpret_cast<const struct sockaddr_in6*>(&v4_mapped_any.addr)\n+ ->sin6_addr;\n+ }\n+ }\n+\n+ // TODO(b/138658473): gVisor doesn't allow connecting to the zero port.\n+ if (port == 0) {\n+ SKIP_IF(IsRunningOnGvisor());\n+ }\n+\n+ ASSERT_THAT(connect(sockfd, reinterpret_cast<sockaddr*>(&baddr), addrlen),\n+ SyscallSucceeds());\n+ // Now the socket is bound to the loopback address.\n+\n+ // Disconnect\n+ addrlen = sizeof(addr);\n+ addr.ss_family = AF_UNSPEC;\n+ ASSERT_THAT(connect(sockfd, reinterpret_cast<sockaddr*>(&addr), addrlen),\n+ SyscallSucceeds());\n+\n+ // Check that after disconnect the socket is bound to the ANY address.\n+ EXPECT_THAT(getsockname(sockfd, reinterpret_cast<sockaddr*>(&addr), &addrlen),\n+ SyscallSucceeds());\n+ if (family == AddressFamily::kIpv4) {\n+ auto addr_out = reinterpret_cast<struct sockaddr_in*>(&addr);\n+ EXPECT_EQ(addrlen, sizeof(*addr_out));\n+ EXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_ANY));\n+ } else {\n+ auto addr_out = reinterpret_cast<struct sockaddr_in6*>(&addr);\n+ EXPECT_EQ(addrlen, sizeof(*addr_out));\n+ struct in6_addr loopback = IN6ADDR_ANY_INIT;\n+\n+ EXPECT_EQ(memcmp(&addr_out->sin6_addr, &loopback, sizeof(in6_addr)), 0);\n+ }\n+}\n+\n+TEST_P(UdpSocketTest, DisconnectAfterConnectAny) {\n+ DisconnectAfterConnectAny(GetParam(), s_, 0);\n+}\n+\n+TEST_P(UdpSocketTest, DisconnectAfterConnectAnyWithPort) {\n+ auto port = *Port(reinterpret_cast<struct sockaddr_storage*>(addr_[1]));\n+ DisconnectAfterConnectAny(GetParam(), s_, port);\n}\nTEST_P(UdpSocketTest, DisconnectAfterBind) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack: disconnect an unix socket only if the address family is AF_UNSPEC
Linux allows to call connect for ANY and the zero port.
PiperOrigin-RevId: 263892534 |
259,891 | 19.08.2019 10:04:54 | 25,200 | bd826092fecf32a87a3207a23c3795e819babce7 | Read iptables via sockopts. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/stack.go",
"new_path": "pkg/sentry/socket/epsocket/stack.go",
"diff": "@@ -198,8 +198,8 @@ func (s *Stack) IPTables() (iptables.IPTables, error) {\n// FillDefaultIPTables sets the stack's iptables to the default tables, which\n// allow and do not modify all traffic.\n-func (s *Stack) FillDefaultIPTables() error {\n- return netfilter.FillDefaultIPTables(s.Stack)\n+func (s *Stack) FillDefaultIPTables() {\n+ netfilter.FillDefaultIPTables(s.Stack)\n}\n// Resume implements inet.Stack.Resume.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/BUILD",
"new_path": "pkg/sentry/socket/netfilter/BUILD",
"diff": "@@ -13,6 +13,7 @@ go_library(\nvisibility = [\"//pkg/sentry:internal\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/binary\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/usermem\",\n\"//pkg/syserr\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/netfilter/netfilter.go",
"new_path": "pkg/sentry/socket/netfilter/netfilter.go",
"diff": "package netfilter\nimport (\n+ \"fmt\"\n+\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n@@ -26,21 +29,258 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n+// errorTargetName is used to mark targets as error targets. Error targets\n+// shouldn't be reached - an error has occurred if we fall through to one.\n+const errorTargetName = \"ERROR\"\n+\n+// metadata is opaque to netstack. It holds data that we need to translate\n+// between Linux's and netstack's iptables representations.\n+type metadata struct {\n+ HookEntry [linux.NF_INET_NUMHOOKS]uint32\n+ Underflow [linux.NF_INET_NUMHOOKS]uint32\n+ NumEntries uint32\n+ Size uint32\n+}\n+\n// GetInfo returns information about iptables.\nfunc GetInfo(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr) (linux.IPTGetinfo, *syserr.Error) {\n- // TODO(b/129292233): Implement.\n- return linux.IPTGetinfo{}, syserr.ErrInvalidArgument\n+ // Read in the struct and table name.\n+ var info linux.IPTGetinfo\n+ if _, err := t.CopyIn(outPtr, &info); err != nil {\n+ return linux.IPTGetinfo{}, syserr.FromError(err)\n+ }\n+\n+ // Find the appropriate table.\n+ table, err := findTable(ep, info.TableName())\n+ if err != nil {\n+ return linux.IPTGetinfo{}, err\n+ }\n+\n+ // Get the hooks that apply to this table.\n+ info.ValidHooks = table.ValidHooks()\n+\n+ // Grab the metadata struct, which is used to store information (e.g.\n+ // the number of entries) that applies to the user's encoding of\n+ // iptables, but not netstack's.\n+ metadata := table.Metadata().(metadata)\n+\n+ // Set values from metadata.\n+ info.HookEntry = metadata.HookEntry\n+ info.Underflow = metadata.Underflow\n+ info.NumEntries = metadata.NumEntries\n+ info.Size = metadata.Size\n+\n+ return info, nil\n}\n// GetEntries returns netstack's iptables rules encoded for the iptables tool.\nfunc GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen int) (linux.KernelIPTGetEntries, *syserr.Error) {\n- // TODO(b/129292233): Implement.\n+ // Read in the struct and table name.\n+ var userEntries linux.IPTGetEntries\n+ if _, err := t.CopyIn(outPtr, &userEntries); err != nil {\n+ return linux.KernelIPTGetEntries{}, syserr.FromError(err)\n+ }\n+\n+ // Find the appropriate table.\n+ table, err := findTable(ep, userEntries.TableName())\n+ if err != nil {\n+ return linux.KernelIPTGetEntries{}, err\n+ }\n+\n+ // Convert netstack's iptables rules to something that the iptables\n+ // tool can understand.\n+ entries, _, err := convertNetstackToBinary(userEntries.TableName(), table)\n+ if err != nil {\n+ return linux.KernelIPTGetEntries{}, err\n+ }\n+ if binary.Size(entries) > uintptr(outLen) {\nreturn linux.KernelIPTGetEntries{}, syserr.ErrInvalidArgument\n}\n+ return entries, nil\n+}\n+\n+func findTable(ep tcpip.Endpoint, tableName string) (iptables.Table, *syserr.Error) {\n+ ipt, err := ep.IPTables()\n+ if err != nil {\n+ return iptables.Table{}, syserr.FromError(err)\n+ }\n+ table, ok := ipt.Tables[tableName]\n+ if !ok {\n+ return iptables.Table{}, syserr.ErrInvalidArgument\n+ }\n+ return table, nil\n+}\n+\n// FillDefaultIPTables sets stack's IPTables to the default tables and\n// populates them with metadata.\n-func FillDefaultIPTables(stack *stack.Stack) error {\n- stack.SetIPTables(iptables.DefaultTables())\n- return nil\n+func FillDefaultIPTables(stack *stack.Stack) {\n+ ipt := iptables.DefaultTables()\n+\n+ // In order to fill in the metadata, we have to translate ipt from its\n+ // netstack format to Linux's giant-binary-blob format.\n+ for name, table := range ipt.Tables {\n+ _, metadata, err := convertNetstackToBinary(name, table)\n+ if err != nil {\n+ panic(fmt.Errorf(\"Unable to set default IP tables: %v\", err))\n+ }\n+ table.SetMetadata(metadata)\n+ ipt.Tables[name] = table\n+ }\n+\n+ stack.SetIPTables(ipt)\n+}\n+\n+// convertNetstackToBinary converts the iptables as stored in netstack to the\n+// format expected by the iptables tool. Linux stores each table as a binary\n+// blob that can only be traversed by parsing a bit, reading some offsets,\n+// jumping to those offsets, parsing again, etc.\n+func convertNetstackToBinary(name string, table iptables.Table) (linux.KernelIPTGetEntries, metadata, *syserr.Error) {\n+ // Return values.\n+ var entries linux.KernelIPTGetEntries\n+ var meta metadata\n+\n+ // The table name has to fit in the struct.\n+ if linux.XT_TABLE_MAXNAMELEN < len(name) {\n+ return linux.KernelIPTGetEntries{}, metadata{}, syserr.ErrInvalidArgument\n+ }\n+ copy(entries.Name[:], name)\n+\n+ // Deal with the built in chains first (INPUT, OUTPUT, etc.). Each of\n+ // these chains ends with an unconditional policy entry.\n+ for hook := iptables.Prerouting; hook < iptables.NumHooks; hook++ {\n+ chain, ok := table.BuiltinChains[hook]\n+ if !ok {\n+ // This table doesn't support this hook.\n+ continue\n+ }\n+\n+ // Sanity check.\n+ if len(chain.Rules) < 1 {\n+ return linux.KernelIPTGetEntries{}, metadata{}, syserr.ErrInvalidArgument\n+ }\n+\n+ for ruleIdx, rule := range chain.Rules {\n+ // If this is the first rule of a builtin chain, set\n+ // the metadata hook entry point.\n+ if ruleIdx == 0 {\n+ meta.HookEntry[hook] = entries.Size\n+ }\n+\n+ // Each rule corresponds to an entry.\n+ entry := linux.KernelIPTEntry{\n+ IPTEntry: linux.IPTEntry{\n+ NextOffset: linux.SizeOfIPTEntry,\n+ TargetOffset: linux.SizeOfIPTEntry,\n+ },\n+ }\n+\n+ for _, matcher := range rule.Matchers {\n+ // Serialize the matcher and add it to the\n+ // entry.\n+ serialized := marshalMatcher(matcher)\n+ entry.Elems = append(entry.Elems, serialized...)\n+ entry.NextOffset += uint16(len(serialized))\n+ entry.TargetOffset += uint16(len(serialized))\n+ }\n+\n+ // Serialize and append the target.\n+ serialized := marshalTarget(rule.Target)\n+ entry.Elems = append(entry.Elems, serialized...)\n+ entry.NextOffset += uint16(len(serialized))\n+\n+ // The underflow rule is the last rule in the chain,\n+ // and is an unconditional rule (i.e. it matches any\n+ // packet). This is enforced when saving iptables.\n+ if ruleIdx == len(chain.Rules)-1 {\n+ meta.Underflow[hook] = entries.Size\n+ }\n+\n+ entries.Size += uint32(entry.NextOffset)\n+ entries.Entrytable = append(entries.Entrytable, entry)\n+ meta.NumEntries++\n+ }\n+\n+ }\n+\n+ // TODO(gvisor.dev/issue/170): Deal with the user chains here. Each of\n+ // these starts with an error node holding the chain's name and ends\n+ // with an unconditional return.\n+\n+ // Lastly, each table ends with an unconditional error target rule as\n+ // its final entry.\n+ errorEntry := linux.KernelIPTEntry{\n+ IPTEntry: linux.IPTEntry{\n+ NextOffset: linux.SizeOfIPTEntry,\n+ TargetOffset: linux.SizeOfIPTEntry,\n+ },\n+ }\n+ var errorTarget linux.XTErrorTarget\n+ errorTarget.Target.TargetSize = linux.SizeOfXTErrorTarget\n+ copy(errorTarget.ErrorName[:], errorTargetName)\n+ copy(errorTarget.Target.Name[:], errorTargetName)\n+\n+ // Serialize and add it to the list of entries.\n+ errorTargetBuf := make([]byte, 0, linux.SizeOfXTErrorTarget)\n+ serializedErrorTarget := binary.Marshal(errorTargetBuf, usermem.ByteOrder, errorTarget)\n+ errorEntry.Elems = append(errorEntry.Elems, serializedErrorTarget...)\n+ errorEntry.NextOffset += uint16(len(serializedErrorTarget))\n+\n+ entries.Size += uint32(errorEntry.NextOffset)\n+ entries.Entrytable = append(entries.Entrytable, errorEntry)\n+ meta.NumEntries++\n+ meta.Size = entries.Size\n+\n+ return entries, meta, nil\n+}\n+\n+func marshalMatcher(matcher iptables.Matcher) []byte {\n+ switch matcher.(type) {\n+ default:\n+ // TODO(gvisor.dev/issue/170): We don't support any matchers yet, so\n+ // any call to marshalMatcher will panic.\n+ panic(fmt.Errorf(\"unknown matcher of type %T\", matcher))\n+ }\n+}\n+\n+func marshalTarget(target iptables.Target) []byte {\n+ switch target.(type) {\n+ case iptables.UnconditionalAcceptTarget:\n+ return marshalUnconditionalAcceptTarget()\n+ default:\n+ panic(fmt.Errorf(\"unknown target of type %T\", target))\n+ }\n+}\n+\n+func marshalUnconditionalAcceptTarget() []byte {\n+ // The target's name will be the empty string.\n+ target := linux.XTStandardTarget{\n+ Target: linux.XTEntryTarget{\n+ TargetSize: linux.SizeOfXTStandardTarget,\n+ },\n+ Verdict: translateStandardVerdict(iptables.Accept),\n+ }\n+\n+ ret := make([]byte, 0, linux.SizeOfXTStandardTarget)\n+ return binary.Marshal(ret, usermem.ByteOrder, target)\n+}\n+\n+// translateStandardVerdict translates verdicts the same way as the iptables\n+// tool.\n+func translateStandardVerdict(verdict iptables.Verdict) int32 {\n+ switch verdict {\n+ case iptables.Accept:\n+ return -linux.NF_ACCEPT - 1\n+ case iptables.Drop:\n+ return -linux.NF_DROP - 1\n+ case iptables.Queue:\n+ return -linux.NF_QUEUE - 1\n+ case iptables.Return:\n+ return linux.NF_RETURN\n+ case iptables.Jump:\n+ // TODO(gvisor.dev/issue/170): Support Jump.\n+ panic(\"Jump isn't supported yet\")\n+ default:\n+ panic(fmt.Sprintf(\"unknown standard verdict: %d\", verdict))\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -179,6 +179,10 @@ syscall_test(\ntest = \"//test/syscalls/linux:ioctl_test\",\n)\n+syscall_test(\n+ test = \"//test/syscalls/linux:iptables_test\",\n+)\n+\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:itimer_test\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -912,6 +912,24 @@ cc_library(\n],\n)\n+cc_binary(\n+ name = \"iptables_test\",\n+ testonly = 1,\n+ srcs = [\n+ \"iptables.cc\",\n+ ],\n+ linkstatic = 1,\n+ deps = [\n+ \":iptables_types\",\n+ \":socket_test_util\",\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\ncc_binary(\nname = \"itimer_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/iptables.cc",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include \"test/syscalls/linux/iptables.h\"\n+\n+#include <arpa/inet.h>\n+#include <linux/capability.h>\n+#include <linux/netfilter/x_tables.h>\n+#include <net/if.h>\n+#include <netinet/in.h>\n+#include <netinet/ip.h>\n+#include <netinet/ip_icmp.h>\n+#include <stdio.h>\n+#include <sys/poll.h>\n+#include <sys/socket.h>\n+#include <sys/types.h>\n+#include <unistd.h>\n+\n+#include <algorithm>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+constexpr char kNatTablename[] = \"nat\";\n+constexpr char kErrorTarget[] = \"ERROR\";\n+constexpr size_t kEmptyStandardEntrySize =\n+ sizeof(struct ipt_entry) + sizeof(struct ipt_standard_target);\n+constexpr size_t kEmptyErrorEntrySize =\n+ sizeof(struct ipt_entry) + sizeof(struct ipt_error_target);\n+\n+TEST(IPTablesBasic, CreateSocket) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ int sock;\n+ ASSERT_THAT(sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP),\n+ SyscallSucceeds());\n+\n+ ASSERT_THAT(close(sock), SyscallSucceeds());\n+}\n+\n+TEST(IPTablesBasic, FailSockoptNonRaw) {\n+ // Even if the user has CAP_NET_RAW, they shouldn't be able to use the\n+ // iptables sockopts with a non-raw socket.\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ int sock;\n+ ASSERT_THAT(sock = socket(AF_INET, SOCK_DGRAM, 0), SyscallSucceeds());\n+\n+ struct ipt_getinfo info = {};\n+ snprintf(info.name, XT_TABLE_MAXNAMELEN, \"%s\", kNatTablename);\n+ socklen_t info_size = sizeof(info);\n+ EXPECT_THAT(getsockopt(sock, IPPROTO_IP, SO_GET_INFO, &info, &info_size),\n+ SyscallFailsWithErrno(ENOPROTOOPT));\n+\n+ ASSERT_THAT(close(sock), SyscallSucceeds());\n+}\n+\n+// Fixture for iptables tests.\n+class IPTablesTest : public ::testing::Test {\n+ protected:\n+ // Creates a socket to be used in tests.\n+ void SetUp() override;\n+\n+ // Closes the socket created by SetUp().\n+ void TearDown() override;\n+\n+ // The socket via which to manipulate iptables.\n+ int s_;\n+};\n+\n+void IPTablesTest::SetUp() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ ASSERT_THAT(s_ = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), SyscallSucceeds());\n+}\n+\n+void IPTablesTest::TearDown() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ EXPECT_THAT(close(s_), SyscallSucceeds());\n+}\n+\n+// This tests the initial state of a machine with empty iptables. We don't have\n+// a guarantee that the iptables are empty when running in native, but we can\n+// test that gVisor has the same initial state that a newly-booted Linux machine\n+// would have.\n+TEST_F(IPTablesTest, InitialState) {\n+ SKIP_IF(!IsRunningOnGvisor());\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+\n+ //\n+ // Get info via sockopt.\n+ //\n+ struct ipt_getinfo info = {};\n+ snprintf(info.name, XT_TABLE_MAXNAMELEN, \"%s\", kNatTablename);\n+ socklen_t info_size = sizeof(info);\n+ ASSERT_THAT(getsockopt(s_, IPPROTO_IP, SO_GET_INFO, &info, &info_size),\n+ SyscallSucceeds());\n+\n+ // The nat table supports PREROUTING, and OUTPUT.\n+ unsigned int valid_hooks = (1 << NF_IP_PRE_ROUTING) | (1 << NF_IP_LOCAL_OUT) |\n+ (1 << NF_IP_POST_ROUTING) | (1 << NF_IP_LOCAL_IN);\n+\n+ EXPECT_EQ(info.valid_hooks, valid_hooks);\n+\n+ // Each chain consists of an empty entry with a standard target..\n+ EXPECT_EQ(info.hook_entry[NF_IP_PRE_ROUTING], 0);\n+ EXPECT_EQ(info.hook_entry[NF_IP_LOCAL_IN], kEmptyStandardEntrySize);\n+ EXPECT_EQ(info.hook_entry[NF_IP_LOCAL_OUT], kEmptyStandardEntrySize * 2);\n+ EXPECT_EQ(info.hook_entry[NF_IP_POST_ROUTING], kEmptyStandardEntrySize * 3);\n+\n+ // The underflow points are the same as the entry points.\n+ EXPECT_EQ(info.underflow[NF_IP_PRE_ROUTING], 0);\n+ EXPECT_EQ(info.underflow[NF_IP_LOCAL_IN], kEmptyStandardEntrySize);\n+ EXPECT_EQ(info.underflow[NF_IP_LOCAL_OUT], kEmptyStandardEntrySize * 2);\n+ EXPECT_EQ(info.underflow[NF_IP_POST_ROUTING], kEmptyStandardEntrySize * 3);\n+\n+ // One entry for each chain, plus an error entry at the end.\n+ EXPECT_EQ(info.num_entries, 5);\n+\n+ EXPECT_EQ(info.size, 4 * kEmptyStandardEntrySize + kEmptyErrorEntrySize);\n+ EXPECT_EQ(strcmp(info.name, kNatTablename), 0);\n+\n+ //\n+ // Use info to get entries.\n+ //\n+ socklen_t entries_size = sizeof(struct ipt_get_entries) + info.size;\n+ struct ipt_get_entries* entries =\n+ static_cast<struct ipt_get_entries*>(malloc(entries_size));\n+ snprintf(entries->name, XT_TABLE_MAXNAMELEN, \"%s\", kNatTablename);\n+ entries->size = info.size;\n+ ASSERT_THAT(\n+ getsockopt(s_, IPPROTO_IP, SO_GET_ENTRIES, entries, &entries_size),\n+ SyscallSucceeds());\n+\n+ // Verify the name and size.\n+ ASSERT_EQ(info.size, entries->size);\n+ ASSERT_EQ(strcmp(entries->name, kNatTablename), 0);\n+\n+ // Verify that the entrytable is 4 entries with accept targets and no matches\n+ // followed by a single error target.\n+ size_t entry_offset = 0;\n+ while (entry_offset < entries->size) {\n+ struct ipt_entry* entry = reinterpret_cast<struct ipt_entry*>(\n+ reinterpret_cast<char*>(entries->entrytable) + entry_offset);\n+\n+ // ip should be zeroes.\n+ struct ipt_ip zeroed = {};\n+ EXPECT_EQ(memcmp(static_cast<void*>(&zeroed),\n+ static_cast<void*>(&entry->ip), sizeof(zeroed)),\n+ 0);\n+\n+ // target_offset should be zero.\n+ EXPECT_EQ(entry->target_offset, sizeof(ipt_entry));\n+\n+ if (entry_offset < kEmptyStandardEntrySize * 4) {\n+ // The first 4 entries are standard targets\n+ struct ipt_standard_target* target =\n+ reinterpret_cast<struct ipt_standard_target*>(entry->elems);\n+ EXPECT_EQ(entry->next_offset, kEmptyStandardEntrySize);\n+ EXPECT_EQ(target->target.u.user.target_size, sizeof(*target));\n+ EXPECT_EQ(strcmp(target->target.u.user.name, \"\"), 0);\n+ EXPECT_EQ(target->target.u.user.revision, 0);\n+ // This is what's returned for an accept verdict. I don't know why.\n+ EXPECT_EQ(target->verdict, -NF_ACCEPT - 1);\n+ } else {\n+ // The last entry is an error target\n+ struct ipt_error_target* target =\n+ reinterpret_cast<struct ipt_error_target*>(entry->elems);\n+ EXPECT_EQ(entry->next_offset, kEmptyErrorEntrySize);\n+ EXPECT_EQ(target->target.u.user.target_size, sizeof(*target));\n+ EXPECT_EQ(strcmp(target->target.u.user.name, kErrorTarget), 0);\n+ EXPECT_EQ(target->target.u.user.revision, 0);\n+ EXPECT_EQ(strcmp(target->errorname, kErrorTarget), 0);\n+ }\n+\n+ entry_offset += entry->next_offset;\n+ }\n+\n+ free(entries);\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Read iptables via sockopts.
PiperOrigin-RevId: 264180125 |
259,883 | 19.08.2019 12:09:08 | 25,200 | a63f88855f9c5d9340028e5828617a263dbf3023 | hostinet: fix parsing route netlink message
We wrongly parses output interface as gateway address.
The fix is straightforward.
Fixes
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/684 from tanjianfeng:fix-638 | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/hostinet/stack.go",
"new_path": "pkg/sentry/socket/hostinet/stack.go",
"diff": "@@ -203,8 +203,14 @@ func ExtractHostRoutes(routeMsgs []syscall.NetlinkMessage) ([]inet.Route, error)\ninetRoute.DstAddr = attr.Value\ncase syscall.RTA_SRC:\ninetRoute.SrcAddr = attr.Value\n- case syscall.RTA_OIF:\n+ case syscall.RTA_GATEWAY:\ninetRoute.GatewayAddr = attr.Value\n+ case syscall.RTA_OIF:\n+ expected := int(binary.Size(inetRoute.OutputInterface))\n+ if len(attr.Value) != expected {\n+ return nil, fmt.Errorf(\"RTM_GETROUTE returned RTM_NEWROUTE message with invalid attribute data length (%d bytes, expected %d bytes)\", len(attr.Value), expected)\n+ }\n+ binary.Unmarshal(attr.Value, usermem.ByteOrder, &inetRoute.OutputInterface)\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | hostinet: fix parsing route netlink message
We wrongly parses output interface as gateway address.
The fix is straightforward.
Fixes #638
Signed-off-by: Jianfeng Tan <[email protected]>
Change-Id: Ia4bab31f3c238b0278ea57ab22590fad00eaf061
COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/684 from tanjianfeng:fix-638 b940e810367ad1273519bfa594f4371bdd293e83
PiperOrigin-RevId: 264211336 |
259,975 | 19.08.2019 14:06:22 | 25,200 | 67d7864f839037c5188c2a9e7ec5e7b11a7672a2 | Document RWF_HIPRI not implemented for preadv2/pwritev2.
Document limitation of no reasonable implementation for RWF_HIPRI
flag (High Priority Read/Write for block-based file systems). | [
{
"change_type": "MODIFY",
"old_path": "pkg/abi/linux/file.go",
"new_path": "pkg/abi/linux/file.go",
"diff": "@@ -178,6 +178,8 @@ const (\n// Values for preadv2/pwritev2.\nconst (\n+ // Note: gVisor does not implement the RWF_HIPRI feature, but the flag is\n+ // accepted as a valid flag argument for preadv2/pwritev2.\nRWF_HIPRI = 0x00000001\nRWF_DSYNC = 0x00000002\nRWF_SYNC = 0x00000004\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_read.go",
"new_path": "pkg/sentry/syscalls/linux/sys_read.go",
"diff": "@@ -191,7 +191,6 @@ func Preadv(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\n}\n// Preadv2 implements linux syscall preadv2(2).\n-// TODO(b/120162627): Implement RWF_HIPRI functionality.\nfunc Preadv2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n// While the syscall is\n// preadv2(int fd, struct iovec* iov, int iov_cnt, off_t offset, int flags)\n@@ -228,6 +227,8 @@ func Preadv2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\n// Check flags field.\n+ // Note: gVisor does not implement the RWF_HIPRI feature, but the flag is\n+ // accepted as a valid flag argument for preadv2.\nif flags&^linux.RWF_VALID != 0 {\nreturn 0, nil, syserror.EOPNOTSUPP\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_write.go",
"new_path": "pkg/sentry/syscalls/linux/sys_write.go",
"diff": "@@ -191,7 +191,6 @@ func Pwritev(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysca\n}\n// Pwritev2 implements linux syscall pwritev2(2).\n-// TODO(b/120162627): Implement RWF_HIPRI functionality.\n// TODO(b/120161091): Implement O_SYNC and D_SYNC functionality.\nfunc Pwritev2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n// While the syscall is\n@@ -227,6 +226,8 @@ func Pwritev2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, syserror.ESPIPE\n}\n+ // Note: gVisor does not implement the RWF_HIPRI feature, but the flag is\n+ // accepted as a valid flag argument for pwritev2.\nif flags&^linux.RWF_VALID != 0 {\nreturn uintptr(flags), nil, syserror.EOPNOTSUPP\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Document RWF_HIPRI not implemented for preadv2/pwritev2.
Document limitation of no reasonable implementation for RWF_HIPRI
flag (High Priority Read/Write for block-based file systems).
PiperOrigin-RevId: 264237589 |
259,975 | 20.08.2019 15:05:17 | 25,200 | 3d0715b3f8e7864104e9cbb29b16e6a6b7568d63 | Fix flaky futex test.
The test is long running (175128 ms or so) which causes timeouts.
The test simply makes sure that private futexes can acquire
locks concurrently. Dropping current threads and increasing the
number of locks each thread tests the same concurrency concerns
but drops execution time to ~1411 ms. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/futex.cc",
"new_path": "test/syscalls/linux/futex.cc",
"diff": "@@ -689,10 +689,10 @@ TEST_P(PrivateAndSharedFutexTest, PITryLockConcurrency_NoRandomSave) {\nstd::atomic<int> a = ATOMIC_VAR_INIT(0);\nconst bool is_priv = IsPrivate();\n- std::unique_ptr<ScopedThread> threads[100];\n+ std::unique_ptr<ScopedThread> threads[10];\nfor (size_t i = 0; i < ABSL_ARRAYSIZE(threads); ++i) {\nthreads[i] = absl::make_unique<ScopedThread>([is_priv, &a] {\n- for (size_t j = 0; j < 10;) {\n+ for (size_t j = 0; j < 100;) {\nif (futex_trylock_pi(is_priv, &a) >= 0) {\n++j;\nEXPECT_EQ(a.load() & FUTEX_TID_MASK, gettid());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix flaky futex test.
The test is long running (175128 ms or so) which causes timeouts.
The test simply makes sure that private futexes can acquire
locks concurrently. Dropping current threads and increasing the
number of locks each thread tests the same concurrency concerns
but drops execution time to ~1411 ms.
PiperOrigin-RevId: 264476144 |
259,891 | 20.08.2019 16:34:37 | 25,200 | 6c3a242143dd234e7ef5979a41dfe648cea23d84 | Add tests for raw AF_PACKET sockets. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -255,6 +255,8 @@ syscall_test(\ntest = \"//test/syscalls/linux:open_test\",\n)\n+syscall_test(test = \"//test/syscalls/linux:packet_socket_raw_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:packet_socket_test\")\nsyscall_test(test = \"//test/syscalls/linux:partial_bad_buffer_test\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1226,6 +1226,24 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"packet_socket_raw_test\",\n+ testonly = 1,\n+ srcs = [\"packet_socket_raw.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \":socket_test_util\",\n+ \":unix_domain_socket_test_util\",\n+ \"//test/util:capability_util\",\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_absl//absl/base:core_headers\",\n+ \"@com_google_absl//absl/base:endian\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\ncc_binary(\nname = \"packet_socket_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <arpa/inet.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 <netinet/in.h>\n+#include <netinet/ip.h>\n+#include <netinet/udp.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+\n+#include \"gtest/gtest.h\"\n+#include \"absl/base/internal/endian.h\"\n+#include \"test/syscalls/linux/socket_test_util.h\"\n+#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n+#include \"test/util/capability_util.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/test_util.h\"\n+\n+// Some of these tests involve sending packets via AF_PACKET sockets and the\n+// loopback interface. Because AF_PACKET circumvents so much of the networking\n+// stack, Linux sees these packets as \"martian\", i.e. they claim to be to/from\n+// localhost but don't have the usual associated data. Thus Linux drops them by\n+// default. You can see where this happens by following the code at:\n+//\n+// - net/ipv4/ip_input.c:ip_rcv_finish, which calls\n+// - net/ipv4/route.c:ip_route_input_noref, which calls\n+// - net/ipv4/route.c:ip_route_input_slow, which finds and drops martian\n+// packets.\n+//\n+// To tell Linux not to drop these packets, you need to tell it to accept our\n+// funny packets (which are completely valid and correct, but lack associated\n+// in-kernel data because we use AF_PACKET):\n+//\n+// echo 1 >> /proc/sys/net/ipv4/conf/lo/accept_local\n+// echo 1 >> /proc/sys/net/ipv4/conf/lo/route_localnet\n+//\n+// These tests require CAP_NET_RAW to run.\n+\n+// TODO(gvisor.dev/issue/173): gVisor support.\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+constexpr char kMessage[] = \"soweoneul malhaebwa\";\n+constexpr in_port_t kPort = 0x409c; // htons(40000)\n+\n+// Send kMessage via sock to loopback\n+void SendUDPMessage(int sock) {\n+ struct sockaddr_in dest = {};\n+ dest.sin_port = kPort;\n+ dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ dest.sin_family = AF_INET;\n+ EXPECT_THAT(sendto(sock, kMessage, sizeof(kMessage), 0,\n+ reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),\n+ SyscallSucceedsWithValue(sizeof(kMessage)));\n+}\n+\n+//\n+// Raw tests. Packets sent with raw AF_PACKET sockets always include link layer\n+// headers.\n+//\n+\n+// Tests for \"raw\" (SOCK_RAW) packet(7) sockets.\n+class RawPacketTest : public ::testing::TestWithParam<int> {\n+ protected:\n+ // Creates a socket to be used in tests.\n+ void SetUp() override;\n+\n+ // Closes the socket created by SetUp().\n+ void TearDown() override;\n+\n+ // Gets the device index of the loopback device.\n+ int GetLoopbackIndex();\n+\n+ // The socket used for both reading and writing.\n+ int socket_;\n+};\n+\n+void RawPacketTest::SetUp() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ if (!IsRunningOnGvisor()) {\n+ FileDescriptor acceptLocal = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(\"/proc/sys/net/ipv4/conf/lo/accept_local\", O_RDONLY));\n+ FileDescriptor routeLocalnet = ASSERT_NO_ERRNO_AND_VALUE(\n+ Open(\"/proc/sys/net/ipv4/conf/lo/route_localnet\", O_RDONLY));\n+ char enabled;\n+ ASSERT_THAT(read(acceptLocal.get(), &enabled, 1),\n+ SyscallSucceedsWithValue(1));\n+ ASSERT_EQ(enabled, '1');\n+ ASSERT_THAT(read(routeLocalnet.get(), &enabled, 1),\n+ SyscallSucceedsWithValue(1));\n+ ASSERT_EQ(enabled, '1');\n+ }\n+\n+ ASSERT_THAT(socket_ = socket(AF_PACKET, SOCK_RAW, htons(GetParam())),\n+ SyscallSucceeds());\n+}\n+\n+void RawPacketTest::TearDown() {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ EXPECT_THAT(close(socket_), SyscallSucceeds());\n+}\n+\n+int RawPacketTest::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+}\n+\n+// Receive via a packet socket.\n+TEST_P(RawPacketTest, Receive) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Let's use a simple IP payload: a UDP datagram.\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n+ SendUDPMessage(udp_sock.get());\n+\n+ // Wait for the socket to become readable.\n+ struct pollfd pfd = {};\n+ pfd.fd = socket_;\n+ pfd.events = POLLIN;\n+ EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 2000), SyscallSucceedsWithValue(1));\n+\n+ // Read and verify the data.\n+ constexpr size_t packet_size = sizeof(struct ethhdr) + sizeof(struct iphdr) +\n+ sizeof(struct udphdr) + sizeof(kMessage);\n+ char buf[64];\n+ struct sockaddr_ll src = {};\n+ socklen_t src_len = sizeof(src);\n+ ASSERT_THAT(recvfrom(socket_, buf, sizeof(buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&src), &src_len),\n+ SyscallSucceedsWithValue(packet_size));\n+ // sizeof(src) is the size of a struct sockaddr_ll. sockaddr_ll ends with an 8\n+ // byte physical address field, but ethernet (MAC) addresses only use 6 bytes.\n+ // Thus src_len should get modified to be 2 less than the size of sockaddr_ll.\n+ ASSERT_EQ(src_len, sizeof(src) - 2);\n+\n+ // Verify the source address.\n+ EXPECT_EQ(src.sll_family, AF_PACKET);\n+ EXPECT_EQ(src.sll_protocol, htons(ETH_P_IP));\n+ EXPECT_EQ(src.sll_ifindex, GetLoopbackIndex());\n+ EXPECT_EQ(src.sll_hatype, ARPHRD_LOOPBACK);\n+ EXPECT_EQ(src.sll_halen, ETH_ALEN);\n+ // This came from the loopback device, so the address is all 0s.\n+ for (int i = 0; i < src.sll_halen; i++) {\n+ EXPECT_EQ(src.sll_addr[i], 0);\n+ }\n+\n+ // Verify the ethernet header. We memcpy to deal with pointer alignment.\n+ struct ethhdr eth = {};\n+ memcpy(ð, buf, sizeof(eth));\n+ // The destination and source address should be 0, for loopback.\n+ for (int i = 0; i < ETH_ALEN; i++) {\n+ EXPECT_EQ(eth.h_dest[i], 0);\n+ EXPECT_EQ(eth.h_source[i], 0);\n+ }\n+ EXPECT_EQ(eth.h_proto, htons(ETH_P_IP));\n+\n+ // Verify the IP header. We memcpy to deal with pointer aligment.\n+ struct iphdr ip = {};\n+ memcpy(&ip, buf + sizeof(ethhdr), sizeof(ip));\n+ EXPECT_EQ(ip.ihl, 5);\n+ EXPECT_EQ(ip.version, 4);\n+ EXPECT_EQ(ip.tot_len, htons(packet_size - sizeof(eth)));\n+ EXPECT_EQ(ip.protocol, IPPROTO_UDP);\n+ EXPECT_EQ(ip.daddr, htonl(INADDR_LOOPBACK));\n+ EXPECT_EQ(ip.saddr, htonl(INADDR_LOOPBACK));\n+\n+ // Verify the UDP header. We memcpy to deal with pointer aligment.\n+ struct udphdr udp = {};\n+ memcpy(&udp, buf + sizeof(eth) + sizeof(iphdr), sizeof(udp));\n+ EXPECT_EQ(udp.dest, kPort);\n+ EXPECT_EQ(udp.len, htons(sizeof(udphdr) + sizeof(kMessage)));\n+\n+ // Verify the payload.\n+ char* payload = reinterpret_cast<char*>(buf + sizeof(eth) + sizeof(iphdr) +\n+ sizeof(udphdr));\n+ EXPECT_EQ(strncmp(payload, kMessage, sizeof(kMessage)), 0);\n+}\n+\n+// Send via a packet socket.\n+TEST_P(RawPacketTest, Send) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ SKIP_IF(IsRunningOnGvisor());\n+\n+ // Let's send a UDP packet and receive it using a regular UDP socket.\n+ FileDescriptor udp_sock =\n+ ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n+ struct sockaddr_in bind_addr = {};\n+ bind_addr.sin_family = AF_INET;\n+ bind_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);\n+ bind_addr.sin_port = kPort;\n+ ASSERT_THAT(\n+ bind(udp_sock.get(), reinterpret_cast<struct sockaddr*>(&bind_addr),\n+ sizeof(bind_addr)),\n+ SyscallSucceeds());\n+\n+ // Set up the destination physical address.\n+ struct sockaddr_ll dest = {};\n+ dest.sll_family = AF_PACKET;\n+ dest.sll_halen = ETH_ALEN;\n+ dest.sll_ifindex = GetLoopbackIndex();\n+ dest.sll_protocol = htons(ETH_P_IP);\n+ // We're sending to the loopback device, so the address is all 0s.\n+ memset(dest.sll_addr, 0x00, ETH_ALEN);\n+\n+ // Set up the ethernet header. The kernel takes care of the footer.\n+ // We're sending to and from hardware address 0 (loopback).\n+ struct ethhdr eth = {};\n+ eth.h_proto = htons(ETH_P_IP);\n+\n+ // Set up the IP header.\n+ struct iphdr iphdr = {};\n+ iphdr.ihl = 5;\n+ iphdr.version = 4;\n+ iphdr.tos = 0;\n+ iphdr.tot_len =\n+ htons(sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage));\n+ // Get a pseudo-random ID. If we clash with an in-use ID the test will fail,\n+ // but we have no way of getting an ID we know to be good.\n+ srand(*reinterpret_cast<unsigned int*>(&iphdr));\n+ iphdr.id = rand();\n+ // Linux sets this bit (\"do not fragment\") for small packets.\n+ iphdr.frag_off = 1 << 6;\n+ iphdr.ttl = 64;\n+ iphdr.protocol = IPPROTO_UDP;\n+ iphdr.daddr = htonl(INADDR_LOOPBACK);\n+ iphdr.saddr = htonl(INADDR_LOOPBACK);\n+ iphdr.check = IPChecksum(iphdr);\n+\n+ // Set up the UDP header.\n+ struct udphdr udphdr = {};\n+ udphdr.source = kPort;\n+ udphdr.dest = kPort;\n+ udphdr.len = htons(sizeof(udphdr) + sizeof(kMessage));\n+ udphdr.check = UDPChecksum(iphdr, udphdr, kMessage, sizeof(kMessage));\n+\n+ // Copy both headers and the payload into our packet buffer.\n+ char\n+ send_buf[sizeof(eth) + sizeof(iphdr) + sizeof(udphdr) + sizeof(kMessage)];\n+ memcpy(send_buf, ð, sizeof(eth));\n+ memcpy(send_buf + sizeof(ethhdr), &iphdr, sizeof(iphdr));\n+ memcpy(send_buf + sizeof(ethhdr) + sizeof(iphdr), &udphdr, sizeof(udphdr));\n+ memcpy(send_buf + sizeof(ethhdr) + sizeof(iphdr) + sizeof(udphdr), kMessage,\n+ sizeof(kMessage));\n+\n+ // Send it.\n+ ASSERT_THAT(sendto(socket_, send_buf, sizeof(send_buf), 0,\n+ reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),\n+ SyscallSucceedsWithValue(sizeof(send_buf)));\n+\n+ // Wait for the packet to become available on both sockets.\n+ struct pollfd pfd = {};\n+ pfd.fd = udp_sock.get();\n+ pfd.events = POLLIN;\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));\n+ pfd.fd = socket_;\n+ pfd.events = POLLIN;\n+ ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));\n+\n+ // Receive on the packet socket.\n+ char recv_buf[sizeof(send_buf)];\n+ ASSERT_THAT(recv(socket_, recv_buf, sizeof(recv_buf), 0),\n+ SyscallSucceedsWithValue(sizeof(recv_buf)));\n+ ASSERT_EQ(memcmp(recv_buf, send_buf, sizeof(send_buf)), 0);\n+\n+ // Receive on the UDP socket.\n+ struct sockaddr_in src;\n+ socklen_t src_len = sizeof(src);\n+ ASSERT_THAT(recvfrom(udp_sock.get(), recv_buf, sizeof(recv_buf), MSG_DONTWAIT,\n+ reinterpret_cast<struct sockaddr*>(&src), &src_len),\n+ SyscallSucceedsWithValue(sizeof(kMessage)));\n+ // Check src and payload.\n+ EXPECT_EQ(strncmp(recv_buf, kMessage, sizeof(kMessage)), 0);\n+ EXPECT_EQ(src.sin_family, AF_INET);\n+ EXPECT_EQ(src.sin_port, kPort);\n+ EXPECT_EQ(src.sin_addr.s_addr, htonl(INADDR_LOOPBACK));\n+}\n+\n+INSTANTIATE_TEST_SUITE_P(AllInetTests, RawPacketTest,\n+ ::testing::Values(ETH_P_IP /*, ETH_P_ALL*/));\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add tests for raw AF_PACKET sockets.
PiperOrigin-RevId: 264494359 |
259,853 | 20.08.2019 19:09:45 | 25,200 | 7609da6cb937f1152206dc0fe7294982ea7160e1 | test: reset a signal handler before closing a signal channel
goroutine 5 [running]:
os/signal.process(0x10e21c0, 0xc00050c280)
third_party/go/gc/src/os/signal/signal.go:227 +0x164
os/signal.loop()
third_party/go/gc/src/os/signal/signal_unix.go:23 +0x3e
created by os/signal.init.0
third_party/go/gc/src/os/signal/signal_unix.go:29 +0x41 | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/syscall_test_runner.go",
"new_path": "test/syscalls/syscall_test_runner.go",
"diff": "@@ -280,6 +280,7 @@ func runTestCaseRunsc(testBin string, tc gtest.TestCase, t *testing.T) {\nif err = cmd.Run(); err != nil {\nt.Errorf(\"test %q exited with status %v, want 0\", tc.FullName(), err)\n}\n+ signal.Stop(sig)\nclose(sig)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | test: reset a signal handler before closing a signal channel
goroutine 5 [running]:
os/signal.process(0x10e21c0, 0xc00050c280)
third_party/go/gc/src/os/signal/signal.go:227 +0x164
os/signal.loop()
third_party/go/gc/src/os/signal/signal_unix.go:23 +0x3e
created by os/signal.init.0
third_party/go/gc/src/os/signal/signal_unix.go:29 +0x41
PiperOrigin-RevId: 264518530 |
260,006 | 20.08.2019 23:27:29 | 25,200 | 7e79ca02251d0e085e2f1fc05b3811291e85fc0b | Add tcpip.Route.String and tcpip.AddressMask.Prefix | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -31,6 +31,7 @@ package tcpip\nimport (\n\"errors\"\n\"fmt\"\n+ \"math/bits\"\n\"reflect\"\n\"strconv\"\n\"strings\"\n@@ -145,8 +146,17 @@ type Address string\ntype AddressMask string\n// String implements Stringer.\n-func (a AddressMask) String() string {\n- return Address(a).String()\n+func (m AddressMask) String() string {\n+ return Address(m).String()\n+}\n+\n+// Prefix returns the number of bits before the first host bit.\n+func (m AddressMask) Prefix() int {\n+ p := 0\n+ for _, b := range []byte(m) {\n+ p += bits.LeadingZeros8(^b)\n+ }\n+ return p\n}\n// Subnet is a subnet defined by its address and mask.\n@@ -209,14 +219,7 @@ func (s *Subnet) Bits() (ones int, zeros int) {\n// Prefix returns the number of bits before the first host bit.\nfunc (s *Subnet) Prefix() int {\n- for i, b := range []byte(s.mask) {\n- for j := 7; j >= 0; j-- {\n- if b&(1<<uint(j)) == 0 {\n- return i*8 + 7 - j\n- }\n- }\n- }\n- return len(s.mask) * 8\n+ return s.mask.Prefix()\n}\n// Mask returns the subnet mask.\n@@ -590,6 +593,17 @@ type Route struct {\nNIC NICID\n}\n+// String implements the fmt.Stringer interface.\n+func (r *Route) String() string {\n+ var out strings.Builder\n+ fmt.Fprintf(&out, \"%s/%d\", r.Destination, r.Mask.Prefix())\n+ if len(r.Gateway) > 0 {\n+ fmt.Fprintf(&out, \" via %s\", r.Gateway)\n+ }\n+ fmt.Fprintf(&out, \" nic %d\", r.NIC)\n+ return out.String()\n+}\n+\n// Match determines if r is viable for the given destination address.\nfunc (r *Route) Match(addr Address) bool {\nif len(addr) != len(r.Destination) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add tcpip.Route.String and tcpip.AddressMask.Prefix
PiperOrigin-RevId: 264544163 |
259,853 | 21.08.2019 19:05:56 | 25,200 | 5fd63d1c7fc8ea8d0aff30abc6403aa4491b6f81 | tests: retry connect if it fails with EINTR
test/syscalls/linux/proc_net_tcp.cc:252: Failure
Value of: connect(client->get(), &addr, addrlen)
Expected: not -1 (success)
Actual: -1 (of type int), with errno PosixError(errno=4 Interrupted system call) | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net_tcp.cc",
"new_path": "test/syscalls/linux/proc_net_tcp.cc",
"diff": "@@ -249,7 +249,8 @@ TEST(ProcNetTCP, State) {\nstd::unique_ptr<FileDescriptor> client =\nASSERT_NO_ERRNO_AND_VALUE(IPv4TCPUnboundSocket(0).Create());\n- ASSERT_THAT(connect(client->get(), &addr, addrlen), SyscallSucceeds());\n+ ASSERT_THAT(RetryEINTR(connect)(client->get(), &addr, addrlen),\n+ SyscallSucceeds());\nentries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCPEntries());\nASSERT_TRUE(FindByLocalAddr(entries, &listen_entry, &addr));\nEXPECT_EQ(listen_entry.state, TCP_LISTEN);\n"
}
] | Go | Apache License 2.0 | google/gvisor | tests: retry connect if it fails with EINTR
test/syscalls/linux/proc_net_tcp.cc:252: Failure
Value of: connect(client->get(), &addr, addrlen)
Expected: not -1 (success)
Actual: -1 (of type int), with errno PosixError(errno=4 Interrupted system call)
PiperOrigin-RevId: 264743815 |
259,997 | 22.08.2019 22:52:43 | -36,000 | 7672eaae25eebad650e71ba790e1585736866ccc | Add log prefix for better clarity | [
{
"change_type": "MODIFY",
"old_path": "pkg/refs/refcounter.go",
"new_path": "pkg/refs/refcounter.go",
"diff": "@@ -237,9 +237,9 @@ func (l LeakMode) String() string {\ncase NoLeakChecking:\nreturn \"disabled\"\ncase LeaksLogWarning:\n- return \"warning\"\n+ return \"log-names\"\ncase LeaksLogTraces:\n- return \"traces\"\n+ return \"log-traces\"\ndefault:\npanic(fmt.Sprintf(\"Invalid leakmode: %d\", l))\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -118,9 +118,9 @@ func MakeRefsLeakMode(s string) (refs.LeakMode, error) {\nswitch strings.ToLower(s) {\ncase \"disabled\":\nreturn refs.NoLeakChecking, nil\n- case \"warning\":\n+ case \"log-names\":\nreturn refs.LeaksLogWarning, nil\n- case \"traces\":\n+ case \"log-traces\":\nreturn refs.LeaksLogTraces, nil\ndefault:\nreturn 0, fmt.Errorf(\"invalid refs leakmode %q\", s)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -73,7 +73,7 @@ var (\nnetRaw = flag.Bool(\"net-raw\", false, \"enable raw sockets. When false, raw sockets are disabled by removing CAP_NET_RAW from containers (`runsc exec` will still be able to utilize raw sockets). Raw sockets allow malicious containers to craft packets and potentially attack the network.\")\nnumNetworkChannels = flag.Int(\"num-network-channels\", 1, \"number of underlying channels(FDs) to use for network link endpoints.\")\nrootless = flag.Bool(\"rootless\", false, \"it allows the sandbox to be started with a user that is not root. Sandbox and Gofer processes may run with same privileges as current user.\")\n- referenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), warning, traces.\")\n+ referenceLeakMode = flag.String(\"ref-leak-mode\", \"disabled\", \"sets reference leak check mode: disabled (default), log-names, log-traces.\")\n// Test flags, not to be used outside tests, ever.\ntestOnlyAllowRunAsCurrentUserWithoutChroot = flag.Bool(\"TESTONLY-unsafe-nonroot\", false, \"TEST ONLY; do not ever use! This skips many security measures that isolate the host from the sandbox.\")\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add log prefix for better clarity |
259,883 | 19.08.2019 23:13:03 | -28,800 | 2c3e2ed2bf4aa61bf317545fe428ff3adac95f92 | unix: return ECONNRESET if peer closed with data not read
For SOCK_STREAM type unix socket, we shall return ECONNRESET if peer is
closed with data not read.
We explictly set a flag when closing one end, to differentiate from
just shutdown (where zero shall be returned).
Fixes: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/socket.go",
"new_path": "pkg/sentry/fs/host/socket.go",
"diff": "@@ -385,3 +385,6 @@ func (c *ConnectedEndpoint) RecvMaxQueueSize() int64 {\nfunc (c *ConnectedEndpoint) Release() {\nc.ref.DecRefWithDestructor(c.close)\n}\n+\n+// CloseUnread implements transport.ConnectedEndpoint.CloseUnread.\n+func (c *ConnectedEndpoint) CloseUnread() {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"new_path": "pkg/sentry/socket/unix/transport/connectioned.go",
"diff": "@@ -220,6 +220,11 @@ func (e *connectionedEndpoint) Close() {\ncase e.Connected():\ne.connected.CloseSend()\ne.receiver.CloseRecv()\n+ // Still have unread data? If yes, we set this into the write\n+ // end so that the peer can get ECONNRESET) when it does read.\n+ if e.receiver.RecvQueuedSize() > 0 {\n+ e.connected.CloseUnread()\n+ }\nc = e.connected\nr = e.receiver\ne.connected = nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/queue.go",
"new_path": "pkg/sentry/socket/unix/transport/queue.go",
"diff": "@@ -33,6 +33,7 @@ type queue struct {\nmu sync.Mutex `state:\"nosave\"`\nclosed bool\n+ unread bool\nused int64\nlimit int64\ndataList messageList\n@@ -160,7 +161,9 @@ func (q *queue) Dequeue() (e *message, notify bool, err *syserr.Error) {\nif q.dataList.Front() == nil {\nerr := syserr.ErrWouldBlock\nif q.closed {\n- err = syserr.ErrClosedForReceive\n+ if err = syserr.ErrClosedForReceive; q.unread {\n+ err = syserr.ErrConnectionReset\n+ }\n}\nq.mu.Unlock()\n@@ -188,7 +191,9 @@ func (q *queue) Peek() (*message, *syserr.Error) {\nif q.dataList.Front() == nil {\nerr := syserr.ErrWouldBlock\nif q.closed {\n- err = syserr.ErrClosedForReceive\n+ if err = syserr.ErrClosedForReceive; q.unread {\n+ err = syserr.ErrConnectionReset\n+ }\n}\nreturn nil, err\n}\n@@ -208,3 +213,11 @@ func (q *queue) QueuedSize() int64 {\nfunc (q *queue) MaxQueueSize() int64 {\nreturn q.limit\n}\n+\n+// CloseUnread sets flag to indicate that the peer is closed (not shutdown)\n+// with unread data. So if read on this queue shall return ECONNRESET error.\n+func (q *queue) CloseUnread() {\n+ q.mu.Lock()\n+ defer q.mu.Unlock()\n+ q.unread = true\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/unix/transport/unix.go",
"new_path": "pkg/sentry/socket/unix/transport/unix.go",
"diff": "@@ -604,6 +604,10 @@ type ConnectedEndpoint interface {\n// Release releases any resources owned by the ConnectedEndpoint. It should\n// be called before droping all references to a ConnectedEndpoint.\nRelease()\n+\n+ // CloseUnread sets the fact that this end is closed with unread data to\n+ // the peer socket.\n+ CloseUnread()\n}\n// +stateify savable\n@@ -707,6 +711,11 @@ func (e *connectedEndpoint) Release() {\ne.writeQueue.DecRef()\n}\n+// CloseUnread implements ConnectedEndpoint.CloseUnread.\n+func (e *connectedEndpoint) CloseUnread() {\n+ e.writeQueue.CloseUnread()\n+}\n+\n// baseEndpoint is an embeddable unix endpoint base used in both the connected and connectionless\n// unix domain socket Endpoint implementations.\n//\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_unix_stream.cc",
"new_path": "test/syscalls/linux/socket_unix_stream.cc",
"diff": "#include <stdio.h>\n#include <sys/un.h>\n+#include <poll.h>\n#include \"gtest/gtest.h\"\n#include \"gtest/gtest.h\"\n#include \"test/syscalls/linux/socket_test_util.h\"\n@@ -70,6 +71,25 @@ TEST_P(StreamUnixSocketPairTest, RecvmsgOneSideClosed) {\nSyscallSucceedsWithValue(0));\n}\n+TEST_P(StreamUnixSocketPairTest, ReadOneSideClosedWithUnreadData) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char buf[10] = {};\n+ ASSERT_THAT(RetryEINTR(write)(sockets->second_fd(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(sizeof(buf)));\n+\n+ ASSERT_THAT(shutdown(sockets->first_fd(), SHUT_RDWR),\n+ SyscallSucceeds());\n+\n+ ASSERT_THAT(RetryEINTR(read)(sockets->second_fd(), buf, sizeof(buf)),\n+ SyscallSucceedsWithValue(0));\n+\n+ ASSERT_THAT(close(sockets->release_first_fd()), SyscallSucceeds());\n+\n+ ASSERT_THAT(RetryEINTR(read)(sockets->second_fd(), buf, sizeof(buf)),\n+ SyscallFailsWithErrno(ECONNRESET));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(\nAllUnixDomainSockets, StreamUnixSocketPairTest,\n::testing::ValuesIn(IncludeReversals(VecCat<SocketPairKind>(\n"
}
] | Go | Apache License 2.0 | google/gvisor | unix: return ECONNRESET if peer closed with data not read
For SOCK_STREAM type unix socket, we shall return ECONNRESET if peer is
closed with data not read.
We explictly set a flag when closing one end, to differentiate from
just shutdown (where zero shall be returned).
Fixes: #735
Signed-off-by: Jianfeng Tan <[email protected]> |
259,881 | 22.08.2019 13:19:47 | 25,200 | 52e674b44d77b0a227d2b74dd75ae29c036fb01b | Remove ASSERT from fork child
The gunit macros are not safe to use in the child. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty_root.cc",
"new_path": "test/syscalls/linux/pty_root.cc",
"diff": "@@ -50,7 +50,7 @@ TEST(JobControlRootTest, StealTTY) {\n// of 1.\npid_t child = fork();\nif (!child) {\n- ASSERT_THAT(setsid(), SyscallSucceeds());\n+ TEST_PCHECK(setsid() >= 0);\n// We shouldn't be able to steal the terminal with the wrong arg value.\nTEST_PCHECK(ioctl(slave.get(), TIOCSCTTY, 0));\n// We should be able to steal it here.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove ASSERT from fork child
The gunit macros are not safe to use in the child.
PiperOrigin-RevId: 264904348 |
259,992 | 22.08.2019 13:25:29 | 25,200 | 0034aaa82ac00a75866e77a3570febdec8d291d1 | Send sandbox log to test log
This used to be the case, but when --alsologtostderr
was added, it stopped logging. | [
{
"change_type": "MODIFY",
"old_path": "runsc/test/testutil/testutil.go",
"new_path": "runsc/test/testutil/testutil.go",
"diff": "@@ -129,6 +129,8 @@ func TestConfig() *boot.Config {\nreturn &boot.Config{\nDebug: true,\nLogFormat: \"text\",\n+ DebugLogFormat: \"text\",\n+ AlsoLogToStderr: true,\nLogPackets: true,\nNetwork: boot.NetworkNone,\nStrace: true,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Send sandbox log to test log
This used to be the case, but when --alsologtostderr
was added, it stopped logging.
PiperOrigin-RevId: 264905640 |
259,858 | 22.08.2019 14:33:16 | 25,200 | 761e4bf2fe520dae1120341b09c26be1577a2adb | Ensure yield-equivalent with an already-expired timeout. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/kernel/task_block.go",
"new_path": "pkg/sentry/kernel/task_block.go",
"diff": "package kernel\nimport (\n+ \"runtime\"\n\"time\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n@@ -121,6 +122,17 @@ func (t *Task) block(C <-chan struct{}, timerChan <-chan struct{}) error {\n// Deactive our address space, we don't need it.\ninterrupt := t.SleepStart()\n+ // If the request is not completed, but the timer has already expired,\n+ // then ensure that we run through a scheduler cycle. This is because\n+ // we may see applications relying on timer slack to yield the thread.\n+ // For example, they may attempt to sleep for some number of nanoseconds,\n+ // and expect that this will actually yield the CPU and sleep for at\n+ // least microseconds, e.g.:\n+ // https://github.com/LMAX-Exchange/disruptor/commit/6ca210f2bcd23f703c479804d583718e16f43c07\n+ if len(timerChan) > 0 {\n+ runtime.Gosched()\n+ }\n+\nselect {\ncase <-C:\nt.SleepFinish(true)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure yield-equivalent with an already-expired timeout.
PiperOrigin-RevId: 264920977 |
259,992 | 22.08.2019 18:25:57 | 25,200 | f225fdbbe77c2017225517adcf67df70fcf8e36e | Log message sent before logging is setup
Moved log message to after the log options have
been read and log setup. | [
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -117,13 +117,6 @@ func main() {\n// All subcommands must be registered before flag parsing.\nflag.Parse()\n- if *testOnlyAllowRunAsCurrentUserWithoutChroot {\n- // SIGTERM is sent to all processes if a test exceeds its\n- // timeout and this case is handled by syscall_test_runner.\n- log.Warningf(\"Block the TERM signal. This is only safe in tests!\")\n- signal.Ignore(syscall.SIGTERM)\n- }\n-\n// Are we showing the version?\nif *showVersion {\n// The format here is the same as runc.\n@@ -265,6 +258,13 @@ func main() {\nlog.Infof(\"\\t\\tStrace: %t, max size: %d, syscalls: %s\", conf.Strace, conf.StraceLogSize, conf.StraceSyscalls)\nlog.Infof(\"***************************\")\n+ if *testOnlyAllowRunAsCurrentUserWithoutChroot {\n+ // SIGTERM is sent to all processes if a test exceeds its\n+ // timeout and this case is handled by syscall_test_runner.\n+ log.Warningf(\"Block the TERM signal. This is only safe in tests!\")\n+ signal.Ignore(syscall.SIGTERM)\n+ }\n+\n// Call the subcommand and pass in the configuration.\nvar ws syscall.WaitStatus\nsubcmdCode := subcommands.Execute(context.Background(), conf, &ws)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Log message sent before logging is setup
Moved log message to after the log options have
been read and log setup.
PiperOrigin-RevId: 264964171 |
259,975 | 23.08.2019 16:53:00 | 25,200 | a5d0115943c591173ea322cd1d721c89fc9c442d | Second try at flaky futex test.
The flake had the call to futex_unlock_pi() returning EINVAL with the
FUTEX_OWNER_DIED set. In this case, userspace has to clean up stale
state. So instead of calling FUTEX_UNLOCK_PI outright, we'll use the
advised atomic compare_exchange as advised in the man page. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/futex.cc",
"new_path": "test/syscalls/linux/futex.cc",
"diff": "@@ -125,6 +125,10 @@ int futex_lock_pi(bool priv, std::atomic<int>* uaddr) {\nif (priv) {\nop |= FUTEX_PRIVATE_FLAG;\n}\n+ int zero = 0;\n+ if (uaddr->compare_exchange_strong(zero, gettid())) {\n+ return 0;\n+ }\nreturn RetryEINTR(syscall)(SYS_futex, uaddr, op, nullptr, nullptr);\n}\n@@ -133,6 +137,10 @@ int futex_trylock_pi(bool priv, std::atomic<int>* uaddr) {\nif (priv) {\nop |= FUTEX_PRIVATE_FLAG;\n}\n+ int zero = 0;\n+ if (uaddr->compare_exchange_strong(zero, gettid())) {\n+ return 0;\n+ }\nreturn RetryEINTR(syscall)(SYS_futex, uaddr, op, nullptr, nullptr);\n}\n@@ -141,6 +149,10 @@ int futex_unlock_pi(bool priv, std::atomic<int>* uaddr) {\nif (priv) {\nop |= FUTEX_PRIVATE_FLAG;\n}\n+ int tid = gettid();\n+ if (uaddr->compare_exchange_strong(tid, 0)) {\n+ return 0;\n+ }\nreturn RetryEINTR(syscall)(SYS_futex, uaddr, op, nullptr, nullptr);\n}\n@@ -692,8 +704,8 @@ TEST_P(PrivateAndSharedFutexTest, PITryLockConcurrency_NoRandomSave) {\nstd::unique_ptr<ScopedThread> threads[10];\nfor (size_t i = 0; i < ABSL_ARRAYSIZE(threads); ++i) {\nthreads[i] = absl::make_unique<ScopedThread>([is_priv, &a] {\n- for (size_t j = 0; j < 100;) {\n- if (futex_trylock_pi(is_priv, &a) >= 0) {\n+ for (size_t j = 0; j < 10;) {\n+ if (futex_trylock_pi(is_priv, &a) == 0) {\n++j;\nEXPECT_EQ(a.load() & FUTEX_TID_MASK, gettid());\nSleepSafe(absl::Milliseconds(5));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Second try at flaky futex test.
The flake had the call to futex_unlock_pi() returning EINVAL with the
FUTEX_OWNER_DIED set. In this case, userspace has to clean up stale
state. So instead of calling FUTEX_UNLOCK_PI outright, we'll use the
advised atomic compare_exchange as advised in the man page.
PiperOrigin-RevId: 265163920 |
259,853 | 26.08.2019 09:58:16 | 25,200 | c9c52c024cf20c1c66327171af4287129724326e | fsgofer_test.go: a socket file path can't be longer than UNIX_MAX_PATH (108) | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer_test.go",
"new_path": "runsc/fsgofer/fsgofer_test.go",
"diff": "@@ -635,7 +635,15 @@ func TestAttachInvalidType(t *testing.T) {\nt.Fatalf(\"Mkfifo(%q): %v\", fifo, err)\n}\n- socket := filepath.Join(dir, \"socket\")\n+ dirFile, err := os.Open(dir)\n+ if err != nil {\n+ t.Fatalf(\"Open(%s): %v\", dir, err)\n+ }\n+ defer dirFile.Close()\n+\n+ // Bind a socket via /proc to be sure that a length of a socket path\n+ // is less than UNIX_PATH_MAX.\n+ socket := filepath.Join(fmt.Sprintf(\"/proc/self/fd/%d\", dirFile.Fd()), \"socket\")\nl, err := net.Listen(\"unix\", socket)\nif err != nil {\nt.Fatalf(\"net.Listen(unix, %q): %v\", socket, err)\n"
}
] | Go | Apache License 2.0 | google/gvisor | fsgofer_test.go: a socket file path can't be longer than UNIX_MAX_PATH (108)
PiperOrigin-RevId: 265478578 |
259,923 | 26.08.2019 09:27:07 | -7,200 | 5c82fbe1aac83ce76c628c6ee382c77df8d331ea | Add missing sudo in setup-command | [
{
"change_type": "MODIFY",
"old_path": "content/docs/includes/install_gvisor.md",
"new_path": "content/docs/includes/install_gvisor.md",
"diff": "@@ -21,7 +21,7 @@ a good place to put the `runsc` binary.\nsha512sum -c runsc.sha512\nsudo mv runsc /usr/local/bin\nsudo chown root:root /usr/local/bin/runsc\n- chmod 0755 /usr/local/bin/runsc\n+ sudo chmod 0755 /usr/local/bin/runsc\n)\n```\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add missing sudo in setup-command |
259,985 | 26.08.2019 16:38:04 | 25,200 | 1fdefd41c5410291b50c3f28ca13f423031f1f12 | netstack/tcp: Add LastAck transition.
Add missing state transition to LastAck, which should happen when the
endpoint has already recieved a FIN from the remote side, and is
sending its own FIN. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/transport/tcp/snd.go",
"new_path": "pkg/tcpip/transport/tcp/snd.go",
"diff": "@@ -664,7 +664,14 @@ func (s *sender) maybeSendSegment(seg *segment, limit int, end seqnum.Value) (se\nsegEnd = seg.sequenceNumber.Add(1)\n// Transition to FIN-WAIT1 state since we're initiating an active close.\ns.ep.mu.Lock()\n+ switch s.ep.state {\n+ case StateCloseWait:\n+ // We've already received a FIN and are now sending our own. The\n+ // sender is now awaiting a final ACK for this FIN.\n+ s.ep.state = StateLastAck\n+ default:\ns.ep.state = StateFinWait1\n+ }\ns.ep.mu.Unlock()\n} else {\n// We're sending a non-FIN segment.\n"
}
] | Go | Apache License 2.0 | google/gvisor | netstack/tcp: Add LastAck transition.
Add missing state transition to LastAck, which should happen when the
endpoint has already recieved a FIN from the remote side, and is
sending its own FIN.
PiperOrigin-RevId: 265568314 |
259,858 | 26.08.2019 21:35:10 | 25,200 | b4cdaef4a1d545867d8e34036c5ed3175e55079d | Don't lose test output. | [
{
"change_type": "MODIFY",
"old_path": "tools/run_tests.sh",
"new_path": "tools/run_tests.sh",
"diff": "@@ -176,7 +176,6 @@ run_docker_tests() {\nbazel test \\\n\"${BAZEL_BUILD_FLAGS[@]}\" \\\n--test_env=RUNSC_RUNTIME=\"\" \\\n- --test_output=all \\\n//runsc/test/image:image_test\n# These names are used to exclude tests not supported in certain\n@@ -188,9 +187,7 @@ run_docker_tests() {\nbazel test \\\n\"${BAZEL_BUILD_FLAGS[@]}\" \\\n--test_env=RUNSC_RUNTIME=\"${RUNTIME}\" \\\n- --test_output=all \\\n--nocache_test_results \\\n- --test_output=streamed \\\n//runsc/test/integration:integration_test \\\n//runsc/test/integration:integration_test_hostnet \\\n//runsc/test/integration:integration_test_overlay \\\n@@ -248,8 +245,7 @@ upload_test_artifacts() {\nfi\n}\n-# Finish runs at exit, even in the event of an error, and uploads all test\n-# artifacts.\n+# Finish runs in the event of an error, uploading all artifacts.\nfinish() {\n# Grab the last exit code, we will return it.\nlocal exit_code=${?}\n@@ -294,8 +290,14 @@ main() {\n# Build other flavors too.\nbuild_everything dbg\n+ # We need to upload all the existing test logs and artifacts before shutting\n+ # down and cleaning bazel, otherwise all test information is lost. After this\n+ # point, we don't expect any logs or artifacts.\n+ upload_test_artifacts\n+ trap - EXIT\n+\n+ # Run docker build tests.\nbuild_in_docker\n- # No need to call \"finish\" here, it will happen at exit.\n}\n# Kick it off.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Don't lose test output.
PiperOrigin-RevId: 265606322 |
259,993 | 29.07.2019 14:57:14 | 25,200 | c319b360d134cff66000fd036fce8b3816c296ea | First pass at implementing Unix Domain Socket support. No tests.
This commit adds support for detecting the socket file type, connecting
to a Unix Domain Socket, and providing bidirectional communication
(without file descriptor transfer support). | [
{
"change_type": "MODIFY",
"old_path": "pkg/fd/fd.go",
"new_path": "pkg/fd/fd.go",
"diff": "@@ -22,6 +22,7 @@ import (\n\"runtime\"\n\"sync/atomic\"\n\"syscall\"\n+ \"net\"\n)\n// ReadWriter implements io.ReadWriter, io.ReaderAt, and io.WriterAt for fd. It\n@@ -185,6 +186,21 @@ func OpenAt(dir *FD, path string, flags int, mode uint32) (*FD, error) {\nreturn New(f), nil\n}\n+// OpenUnix TODO: DOC\n+func OpenUnix(path string) (*FD, error) {\n+ addr, _ := net.ResolveUnixAddr(\"unix\", path)\n+ f, err := net.DialUnix(\"unix\", nil, addr); if err != nil {\n+ return nil, fmt.Errorf(\"unable to open socket: %q, err: %v\", path, err)\n+ }\n+ fConnd, err := f.File(); if err != nil {\n+ return nil, fmt.Errorf(\"unable to convert to os.File: %q, err: %v\", path, err)\n+ }\n+ fdConnd, err := NewFromFile(fConnd); if err != nil {\n+ return nil, fmt.Errorf(\"unable to convert os.File to fd.FD: %q, err: %v\", path, err)\n+ }\n+ return fdConnd, nil\n+}\n+\n// Close closes the file descriptor contained in the FD.\n//\n// Close is safe to call multiple times, but will return an error after the\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -26,6 +26,31 @@ import (\n// allowedSyscalls is the set of syscalls executed by the gofer.\nvar allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_ACCEPT: {},\n+ syscall.SYS_SOCKET: []seccomp.Rule{\n+ {\n+ seccomp.AllowValue(syscall.AF_UNIX),\n+ },\n+ },\n+ syscall.SYS_CONNECT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ },\n+ },\n+ syscall.SYS_SETSOCKOPT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ },\n+ },\n+ syscall.SYS_GETSOCKNAME: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ },\n+ },\n+ syscall.SYS_GETPEERNAME: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ },\n+ },\nsyscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n{seccomp.AllowValue(linux.ARCH_GET_FS)},\n{seccomp.AllowValue(linux.ARCH_SET_FS)},\n@@ -83,6 +108,9 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.F_GETFD),\n},\n+ {\n+ seccomp.AllowAny{},\n+ },\n},\nsyscall.SYS_FSTAT: {},\nsyscall.SYS_FSTATFS: {},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -54,6 +54,7 @@ const (\nregular fileType = iota\ndirectory\nsymlink\n+ socket\nunknown\n)\n@@ -66,6 +67,8 @@ func (f fileType) String() string {\nreturn \"directory\"\ncase symlink:\nreturn \"symlink\"\n+ case socket:\n+ return \"socket\"\n}\nreturn \"unknown\"\n}\n@@ -124,30 +127,56 @@ func (a *attachPoint) Attach() (p9.File, error) {\nif err != nil {\nreturn nil, fmt.Errorf(\"stat file %q, err: %v\", a.prefix, err)\n}\n+\n+ // Apply the S_IFMT bitmask so we can detect file type appropriately\n+ fmtStat := stat.Mode & syscall.S_IFMT\n+\n+ switch fmtStat{\n+ case syscall.S_IFSOCK:\n+ // Attempt to open a connection. Bubble up the failures.\n+ f, err := fd.OpenUnix(a.prefix); if err != nil {\n+ return nil, err\n+ }\n+\n+ // Close the connection if the UDS is already attached.\n+ a.attachedMu.Lock()\n+ defer a.attachedMu.Unlock()\n+ if a.attached {\n+ f.Close()\n+ return nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n+ }\n+ a.attached = true\n+\n+ // Return a localFile object to the caller with the UDS FD included.\n+ return newLocalFile(a, f, a.prefix, stat)\n+\n+ default:\n+ // Default to Read/Write permissions.\nmode := syscall.O_RDWR\n- if a.conf.ROMount || (stat.Mode&syscall.S_IFMT) == syscall.S_IFDIR {\n+ // If the configuration is Read Only & the mount point is a directory,\n+ // set the mode to Read Only.\n+ if a.conf.ROMount || fmtStat == syscall.S_IFDIR {\nmode = syscall.O_RDONLY\n}\n- // Open the root directory.\n+ // Open the mount point & capture the FD.\nf, err := fd.Open(a.prefix, openFlags|mode, 0)\nif err != nil {\nreturn nil, fmt.Errorf(\"unable to open file %q, err: %v\", a.prefix, err)\n}\n+ // If the mount point has already been attached, close the FD.\na.attachedMu.Lock()\ndefer a.attachedMu.Unlock()\nif a.attached {\nf.Close()\nreturn nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n}\n+ a.attached = true\n- rv, err := newLocalFile(a, f, a.prefix, stat)\n- if err != nil {\n- return nil, err\n+ // Return a localFile object to the caller with the mount point FD\n+ return newLocalFile(a, f, a.prefix, stat)\n}\n- a.attached = true\n- return rv, nil\n}\n// makeQID returns a unique QID for the given stat buffer.\n@@ -304,6 +333,8 @@ func getSupportedFileType(stat syscall.Stat_t) (fileType, error) {\nft = directory\ncase syscall.S_IFLNK:\nft = symlink\n+ case syscall.S_IFSOCK:\n+ ft = socket\ndefault:\nreturn unknown, syscall.EPERM\n}\n@@ -1026,7 +1057,7 @@ func (l *localFile) Flush() error {\n// Connect implements p9.File.\nfunc (l *localFile) Connect(p9.ConnectFlags) (*fd.FD, error) {\n- return nil, syscall.ECONNREFUSED\n+ return fd.OpenUnix(l.hostPath)\n}\n// Close implements p9.File.\n"
}
] | Go | Apache License 2.0 | google/gvisor | First pass at implementing Unix Domain Socket support. No tests.
This commit adds support for detecting the socket file type, connecting
to a Unix Domain Socket, and providing bidirectional communication
(without file descriptor transfer support). |
259,993 | 30.07.2019 14:58:26 | 25,200 | 07d329d89f25e4649731199c3025f4fa0ed52bdb | Restrict seccomp filters for UDS support.
This commit further restricts the seccomp filters required for Gofer
access ot Unix Domain Sockets (UDS). | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -39,6 +39,8 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_SETSOCKOPT: []seccomp.Rule{\n{\nseccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.SOL_SOCKET),\n+ seccomp.AllowValue(syscall.SO_BROADCAST),\n},\n},\nsyscall.SYS_GETSOCKNAME: []seccomp.Rule{\n@@ -110,6 +112,7 @@ var allowedSyscalls = seccomp.SyscallRules{\n},\n{\nseccomp.AllowAny{},\n+ seccomp.AllowValue(syscall.F_DUPFD_CLOEXEC),\n},\n},\nsyscall.SYS_FSTAT: {},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Restrict seccomp filters for UDS support.
This commit further restricts the seccomp filters required for Gofer
access ot Unix Domain Sockets (UDS). |
259,992 | 27.08.2019 10:46:06 | 25,200 | c39564332bdd5030b9031ed3b1a428464fea670e | Mount volumes as super user
This used to be the case, but regressed after a recent change.
Also made a few fixes around it and clean up the code a bit.
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/mounts.go",
"new_path": "pkg/sentry/fs/mounts.go",
"diff": "@@ -171,8 +171,6 @@ type MountNamespace struct {\n// NewMountNamespace returns a new MountNamespace, with the provided node at the\n// root, and the given cache size. A root must always be provided.\nfunc NewMountNamespace(ctx context.Context, root *Inode) (*MountNamespace, error) {\n- creds := auth.CredentialsFromContext(ctx)\n-\n// Set the root dirent and id on the root mount. The reference returned from\n// NewDirent will be donated to the MountNamespace constructed below.\nd := NewDirent(ctx, root, \"/\")\n@@ -181,6 +179,7 @@ func NewMountNamespace(ctx context.Context, root *Inode) (*MountNamespace, error\nd: newRootMount(1, d),\n}\n+ creds := auth.CredentialsFromContext(ctx)\nmns := MountNamespace{\nuserns: creds.UserNamespace,\nroot: d,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/fs.go",
"new_path": "runsc/boot/fs.go",
"diff": "@@ -25,19 +25,21 @@ import (\n// Include filesystem types that OCI spec might mount.\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/dev\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs/gofer\"\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/host\"\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/proc\"\n- \"gvisor.dev/gvisor/pkg/sentry/fs/ramfs\"\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/sys\"\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/tmpfs\"\n_ \"gvisor.dev/gvisor/pkg/sentry/fs/tty\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/gofer\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs/ramfs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n\"gvisor.dev/gvisor/runsc/specutils\"\n)\n@@ -261,6 +263,18 @@ func subtargets(root string, mnts []specs.Mount) []string {\nreturn targets\n}\n+func setupContainerFS(ctx context.Context, conf *Config, mntr *containerMounter, procArgs *kernel.CreateProcessArgs) error {\n+ mns, err := mntr.setupFS(conf, procArgs)\n+ if err != nil {\n+ return err\n+ }\n+\n+ // Set namespace here so that it can be found in ctx.\n+ procArgs.MountNamespace = mns\n+\n+ return setExecutablePath(ctx, procArgs)\n+}\n+\n// setExecutablePath sets the procArgs.Filename by searching the PATH for an\n// executable matching the procArgs.Argv[0].\nfunc setExecutablePath(ctx context.Context, procArgs *kernel.CreateProcessArgs) error {\n@@ -500,73 +514,95 @@ func newContainerMounter(spec *specs.Spec, goferFDs []int, k *kernel.Kernel, hin\n}\n}\n-// setupChildContainer is used to set up the file system for non-root containers\n-// and amend the procArgs accordingly. This is the main entry point for this\n-// rest of functions in this file. procArgs are passed by reference and the\n-// FDMap field is modified. It dups stdioFDs.\n-func (c *containerMounter) setupChildContainer(conf *Config, procArgs *kernel.CreateProcessArgs) error {\n- // Setup a child container.\n- log.Infof(\"Creating new process in child container.\")\n+// processHints processes annotations that container hints about how volumes\n+// should be mounted (e.g. a volume shared between containers). It must be\n+// called for the root container only.\n+func (c *containerMounter) processHints(conf *Config) error {\n+ ctx := c.k.SupervisorContext()\n+ for _, hint := range c.hints.mounts {\n+ log.Infof(\"Mounting master of shared mount %q from %q type %q\", hint.name, hint.mount.Source, hint.mount.Type)\n+ inode, err := c.mountSharedMaster(ctx, conf, hint)\n+ if err != nil {\n+ return fmt.Errorf(\"mounting shared master %q: %v\", hint.name, err)\n+ }\n+ hint.root = inode\n+ }\n+ return nil\n+}\n+\n+// setupFS is used to set up the file system for all containers. This is the\n+// main entry point method, with most of the other being internal only. It\n+// returns the mount namespace that is created for the container.\n+func (c *containerMounter) setupFS(conf *Config, procArgs *kernel.CreateProcessArgs) (*fs.MountNamespace, error) {\n+ log.Infof(\"Configuring container's file system\")\n+\n+ // Create context with root credentials to mount the filesystem (the current\n+ // user may not be privileged enough).\n+ rootProcArgs := *procArgs\n+ rootProcArgs.WorkingDirectory = \"/\"\n+ rootProcArgs.Credentials = auth.NewRootCredentials(procArgs.Credentials.UserNamespace)\n+ rootProcArgs.Umask = 0022\n+ rootProcArgs.MaxSymlinkTraversals = linux.MaxSymlinkTraversals\n+ rootCtx := rootProcArgs.NewContext(c.k)\n- // Create a new root inode and mount namespace for the container.\n- rootCtx := c.k.SupervisorContext()\n- rootInode, err := c.createRootMount(rootCtx, conf)\n+ mns, err := c.createMountNamespace(rootCtx, conf)\nif err != nil {\n- return fmt.Errorf(\"creating filesystem for container: %v\", err)\n+ return nil, err\n}\n- mns, err := fs.NewMountNamespace(rootCtx, rootInode)\n+\n+ // Set namespace here so that it can be found in rootCtx.\n+ rootProcArgs.MountNamespace = mns\n+\n+ if err := c.mountSubmounts(rootCtx, conf, mns); err != nil {\n+ return nil, err\n+ }\n+ return mns, nil\n+}\n+\n+func (c *containerMounter) createMountNamespace(ctx context.Context, conf *Config) (*fs.MountNamespace, error) {\n+ rootInode, err := c.createRootMount(ctx, conf)\nif err != nil {\n- return fmt.Errorf(\"creating new mount namespace for container: %v\", err)\n+ return nil, fmt.Errorf(\"creating filesystem for container: %v\", err)\n}\n- procArgs.MountNamespace = mns\n+ mns, err := fs.NewMountNamespace(ctx, rootInode)\n+ if err != nil {\n+ return nil, fmt.Errorf(\"creating new mount namespace for container: %v\", err)\n+ }\n+ return mns, nil\n+}\n+\n+func (c *containerMounter) mountSubmounts(ctx context.Context, conf *Config, mns *fs.MountNamespace) error {\nroot := mns.Root()\ndefer root.DecRef()\n- // Mount all submounts.\n- if err := c.mountSubmounts(rootCtx, conf, mns, root); err != nil {\n- return err\n+ for _, m := range c.mounts {\n+ log.Debugf(\"Mounting %q to %q, type: %s, options: %s\", m.Source, m.Destination, m.Type, m.Options)\n+ if hint := c.hints.findMount(m); hint != nil && hint.isSupported() {\n+ if err := c.mountSharedSubmount(ctx, mns, root, m, hint); err != nil {\n+ return fmt.Errorf(\"mount shared mount %q to %q: %v\", hint.name, m.Destination, err)\n}\n- return c.checkDispenser()\n+ } else {\n+ if err := c.mountSubmount(ctx, conf, mns, root, m); err != nil {\n+ return fmt.Errorf(\"mount submount %q: %v\", m.Destination, err)\n}\n-\n-func (c *containerMounter) checkDispenser() error {\n- if !c.fds.empty() {\n- return fmt.Errorf(\"not all gofer FDs were consumed, remaining: %v\", c.fds)\n}\n- return nil\n}\n-// setupRootContainer creates a mount namespace containing the root filesystem\n-// and all mounts. 'rootCtx' is used to walk directories to find mount points.\n-// The 'setMountNS' callback is called after the mount namespace is created and\n-// will get a reference on that namespace. The callback must ensure that the\n-// rootCtx has the provided mount namespace.\n-func (c *containerMounter) setupRootContainer(userCtx context.Context, rootCtx context.Context, conf *Config, setMountNS func(*fs.MountNamespace)) error {\n- for _, hint := range c.hints.mounts {\n- log.Infof(\"Mounting master of shared mount %q from %q type %q\", hint.name, hint.mount.Source, hint.mount.Type)\n- inode, err := c.mountSharedMaster(rootCtx, conf, hint)\n- if err != nil {\n- return fmt.Errorf(\"mounting shared master %q: %v\", hint.name, err)\n- }\n- hint.root = inode\n+ if err := c.mountTmp(ctx, conf, mns, root); err != nil {\n+ return fmt.Errorf(\"mount submount %q: %v\", \"tmp\", err)\n}\n- rootInode, err := c.createRootMount(rootCtx, conf)\n- if err != nil {\n- return fmt.Errorf(\"creating root mount: %v\", err)\n+ if err := c.checkDispenser(); err != nil {\n+ return err\n}\n- mns, err := fs.NewMountNamespace(userCtx, rootInode)\n- if err != nil {\n- return fmt.Errorf(\"creating root mount namespace: %v\", err)\n+ return nil\n}\n- setMountNS(mns)\n- root := mns.Root()\n- defer root.DecRef()\n- if err := c.mountSubmounts(rootCtx, conf, mns, root); err != nil {\n- return fmt.Errorf(\"mounting submounts: %v\", err)\n+func (c *containerMounter) checkDispenser() error {\n+ if !c.fds.empty() {\n+ return fmt.Errorf(\"not all gofer FDs were consumed, remaining: %v\", c.fds)\n}\n- return c.checkDispenser()\n+ return nil\n}\n// mountSharedMaster mounts the master of a volume that is shared among\n@@ -684,25 +720,6 @@ func (c *containerMounter) getMountNameAndOptions(conf *Config, m specs.Mount) (\nreturn fsName, opts, useOverlay, err\n}\n-func (c *containerMounter) mountSubmounts(ctx context.Context, conf *Config, mns *fs.MountNamespace, root *fs.Dirent) error {\n- for _, m := range c.mounts {\n- if hint := c.hints.findMount(m); hint != nil && hint.isSupported() {\n- if err := c.mountSharedSubmount(ctx, mns, root, m, hint); err != nil {\n- return fmt.Errorf(\"mount shared mount %q to %q: %v\", hint.name, m.Destination, err)\n- }\n- } else {\n- if err := c.mountSubmount(ctx, conf, mns, root, m); err != nil {\n- return fmt.Errorf(\"mount submount %q: %v\", m.Destination, err)\n- }\n- }\n- }\n-\n- if err := c.mountTmp(ctx, conf, mns, root); err != nil {\n- return fmt.Errorf(\"mount submount %q: %v\", \"tmp\", err)\n- }\n- return nil\n-}\n-\n// mountSubmount mounts volumes inside the container's root. Because mounts may\n// be readonly, a lower ramfs overlay is added to create the mount point dir.\n// Another overlay is added with tmpfs on top if Config.Overlay is true.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -527,14 +527,12 @@ func (l *Loader) run() error {\n// Setup the root container file system.\nl.startGoferMonitor(l.sandboxID, l.goferFDs)\n+\nmntr := newContainerMounter(l.spec, l.goferFDs, l.k, l.mountHints)\n- if err := mntr.setupRootContainer(ctx, ctx, l.conf, func(mns *fs.MountNamespace) {\n- l.rootProcArgs.MountNamespace = mns\n- }); err != nil {\n+ if err := mntr.processHints(l.conf); err != nil {\nreturn err\n}\n-\n- if err := setExecutablePath(ctx, &l.rootProcArgs); err != nil {\n+ if err := setupContainerFS(ctx, l.conf, mntr, &l.rootProcArgs); err != nil {\nreturn err\n}\n@@ -687,13 +685,10 @@ func (l *Loader) startContainer(spec *specs.Spec, conf *Config, cid string, file\n// Setup the child container file system.\nl.startGoferMonitor(cid, goferFDs)\n- mntr := newContainerMounter(spec, goferFDs, l.k, l.mountHints)\n- if err := mntr.setupChildContainer(conf, &procArgs); err != nil {\n- return fmt.Errorf(\"configuring container FS: %v\", err)\n- }\n- if err := setExecutablePath(ctx, &procArgs); err != nil {\n- return fmt.Errorf(\"setting executable path for %+v: %v\", procArgs, err)\n+ mntr := newContainerMounter(spec, goferFDs, l.k, l.mountHints)\n+ if err := setupContainerFS(ctx, conf, mntr, &procArgs); err != nil {\n+ return err\n}\n// Create and start the new process.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader_test.go",
"new_path": "runsc/boot/loader_test.go",
"diff": "@@ -401,17 +401,16 @@ func TestCreateMountNamespace(t *testing.T) {\n}\ndefer cleanup()\n- // setupRootContainer needs to find root from the context after the\n- // namespace is created.\n- var mns *fs.MountNamespace\n- setMountNS := func(m *fs.MountNamespace) {\n- mns = m\n- ctx.(*contexttest.TestContext).RegisterValue(fs.CtxRoot, mns.Root())\n- }\nmntr := newContainerMounter(&tc.spec, []int{sandEnd}, nil, &podMountHints{})\n- if err := mntr.setupRootContainer(ctx, ctx, conf, setMountNS); err != nil {\n- t.Fatalf(\"createMountNamespace test case %q failed: %v\", tc.name, err)\n+ mns, err := mntr.createMountNamespace(ctx, conf)\n+ if err != nil {\n+ t.Fatalf(\"failed to create mount namespace: %v\", err)\n}\n+ ctx = fs.WithRoot(ctx, mns.Root())\n+ if err := mntr.mountSubmounts(ctx, conf, mns); err != nil {\n+ t.Fatalf(\"failed to create mount namespace: %v\", err)\n+ }\n+\nroot := mns.Root()\ndefer root.DecRef()\nfor _, p := range tc.expectedPaths {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/user_test.go",
"new_path": "runsc/boot/user_test.go",
"diff": "@@ -164,13 +164,13 @@ func TestGetExecUserHome(t *testing.T) {\n},\n}\n- var mns *fs.MountNamespace\n- setMountNS := func(m *fs.MountNamespace) {\n- mns = m\n- ctx.(*contexttest.TestContext).RegisterValue(fs.CtxRoot, mns.Root())\n- }\nmntr := newContainerMounter(spec, []int{sandEnd}, nil, &podMountHints{})\n- if err := mntr.setupRootContainer(ctx, ctx, conf, setMountNS); err != nil {\n+ mns, err := mntr.createMountNamespace(ctx, conf)\n+ if err != nil {\n+ t.Fatalf(\"failed to create mount namespace: %v\", err)\n+ }\n+ ctx = fs.WithRoot(ctx, mns.Root())\n+ if err := mntr.mountSubmounts(ctx, conf, mns); err != nil {\nt.Fatalf(\"failed to create mount namespace: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -1310,10 +1310,13 @@ func TestRunNonRoot(t *testing.T) {\nt.Logf(\"Running test with conf: %+v\", conf)\nspec := testutil.NewSpecWithArgs(\"/bin/true\")\n+\n+ // Set a random user/group with no access to \"blocked\" dir.\nspec.Process.User.UID = 343\nspec.Process.User.GID = 2401\n+ spec.Process.Capabilities = nil\n- // User that container runs as can't list '$TMP/blocked' and would fail to\n+ // User running inside container can't list '$TMP/blocked' and would fail to\n// mount it.\ndir, err := ioutil.TempDir(testutil.TmpDir(), \"blocked\")\nif err != nil {\n@@ -1327,6 +1330,17 @@ func TestRunNonRoot(t *testing.T) {\nt.Fatalf(\"os.MkDir(%q) failed: %v\", dir, err)\n}\n+ src, err := ioutil.TempDir(testutil.TmpDir(), \"src\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed: %v\", err)\n+ }\n+\n+ spec.Mounts = append(spec.Mounts, specs.Mount{\n+ Destination: dir,\n+ Source: src,\n+ Type: \"bind\",\n+ })\n+\nif err := run(spec, conf); err != nil {\nt.Fatalf(\"error running sandbox: %v\", err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -1485,3 +1485,58 @@ func TestMultiContainerLoadSandbox(t *testing.T) {\nt.Errorf(\"containers not found: %v\", wantIDs)\n}\n}\n+\n+// TestMultiContainerRunNonRoot checks that child container can be configured\n+// when running as non-privileged user.\n+func TestMultiContainerRunNonRoot(t *testing.T) {\n+ cmdRoot := []string{\"/bin/sleep\", \"100\"}\n+ cmdSub := []string{\"/bin/true\"}\n+ podSpecs, ids := createSpecs(cmdRoot, cmdSub)\n+\n+ // User running inside container can't list '$TMP/blocked' and would fail to\n+ // mount it.\n+ blocked, err := ioutil.TempDir(testutil.TmpDir(), \"blocked\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed: %v\", err)\n+ }\n+ if err := os.Chmod(blocked, 0700); err != nil {\n+ t.Fatalf(\"os.MkDir(%q) failed: %v\", blocked, err)\n+ }\n+ dir := path.Join(blocked, \"test\")\n+ if err := os.Mkdir(dir, 0755); err != nil {\n+ t.Fatalf(\"os.MkDir(%q) failed: %v\", dir, err)\n+ }\n+\n+ src, err := ioutil.TempDir(testutil.TmpDir(), \"src\")\n+ if err != nil {\n+ t.Fatalf(\"ioutil.TempDir() failed: %v\", err)\n+ }\n+\n+ // Set a random user/group with no access to \"blocked\" dir.\n+ podSpecs[1].Process.User.UID = 343\n+ podSpecs[1].Process.User.GID = 2401\n+ podSpecs[1].Process.Capabilities = nil\n+\n+ podSpecs[1].Mounts = append(podSpecs[1].Mounts, specs.Mount{\n+ Destination: dir,\n+ Source: src,\n+ Type: \"bind\",\n+ })\n+\n+ conf := testutil.TestConfig()\n+ pod, cleanup, err := startContainers(conf, podSpecs, ids)\n+ if err != nil {\n+ t.Fatalf(\"error starting containers: %v\", err)\n+ }\n+ defer cleanup()\n+\n+ // Once all containers are started, wait for the child container to exit.\n+ // This means that the volume was mounted properly.\n+ ws, err := pod[1].Wait()\n+ if err != nil {\n+ t.Fatalf(\"running child container: %v\", err)\n+ }\n+ if !ws.Exited() || ws.ExitStatus() != 0 {\n+ t.Fatalf(\"child container failed, waitStatus: %v\", ws)\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Mount volumes as super user
This used to be the case, but regressed after a recent change.
Also made a few fixes around it and clean up the code a bit.
Closes #720
PiperOrigin-RevId: 265717496 |
259,992 | 27.08.2019 10:51:23 | 25,200 | 8fd89fd7a2b4a69c76b126fa52f47757b6076d36 | Fix sendfile(2) error code
When output file is in append mode, sendfile(2) should fail
with EINVAL and not EBADF.
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"new_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"diff": "@@ -91,22 +91,29 @@ func Sendfile(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n// Get files.\n+ inFile := t.GetFile(inFD)\n+ if inFile == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer inFile.DecRef()\n+\n+ if !inFile.Flags().Read {\n+ return 0, nil, syserror.EBADF\n+ }\n+\noutFile := t.GetFile(outFD)\nif outFile == nil {\nreturn 0, nil, syserror.EBADF\n}\ndefer outFile.DecRef()\n- inFile := t.GetFile(inFD)\n- if inFile == nil {\n+ if !outFile.Flags().Write {\nreturn 0, nil, syserror.EBADF\n}\n- defer inFile.DecRef()\n- // Verify that the outfile Append flag is not set. Note that fs.Splice\n- // itself validates that the output file is writable.\n+ // Verify that the outfile Append flag is not set.\nif outFile.Flags().Append {\n- return 0, nil, syserror.EBADF\n+ return 0, nil, syserror.EINVAL\n}\n// Verify that we have a regular infile. This is a requirement; the\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/sendfile.cc",
"new_path": "test/syscalls/linux/sendfile.cc",
"diff": "@@ -299,10 +299,30 @@ TEST(SendFileTest, DoNotSendfileIfOutfileIsAppendOnly) {\n// Open the output file as append only.\nconst FileDescriptor outf =\n- ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_APPEND));\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(out_file.path(), O_WRONLY | O_APPEND));\n// Send data and verify that sendfile returns the correct errno.\nEXPECT_THAT(sendfile(outf.get(), inf.get(), nullptr, kDataSize),\n+ SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(SendFileTest, AppendCheckOrdering) {\n+ constexpr char kData[] = \"And by opposing end them: to die, to sleep\";\n+ constexpr int kDataSize = sizeof(kData) - 1;\n+ const TempPath file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n+\n+ const FileDescriptor read =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+ const FileDescriptor write =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_WRONLY));\n+ const FileDescriptor append =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_APPEND));\n+\n+ // Check that read/write file mode is verified before append.\n+ EXPECT_THAT(sendfile(append.get(), read.get(), nullptr, kDataSize),\n+ SyscallFailsWithErrno(EBADF));\n+ EXPECT_THAT(sendfile(write.get(), write.get(), nullptr, kDataSize),\nSyscallFailsWithErrno(EBADF));\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix sendfile(2) error code
When output file is in append mode, sendfile(2) should fail
with EINVAL and not EBADF.
Closes #721
PiperOrigin-RevId: 265718958 |
259,975 | 27.08.2019 14:48:36 | 25,200 | f64d9a7d93865b1ab5246a5ded2ece890582b902 | Fix pwritev2 flaky test.
Fix a uninitialized memory bug in pwritev2 test. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pwritev2.cc",
"new_path": "test/syscalls/linux/pwritev2.cc",
"diff": "@@ -244,8 +244,10 @@ TEST(Pwritev2Test, TestInvalidOffset) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR));\n+ char buf[16];\nstruct iovec iov;\n- iov.iov_base = nullptr;\n+ iov.iov_base = buf;\n+ iov.iov_len = sizeof(buf);\nEXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n/*offset=*/static_cast<off_t>(-8), /*flags=*/0),\n@@ -286,8 +288,10 @@ TEST(Pwritev2Test, TestUnseekableFileInValid) {\nSKIP_IF(pwritev2(-1, nullptr, 0, 0, 0) < 0 && errno == ENOSYS);\nint pipe_fds[2];\n+ char buf[16];\nstruct iovec iov;\n- iov.iov_base = nullptr;\n+ iov.iov_base = buf;\n+ iov.iov_len = sizeof(buf);\nASSERT_THAT(pipe(pipe_fds), SyscallSucceeds());\n@@ -307,8 +311,10 @@ TEST(Pwritev2Test, TestReadOnlyFile) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDONLY));\n+ char buf[16];\nstruct iovec iov;\n- iov.iov_base = nullptr;\n+ iov.iov_base = buf;\n+ iov.iov_len = sizeof(buf);\nEXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n/*offset=*/0, /*flags=*/0),\n@@ -324,8 +330,10 @@ TEST(Pwritev2Test, TestInvalidFlag) {\nconst FileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(file.path(), O_RDWR | O_DIRECT));\n+ char buf[16];\nstruct iovec iov;\n- iov.iov_base = nullptr;\n+ iov.iov_base = buf;\n+ iov.iov_len = sizeof(buf);\nEXPECT_THAT(pwritev2(fd.get(), &iov, /*iovcnt=*/1,\n/*offset=*/0, /*flags=*/0xF0),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix pwritev2 flaky test.
Fix a uninitialized memory bug in pwritev2 test.
PiperOrigin-RevId: 265772176 |
259,858 | 27.08.2019 23:24:33 | 25,200 | 784f48a78debe68435b8fb59e8132d4dbc47ce48 | kokoro: Add scripts to rebuild images.
These scripts generated the following images:
gvisor-kokoro-testing/image-a53bac71541a209e (ubuntu 18.04)
gvisor-kokoro-testing/image-f5b20c5fbd23f448 (ubuntu 16.04)
Any modifications to these scripts should generate new images. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/10_core.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# Install all essential build tools.\n+apt-get update && apt-get -y install make git-core build-essential linux-headers-$(uname -r) pkg-config\n+\n+# Install a recent go toolchain.\n+if ! [[ -d /usr/local/go ]]; then\n+ wget https://dl.google.com/go/go1.12.linux-amd64.tar.gz\n+ tar -xvf go1.12.linux-amd64.tar.gz\n+ mv go /usr/local\n+fi\n+\n+# Link the Go binary from /usr/bin; replacing anything there.\n+(cd /usr/bin && rm -f go && sudo ln -fs /usr/local/go/bin/go go)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/20_bazel.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# We need to install a specific version of bazel due to a bug with the RBE\n+# environment not respecting the dockerPrivileged configuration.\n+declare -r BAZEL_VERSION=0.28.1\n+\n+# Install bazel dependencies.\n+apt-get update && apt-get install -y openjdk-8-jdk-headless unzip\n+\n+# Use the release installer.\n+curl -L -o bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh https://github.com/bazelbuild/bazel/releases/download/${BAZEL_VERSION}/bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh\n+chmod a+x bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh\n+./bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh\n+rm -f bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/30_containerd.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# Helper for Go packages below.\n+install_helper() {\n+ PACKAGE=\"${1}\"\n+ TAG=\"${2}\"\n+ GOPATH=\"${3}\"\n+\n+ # Clone the repository.\n+ mkdir -p \"${GOPATH}\"/src/$(dirname \"${PACKAGE}\") && \\\n+ git clone https://\"${PACKAGE}\" \"${GOPATH}\"/src/\"${PACKAGE}\"\n+\n+ # Checkout and build the repository.\n+ (cd \"${GOPATH}\"/src/\"${PACKAGE}\" && \\\n+ git checkout \"${TAG}\" && \\\n+ GOPATH=\"${GOPATH}\" make && \\\n+ GOPATH=\"${GOPATH}\" make install)\n+}\n+\n+# Install dependencies for the crictl tests.\n+apt-get install -y btrfs-tools libseccomp-dev\n+\n+# Install containerd & cri-tools.\n+GOPATH=$(mktemp -d --tmpdir gopathXXXXX)\n+install_helper github.com/containerd/containerd v1.2.2 \"${GOPATH}\"\n+install_helper github.com/kubernetes-sigs/cri-tools v1.11.0 \"${GOPATH}\"\n+\n+# Install gvisor-containerd-shim.\n+declare -r base=\"https://storage.googleapis.com/cri-containerd-staging/gvisor-containerd-shim\"\n+declare -r latest=$(mktemp --tmpdir gvisor-containerd-shim-latest.XXXXXX)\n+declare -r shim_path=$(mktemp --tmpdir gvisor-containerd-shim.XXXXXX)\n+wget --no-verbose \"${base}\"/latest -O ${latest}\n+wget --no-verbose \"${base}\"/gvisor-containerd-shim-$(cat ${latest}) -O ${shim_path}\n+chmod +x ${shim_path}\n+mv ${shim_path} /usr/local/bin\n+\n+# Configure containerd-shim.\n+declare -r shim_config_path=/etc/containerd\n+declare -r shim_config_tmp_path=$(mktemp --tmpdir gvisor-containerd-shim.XXXXXX.toml)\n+mkdir -p ${shim_config_path}\n+cat > ${shim_config_tmp_path} <<-EOF\n+ runc_shim = \"/usr/local/bin/containerd-shim\"\n+\n+[runsc_config]\n+ debug = \"true\"\n+ debug-log = \"/tmp/runsc-logs/\"\n+ strace = \"true\"\n+ file-access = \"shared\"\n+EOF\n+mv ${shim_config_tmp_path} ${shim_config_path}\n+\n+# Configure CNI.\n+(cd \"${GOPATH}\" && GOPATH=\"${GOPATH}\" \\\n+ src/github.com/containerd/containerd/script/setup/install-cni)\n+\n+# Cleanup the above.\n+rm -rf \"${GOPATH}\"\n+rm -rf \"${latest}\"\n+rm -rf \"${shim_path}\"\n+rm -rf \"${shim_config_tmp_path}\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/40_kokoro.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# Declare kokoro's required public keys.\n+declare -r ssh_public_keys=(\n+ \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDg7L/ZaEauETWrPklUTky3kvxqQfe2Ax/2CsSqhNIGNMnK/8d79CHlmY9+dE1FFQ/RzKNCaltgy7XcN/fCYiCZr5jm2ZtnLuGNOTzupMNhaYiPL419qmL+5rZXt4/dWTrsHbFRACxT8j51PcRMO5wgbL0Bg2XXimbx8kDFaurL2gqduQYqlu4lxWCaJqOL71WogcimeL63Nq/yeH5PJPWpqE4P9VUQSwAzBWFK/hLeds/AiP3MgVS65qHBnhq0JsHy8JQsqjZbG7Iidt/Ll0+gqzEbi62gDIcczG4KC0iOVzDDP/1BxDtt1lKeA23ll769Fcm3rJyoBMYxjvdw1TDx [email protected]\"\n+ \"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNgGK/hCdjmulHfRE3hp4rZs38NCR8yAh0eDsztxqGcuXnuSnL7jOlRrbcQpremJ84omD4eKrIpwJUs+YokMdv4= [email protected]\"\n+)\n+\n+# Install dependencies.\n+apt-get install -y rsync coreutils\n+\n+# We need a kbuilder user.\n+if useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder; then\n+ # User was added successfully; we add the relevant SSH keys here.\n+ mkdir -p ~kbuilder/.ssh\n+ (IFS=$'\\n'; echo \"${ssh_public_keys[*]}\") > ~kbuilder/.ssh/authorized_keys\n+ chmod 0600 ~kbuilder/.ssh/authorized_keys\n+fi\n+\n+# Ensure that /tmpfs exists and is writable by kokoro.\n+#\n+# Note that kokoro will typically attach a second disk (sdb) to the instance\n+# that is used for the /tmpfs volume. In the future we could setup an init\n+# script that formats and mounts this here; however, we don't expect our build\n+# artifacts to be that large.\n+mkdir -p /tmpfs && chmod 0755 /tmpfs && touch /tmpfs/READY\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/build.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# Run the image_build.sh script with appropriate parameters.\n+IMAGE_PROJECT=ubuntu-os-cloud IMAGE_FAMILY=ubuntu-1604-lts $(dirname $0)/../../tools/image_build.sh $(dirname $0)/??_*.sh\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/10_core.sh",
"diff": "+../ubuntu1604/10_core.sh\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/20_bazel.sh",
"diff": "+../ubuntu1604/20_bazel.sh\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/30_containerd.sh",
"diff": "+../ubuntu1604/30_containerd.sh\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/40_kokoro.sh",
"diff": "+../ubuntu1604/40_kokoro.sh\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/build.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+set -xeo pipefail\n+\n+# Run the image_build.sh script with appropriate parameters.\n+IMAGE_PROJECT=ubuntu-os-cloud IMAGE_FAMILY=ubuntu-1804-lts $(dirname $0)/../../tools/image_build.sh $(dirname $0)/??_*.sh\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tools/image_build.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# This script is responsible for building a new GCP image that: 1) has nested\n+# virtualization enabled, and 2) has been completely set up with the\n+# image_setup.sh script. This script should be idempotent, as we memoize the\n+# setup script with a hash and check for that name.\n+#\n+# The GCP project name should be defined via a gcloud config.\n+\n+set -xeo pipefail\n+\n+# Parameters.\n+declare -r ZONE=${ZONE:-us-central1-f}\n+declare -r USERNAME=${USERNAME:-test}\n+declare -r IMAGE_PROJECT=${IMAGE_PROJECT:-ubuntu-os-cloud}\n+declare -r IMAGE_FAMILY=${IMAGE_FAMILY:-ubuntu-1604-lts}\n+\n+# Random names.\n+declare -r DISK_NAME=$(mktemp -u disk-XXXXXX | tr A-Z a-z)\n+declare -r SNAPSHOT_NAME=$(mktemp -u snapshot-XXXXXX | tr A-Z a-z)\n+declare -r INSTANCE_NAME=$(mktemp -u build-XXXXXX | tr A-Z a-z)\n+\n+# Hashes inputs.\n+declare -r SETUP_BLOB=$(echo ${ZONE} ${USERNAME} ${IMAGE_PROJECT} ${IMAGE_FAMILY} && sha256sum \"$@\")\n+declare -r SETUP_HASH=$(echo ${SETUP_BLOB} | sha256sum - | cut -d' ' -f1 | cut -c 1-16)\n+declare -r IMAGE_NAME=${IMAGE_NAME:-image-}${SETUP_HASH}\n+\n+# Does the image already exist? Skip the build.\n+declare -r existing=$(gcloud compute images list --filter=\"name=(${IMAGE_NAME})\" --format=\"value(name)\")\n+if ! [[ -z \"${existing}\" ]]; then\n+ echo \"${existing}\"\n+ exit 0\n+fi\n+\n+# Set the zone for all actions.\n+gcloud config set compute/zone \"${ZONE}\"\n+\n+# Start a unique instance. Note that this instance will have a unique persistent\n+# disk as it's boot disk with the same name as the instance.\n+gcloud compute instances create \\\n+ --quiet \\\n+ --image-project \"${IMAGE_PROJECT}\" \\\n+ --image-family \"${IMAGE_FAMILY}\" \\\n+ --boot-disk-size \"200GB\" \\\n+ \"${INSTANCE_NAME}\"\n+function cleanup {\n+ gcloud compute instances delete --quiet \"${INSTANCE_NAME}\"\n+}\n+trap cleanup EXIT\n+\n+# Wait for the instance to become available.\n+declare attempts=0\n+while [[ \"${attempts}\" -lt 30 ]]; do\n+ attempts=$((${attempts}+1))\n+ if gcloud compute ssh \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- true; then\n+ break\n+ fi\n+done\n+if [[ \"${attempts}\" -ge 30 ]]; then\n+ echo \"too many attempts: failed\"\n+ exit 1\n+fi\n+\n+# Run the install scripts provided.\n+for arg; do\n+ gcloud compute ssh \"${USERNAME}\"@\"${INSTANCE_NAME}\" -- sudo bash - <\"${arg}\"\n+done\n+\n+# Stop the instance; required before creating an image.\n+gcloud compute instances stop --quiet \"${INSTANCE_NAME}\"\n+\n+# Create a snapshot of the instance disk.\n+gcloud compute disks snapshot \\\n+ --quiet \\\n+ --zone=\"${ZONE}\" \\\n+ --snapshot-names=\"${SNAPSHOT_NAME}\" \\\n+ \"${INSTANCE_NAME}\"\n+\n+# Create the disk image.\n+gcloud compute images create \\\n+ --quiet \\\n+ --source-snapshot=\"${SNAPSHOT_NAME}\" \\\n+ --licenses=\"https://www.googleapis.com/compute/v1/projects/vm-options/global/licenses/enable-vmx\" \\\n+ \"${IMAGE_NAME}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | kokoro: Add scripts to rebuild images.
These scripts generated the following images:
gvisor-kokoro-testing/image-a53bac71541a209e (ubuntu 18.04)
gvisor-kokoro-testing/image-f5b20c5fbd23f448 (ubuntu 16.04)
Any modifications to these scripts should generate new images.
PiperOrigin-RevId: 265843929 |
259,858 | 28.08.2019 22:06:09 | 25,200 | 06ae36185ec0a68b4d191ba1c86d4dc250ac2b38 | Fix kokoro image build scripts
The /tmpfs directory needs to be writable, and kokoro needs passwordless sudo
access to execute the test scripts. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/ubuntu1604/40_kokoro.sh",
"new_path": "kokoro/ubuntu1604/40_kokoro.sh",
"diff": "@@ -33,10 +33,15 @@ if useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder; then\nchmod 0600 ~kbuilder/.ssh/authorized_keys\nfi\n+# Give passwordless sudo access.\n+cat > /etc/sudoers.d/kokoro <<EOF\n+kbuilder ALL=(ALL) NOPASSWD:ALL\n+EOF\n+\n# Ensure that /tmpfs exists and is writable by kokoro.\n#\n# Note that kokoro will typically attach a second disk (sdb) to the instance\n# that is used for the /tmpfs volume. In the future we could setup an init\n# script that formats and mounts this here; however, we don't expect our build\n# artifacts to be that large.\n-mkdir -p /tmpfs && chmod 0755 /tmpfs && touch /tmpfs/READY\n+mkdir -p /tmpfs && chmod 0777 /tmpfs && touch /tmpfs/READY\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix kokoro image build scripts
The /tmpfs directory needs to be writable, and kokoro needs passwordless sudo
access to execute the test scripts.
PiperOrigin-RevId: 266063723 |
259,858 | 28.08.2019 22:34:45 | 25,200 | f048c8be1e7636df238e616b41a123ada2049759 | Fix permissions on .ssh files | [
{
"change_type": "MODIFY",
"old_path": "kokoro/ubuntu1604/40_kokoro.sh",
"new_path": "kokoro/ubuntu1604/40_kokoro.sh",
"diff": "@@ -31,6 +31,7 @@ if useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder; then\nmkdir -p ~kbuilder/.ssh\n(IFS=$'\\n'; echo \"${ssh_public_keys[*]}\") > ~kbuilder/.ssh/authorized_keys\nchmod 0600 ~kbuilder/.ssh/authorized_keys\n+ chown -R kbuilder ~kbuilder/.ssh\nfi\n# Give passwordless sudo access.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix permissions on .ssh files
PiperOrigin-RevId: 266066839 |
259,891 | 26.08.2019 13:09:49 | 25,200 | 9e7378a377440fe2d33920e2cb20028c728886da | Add a shortlist of commonly request debugging tools. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -36,5 +36,20 @@ The following applications/images have been tested:\n* tomcat\n* wordpress\n+## Debugging tools\n+\n+Most common debugging utilities work. Specific tools include:\n+\n+| Tool | Status |\n+| --- | --- |\n+| curl | Working |\n+| dig | Working |\n+| drill | Working |\n+| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n+| nslookup | Working |\n+| ping | Working |\n+| tcpdump | [In progress](https://github.com/google/gvisor/issues/173) |\n+| wget | Working |\n+\n[bug]: https://github.com/google/gvisor/issues/new?title=Compatibility%20Issue:\n[issues]: https://github.com/google/gvisor/issues?q=is%3Aissue+is%3Aopen+label%3A%22area%3A+compatibility%22\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a shortlist of commonly request debugging tools. |
259,891 | 26.08.2019 15:16:44 | 25,200 | 16582ade1743b2b4e93ebe90a5e46dd13a54b6f6 | Added gdb, lsof, ps, ss, and top. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -45,10 +45,15 @@ Most common debugging utilities work. Specific tools include:\n| curl | Working |\n| dig | Working |\n| drill | Working |\n+| gdb | Working |\n+| lsof | Working |\n| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n| nslookup | Working |\n| ping | Working |\n+| ps | Working |\n+| ss | Not working |\n| tcpdump | [In progress](https://github.com/google/gvisor/issues/173) |\n+| top | Working |\n| wget | Working |\n[bug]: https://github.com/google/gvisor/issues/new?title=Compatibility%20Issue:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added gdb, lsof, ps, ss, and top. |
259,891 | 26.08.2019 15:33:29 | 25,200 | a89ee859b9b15cdfbfd1eb5219e97fc9884c92d2 | Added note about --net-raw. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -38,7 +38,9 @@ The following applications/images have been tested:\n## Debugging tools\n-Most common debugging utilities work. Specific tools include:\n+Most common debugging utilities work. Note that some tools, such as tcpdump and\n+old versions of ping, require excplicitly enabling raw sockets via the unsafe\n+`--net-raw` runsc flag. Specific tools include:\n| Tool | Status |\n| --- | --- |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added note about --net-raw. |
259,891 | 26.08.2019 16:30:08 | 25,200 | 8e406b0bf96f2f8b39275d1d0b9a3283678c0755 | Added nc, ip, and sshd. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -48,12 +48,15 @@ old versions of ping, require excplicitly enabling raw sockets via the unsafe\n| dig | Working |\n| drill | Working |\n| gdb | Working |\n+| ip | Most commands not working. Some (e.g. addr) work |\n| lsof | Working |\n+| nc | Working |\n| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n| nslookup | Working |\n| ping | Working |\n| ps | Working |\n-| ss | Not working |\n+| ss | Working |\n+| sshd | Partially working. Job control [in progress](https://github.com/google/gvisor/issues/154) |\n| tcpdump | [In progress](https://github.com/google/gvisor/issues/173) |\n| top | Working |\n| wget | Working |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added nc, ip, and sshd. |
259,891 | 26.08.2019 16:32:00 | 25,200 | cc587e6039a3c6429d77e29ba8c8816583ef4c84 | ip route not quite submitted yet | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -48,7 +48,7 @@ old versions of ping, require excplicitly enabling raw sockets via the unsafe\n| dig | Working |\n| drill | Working |\n| gdb | Working |\n-| ip | Most commands not working. Some (e.g. addr) work |\n+| ip | Some subcommands work (e.g. addr) |\n| lsof | Working |\n| nc | Working |\n| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n"
}
] | Go | Apache License 2.0 | google/gvisor | ip route not quite submitted yet |
259,891 | 26.08.2019 16:33:28 | 25,200 | 6e350e809a8486e09eca9c9bae351270c8cfe907 | Added link for ss | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -55,7 +55,7 @@ old versions of ping, require excplicitly enabling raw sockets via the unsafe\n| nslookup | Working |\n| ping | Working |\n| ps | Working |\n-| ss | Working |\n+| ss | [In progress](https://github.com/google/gvisor/issues/506) |\n| sshd | Partially working. Job control [in progress](https://github.com/google/gvisor/issues/154) |\n| tcpdump | [In progress](https://github.com/google/gvisor/issues/173) |\n| top | Working |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added link for ss |
259,891 | 27.08.2019 10:14:25 | 25,200 | 942c740920785f70de2ab95efd249e2fd89acc43 | Added more tools. | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -36,29 +36,47 @@ The following applications/images have been tested:\n* tomcat\n* wordpress\n-## Debugging tools\n+## Utilities\n-Most common debugging utilities work. Note that some tools, such as tcpdump and\n-old versions of ping, require excplicitly enabling raw sockets via the unsafe\n+Most common utilities work. Note that some tools, such as tcpdump and old\n+versions of ping, require excplicitly enabling raw sockets via the unsafe\n`--net-raw` runsc flag. Specific tools include:\n| Tool | Status |\n| --- | --- |\n+| apt-get | Working |\n+| bundle | Working |\n+| cat | Working |\n| curl | Working |\n+| dd | Working |\n+| df | Working |\n| dig | Working |\n| drill | Working |\n+| env | Working |\n+| find | Working |\n| gdb | Working |\n+| gosu | Working |\n+| grep | Working (unless stdin is a pipe and stdout is /dev/null) |\n+| ifconfig | Works partially, like ip |\n| ip | Some subcommands work (e.g. addr) |\n+| less | Working |\n+| ls | Working |\n| lsof | Working |\n+| mount | Works in readonly mode. gVisor doesn't currently support creating new mounts at runtime |\n| nc | Working |\n| netstat | [In progress](https://github.com/google/gvisor/issues/506) |\n| nslookup | Working |\n| ping | Working |\n| ps | Working |\n+| route | Working |\n| ss | [In progress](https://github.com/google/gvisor/issues/506) |\n| sshd | Partially working. Job control [in progress](https://github.com/google/gvisor/issues/154) |\n+| strace | Working |\n+| tar | Working |\n| tcpdump | [In progress](https://github.com/google/gvisor/issues/173) |\n| top | Working |\n+| uptime | Working |\n+| vim | Working |\n| wget | Working |\n[bug]: https://github.com/google/gvisor/issues/new?title=Compatibility%20Issue:\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added more tools. |
259,891 | 27.08.2019 15:55:33 | 25,200 | e0ef639496db0205cec6752b482c30df0e64b80b | Added busybox note, changed route | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -38,9 +38,14 @@ The following applications/images have been tested:\n## Utilities\n-Most common utilities work. Note that some tools, such as tcpdump and old\n-versions of ping, require excplicitly enabling raw sockets via the unsafe\n-`--net-raw` runsc flag. Specific tools include:\n+Most common utilities work. Note that:\n+\n+* Some tools, such as `tcpdump` and old versions of `ping`, require explicitly\n+ enabling raw sockets via the unsafe `--net-raw` runsc flag.\n+* Different Docker images can behave differently. For example, Alpine Linux and\n+ Ubuntu have different `ip` binaries.\n+\n+ Specific tools include:\n| Tool | Status |\n| --- | --- |\n@@ -58,7 +63,7 @@ versions of ping, require excplicitly enabling raw sockets via the unsafe\n| gosu | Working |\n| grep | Working (unless stdin is a pipe and stdout is /dev/null) |\n| ifconfig | Works partially, like ip |\n-| ip | Some subcommands work (e.g. addr) |\n+| ip | Some subcommands work (e.g. addr, route) |\n| less | Working |\n| ls | Working |\n| lsof | Working |\n@@ -69,7 +74,7 @@ versions of ping, require excplicitly enabling raw sockets via the unsafe\n| nslookup | Working |\n| ping | Working |\n| ps | Working |\n-| route | Working |\n+| route | [In progress](https://github.com/google/gvisor/issues/764) |\n| ss | [In progress](https://github.com/google/gvisor/issues/506) |\n| sshd | Partially working. Job control [in progress](https://github.com/google/gvisor/issues/154) |\n| strace | Working |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Added busybox note, changed route |
259,884 | 29.08.2019 11:14:56 | 25,200 | 5c09a0e59e9a2abcc266bd0903a3a54eee81ff66 | Add link to ip bug | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/compatibility/_index.md",
"new_path": "content/docs/user_guide/compatibility/_index.md",
"diff": "@@ -63,7 +63,7 @@ Most common utilities work. Note that:\n| gosu | Working |\n| grep | Working (unless stdin is a pipe and stdout is /dev/null) |\n| ifconfig | Works partially, like ip |\n-| ip | Some subcommands work (e.g. addr, route) |\n+| ip | [In progress](https://github.com/google/gvisor/issues/769). Some subcommands work (e.g. addr, route) on alpine images. Not working on newest debian/ubuntu images. |\n| less | Working |\n| ls | Working |\n| lsof | Working |\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add link to ip bug |
259,885 | 29.08.2019 10:50:48 | 25,200 | 36a8949b2a52aabbe3f0548f1207c133da113c56 | Add limit_host_fd_translation Gofer mount option. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"new_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"diff": "@@ -66,10 +66,8 @@ type CachingInodeOperations struct {\n// mfp is used to allocate memory that caches backingFile's contents.\nmfp pgalloc.MemoryFileProvider\n- // forcePageCache indicates the sentry page cache should be used regardless\n- // of whether the platform supports host mapped I/O or not. This must not be\n- // modified after inode creation.\n- forcePageCache bool\n+ // opts contains options. opts is immutable.\n+ opts CachingInodeOperationsOptions\nattrMu sync.Mutex `state:\"nosave\"`\n@@ -116,6 +114,20 @@ type CachingInodeOperations struct {\nrefs frameRefSet\n}\n+// CachingInodeOperationsOptions configures a CachingInodeOperations.\n+//\n+// +stateify savable\n+type CachingInodeOperationsOptions struct {\n+ // If ForcePageCache is true, use the sentry page cache even if a host file\n+ // descriptor is available.\n+ ForcePageCache bool\n+\n+ // If LimitHostFDTranslation is true, apply maxFillRange() constraints to\n+ // host file descriptor mappings returned by\n+ // CachingInodeOperations.Translate().\n+ LimitHostFDTranslation bool\n+}\n+\n// CachedFileObject is a file that may require caching.\ntype CachedFileObject interface {\n// ReadToBlocksAt reads up to dsts.NumBytes() bytes from the file to dsts,\n@@ -159,7 +171,7 @@ type CachedFileObject interface {\n// NewCachingInodeOperations returns a new CachingInodeOperations backed by\n// a CachedFileObject and its initial unstable attributes.\n-func NewCachingInodeOperations(ctx context.Context, backingFile CachedFileObject, uattr fs.UnstableAttr, forcePageCache bool) *CachingInodeOperations {\n+func NewCachingInodeOperations(ctx context.Context, backingFile CachedFileObject, uattr fs.UnstableAttr, opts CachingInodeOperationsOptions) *CachingInodeOperations {\nmfp := pgalloc.MemoryFileProviderFromContext(ctx)\nif mfp == nil {\npanic(fmt.Sprintf(\"context.Context %T lacks non-nil value for key %T\", ctx, pgalloc.CtxMemoryFileProvider))\n@@ -167,7 +179,7 @@ func NewCachingInodeOperations(ctx context.Context, backingFile CachedFileObject\nreturn &CachingInodeOperations{\nbackingFile: backingFile,\nmfp: mfp,\n- forcePageCache: forcePageCache,\n+ opts: opts,\nattr: uattr,\nhostFileMapper: NewHostFileMapper(),\n}\n@@ -763,7 +775,7 @@ func (rw *inodeReadWriter) WriteFromBlocks(srcs safemem.BlockSeq) (uint64, error\n// and memory mappings, and false if c.cache may contain data cached from\n// c.backingFile.\nfunc (c *CachingInodeOperations) useHostPageCache() bool {\n- return !c.forcePageCache && c.backingFile.FD() >= 0\n+ return !c.opts.ForcePageCache && c.backingFile.FD() >= 0\n}\n// AddMapping implements memmap.Mappable.AddMapping.\n@@ -835,11 +847,15 @@ func (c *CachingInodeOperations) CopyMapping(ctx context.Context, ms memmap.Mapp\nfunc (c *CachingInodeOperations) Translate(ctx context.Context, required, optional memmap.MappableRange, at usermem.AccessType) ([]memmap.Translation, error) {\n// Hot path. Avoid defer.\nif c.useHostPageCache() {\n+ mr := optional\n+ if c.opts.LimitHostFDTranslation {\n+ mr = maxFillRange(required, optional)\n+ }\nreturn []memmap.Translation{\n{\n- Source: optional,\n+ Source: mr,\nFile: c,\n- Offset: optional.Start,\n+ Offset: mr.Start,\nPerms: usermem.AnyAccess,\n},\n}, nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/inode_cached_test.go",
"new_path": "pkg/sentry/fs/fsutil/inode_cached_test.go",
"diff": "@@ -61,7 +61,7 @@ func TestSetPermissions(t *testing.T) {\nuattr := fs.WithCurrentTime(ctx, fs.UnstableAttr{\nPerms: fs.FilePermsFromMode(0444),\n})\n- iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)\n+ iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, CachingInodeOperationsOptions{})\ndefer iops.Release()\nperms := fs.FilePermsFromMode(0777)\n@@ -150,7 +150,7 @@ func TestSetTimestamps(t *testing.T) {\nModificationTime: epoch,\nStatusChangeTime: epoch,\n}\n- iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)\n+ iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, CachingInodeOperationsOptions{})\ndefer iops.Release()\nif err := iops.SetTimestamps(ctx, nil, test.ts); err != nil {\n@@ -188,7 +188,7 @@ func TestTruncate(t *testing.T) {\nuattr := fs.UnstableAttr{\nSize: 0,\n}\n- iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)\n+ iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, CachingInodeOperationsOptions{})\ndefer iops.Release()\nif err := iops.Truncate(ctx, nil, uattr.Size); err != nil {\n@@ -280,7 +280,7 @@ func TestRead(t *testing.T) {\nuattr := fs.UnstableAttr{\nSize: int64(len(buf)),\n}\n- iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, false /*forcePageCache*/)\n+ iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, CachingInodeOperationsOptions{})\ndefer iops.Release()\n// Expect the cache to be initially empty.\n@@ -336,7 +336,7 @@ func TestWrite(t *testing.T) {\nuattr := fs.UnstableAttr{\nSize: int64(len(buf)),\n}\n- iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, false /*forcePageCache*/)\n+ iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, CachingInodeOperationsOptions{})\ndefer iops.Release()\n// Expect the cache to be initially empty.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/fs.go",
"new_path": "pkg/sentry/fs/gofer/fs.go",
"diff": "@@ -54,6 +54,10 @@ const (\n// sandbox using files backed by the gofer. If set to false, unix sockets\n// cannot be bound to gofer files without an overlay on top.\nprivateUnixSocketKey = \"privateunixsocket\"\n+\n+ // If present, sets CachingInodeOperationsOptions.LimitHostFDTranslation to\n+ // true.\n+ limitHostFDTranslationKey = \"limit_host_fd_translation\"\n)\n// defaultAname is the default attach name.\n@@ -140,6 +144,7 @@ type opts struct {\nmsize uint32\nversion string\nprivateunixsocket bool\n+ limitHostFDTranslation bool\n}\n// options parses mount(2) data into structured options.\n@@ -237,6 +242,11 @@ func options(data string) (opts, error) {\ndelete(options, privateUnixSocketKey)\n}\n+ if _, ok := options[limitHostFDTranslationKey]; ok {\n+ o.limitHostFDTranslation = true\n+ delete(options, limitHostFDTranslationKey)\n+ }\n+\n// Fail to attach if the caller wanted us to do something that we\n// don't support.\nif len(options) > 0 {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/gofer/session.go",
"new_path": "pkg/sentry/fs/gofer/session.go",
"diff": "@@ -117,6 +117,11 @@ type session struct {\n// Flags provided to the mount.\nsuperBlockFlags fs.MountSourceFlags `state:\"wait\"`\n+ // limitHostFDTranslation is the value used for\n+ // CachingInodeOperationsOptions.LimitHostFDTranslation for all\n+ // CachingInodeOperations created by the session.\n+ limitHostFDTranslation bool\n+\n// connID is a unique identifier for the session connection.\nconnID string `state:\"wait\"`\n@@ -219,7 +224,10 @@ func newInodeOperations(ctx context.Context, s *session, file contextFile, qid p\nuattr := unstable(ctx, valid, attr, s.mounter, s.client)\nreturn sattr, &inodeOperations{\nfileState: fileState,\n- cachingInodeOps: fsutil.NewCachingInodeOperations(ctx, fileState, uattr, s.superBlockFlags.ForcePageCache),\n+ cachingInodeOps: fsutil.NewCachingInodeOperations(ctx, fileState, uattr, fsutil.CachingInodeOperationsOptions{\n+ ForcePageCache: s.superBlockFlags.ForcePageCache,\n+ LimitHostFDTranslation: s.limitHostFDTranslation,\n+ }),\n}\n}\n@@ -248,6 +256,7 @@ func Root(ctx context.Context, dev string, filesystem fs.Filesystem, superBlockF\ncachePolicy: o.policy,\naname: o.aname,\nsuperBlockFlags: superBlockFlags,\n+ limitHostFDTranslation: o.limitHostFDTranslation,\nmounter: mounter,\n}\ns.EnableLeakCheck(\"gofer.session\")\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/host/inode.go",
"new_path": "pkg/sentry/fs/host/inode.go",
"diff": "@@ -201,7 +201,9 @@ func newInode(ctx context.Context, msrc *fs.MountSource, fd int, saveable bool,\nuattr := unstableAttr(msrc.MountSourceOperations.(*superOperations), &s)\niops := &inodeOperations{\nfileState: fileState,\n- cachingInodeOps: fsutil.NewCachingInodeOperations(ctx, fileState, uattr, msrc.Flags.ForcePageCache),\n+ cachingInodeOps: fsutil.NewCachingInodeOperations(ctx, fileState, uattr, fsutil.CachingInodeOperationsOptions{\n+ ForcePageCache: msrc.Flags.ForcePageCache,\n+ }),\n}\n// Return the fs.Inode.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add limit_host_fd_translation Gofer mount option.
PiperOrigin-RevId: 266177409 |
259,985 | 29.08.2019 14:31:44 | 25,200 | f74affe2035ba038674a0b958d8a31348fba15bc | Handle new representation of abstract UDS paths.
When abstract unix domain socket paths are displayed in
/proc/net/unix, Linux historically emitted null bytes as padding at
the end of the path. Newer versions of Linux (v4.9,
e7947ea770d0de434d38a0f823e660d3fd4bebb5) display these as '@'
characters.
Update proc_net_unix test to handle both version of the padding. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net_unix.cc",
"new_path": "test/syscalls/linux/proc_net_unix.cc",
"diff": "@@ -56,19 +56,44 @@ struct UnixEntry {\nstd::string path;\n};\n+// Abstract socket paths can have either trailing null bytes or '@'s as padding\n+// at the end, depending on the linux version. This function strips any such\n+// padding.\n+void StripAbstractPathPadding(std::string* s) {\n+ const char pad_char = s->back();\n+ if (pad_char != '\\0' && pad_char != '@') {\n+ return;\n+ }\n+\n+ const auto last_pos = s->find_last_not_of(pad_char);\n+ if (last_pos != std::string::npos) {\n+ s->resize(last_pos + 1);\n+ }\n+}\n+\n+// Precondition: addr must be a unix socket address (i.e. sockaddr_un) and\n+// addr->sun_path must be null-terminated. This is always the case if addr comes\n+// from Linux:\n+//\n+// Per man unix(7):\n+//\n+// \"When the address of a pathname socket is returned (by [getsockname(2)]), its\n+// length is\n+//\n+// offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1\n+//\n+// and sun_path contains the null-terminated pathname.\"\nstd::string ExtractPath(const struct sockaddr* addr) {\nconst char* path =\nreinterpret_cast<const struct sockaddr_un*>(addr)->sun_path;\n// Note: sockaddr_un.sun_path is an embedded character array of length\n// UNIX_PATH_MAX, so we can always safely dereference the first 2 bytes below.\n//\n- // The kernel also enforces that the path is always null terminated.\n+ // We also rely on the path being null-terminated.\nif (path[0] == 0) {\n- // Abstract socket paths are null padded to the end of the struct\n- // sockaddr. However, these null bytes may or may not show up in\n- // /proc/net/unix depending on the kernel version. Truncate after the first\n- // null byte (by treating path as a c-string).\n- return StrCat(\"@\", &path[1]);\n+ std::string abstract_path = StrCat(\"@\", &path[1]);\n+ StripAbstractPathPadding(&abstract_path);\n+ return abstract_path;\n}\nreturn std::string(path);\n}\n@@ -96,14 +121,6 @@ PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() {\ncontinue;\n}\n- // Abstract socket paths can have trailing null bytes in them depending on\n- // the linux version. Strip off everything after a null byte, including the\n- // null byte.\n- std::size_t null_pos = line.find('\\0');\n- if (null_pos != std::string::npos) {\n- line.erase(null_pos);\n- }\n-\n// Parse a single entry from /proc/net/unix.\n//\n// Sample file:\n@@ -151,6 +168,7 @@ PosixErrorOr<std::vector<UnixEntry>> ProcNetUnixEntries() {\nentry.path = \"\";\nif (fields.size() > 1) {\nentry.path = fields[1];\n+ StripAbstractPathPadding(&entry.path);\n}\nentries.push_back(entry);\n@@ -200,8 +218,8 @@ TEST(ProcNetUnix, FilesystemBindAcceptConnect) {\nstd::string path1 = ExtractPath(sockets->first_addr());\nstd::string path2 = ExtractPath(sockets->second_addr());\n- std::cout << StreamFormat(\"Server socket address: %s\\n\", path1);\n- std::cout << StreamFormat(\"Client socket address: %s\\n\", path2);\n+ std::cerr << StreamFormat(\"Server socket address (path1): %s\\n\", path1);\n+ std::cerr << StreamFormat(\"Client socket address (path2): %s\\n\", path2);\nstd::vector<UnixEntry> entries =\nASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n@@ -224,8 +242,8 @@ TEST(ProcNetUnix, AbstractBindAcceptConnect) {\nstd::string path1 = ExtractPath(sockets->first_addr());\nstd::string path2 = ExtractPath(sockets->second_addr());\n- std::cout << StreamFormat(\"Server socket address: '%s'\\n\", path1);\n- std::cout << StreamFormat(\"Client socket address: '%s'\\n\", path2);\n+ std::cerr << StreamFormat(\"Server socket address (path1): '%s'\\n\", path1);\n+ std::cerr << StreamFormat(\"Client socket address (path2): '%s'\\n\", path2);\nstd::vector<UnixEntry> entries =\nASSERT_NO_ERRNO_AND_VALUE(ProcNetUnixEntries());\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle new representation of abstract UDS paths.
When abstract unix domain socket paths are displayed in
/proc/net/unix, Linux historically emitted null bytes as padding at
the end of the path. Newer versions of Linux (v4.9,
e7947ea770d0de434d38a0f823e660d3fd4bebb5) display these as '@'
characters.
Update proc_net_unix test to handle both version of the padding.
PiperOrigin-RevId: 266230200 |
259,858 | 30.08.2019 15:01:55 | 25,200 | 888e87909e1a6c3cf93498e6ecb2d451c7551153 | Add C++ toolchain and fix compile issues.
This was accidentally introduced in
Fixes | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -32,6 +32,17 @@ load(\"@bazel_gazelle//:deps.bzl\", \"gazelle_dependencies\", \"go_repository\")\ngazelle_dependencies()\n+# Load C++ rules.\n+http_archive(\n+ name = \"rules_cc\",\n+ sha256 = \"67412176974bfce3f4cf8bdaff39784a72ed709fc58def599d1f68710b58d68b\",\n+ strip_prefix = \"rules_cc-b7fe9697c0c76ab2fd431a891dbb9a6a32ed7c3e\",\n+ urls = [\n+ \"https://mirror.bazel.build/github.com/bazelbuild/rules_cc/archive/b7fe9697c0c76ab2fd431a891dbb9a6a32ed7c3e.zip\",\n+ \"https://github.com/bazelbuild/rules_cc/archive/b7fe9697c0c76ab2fd431a891dbb9a6a32ed7c3e.zip\",\n+ ],\n+)\n+\n# Load protobuf dependencies.\nload(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"git_repository\")\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1213,6 +1213,7 @@ cc_binary(\n\"//test/util:test_main\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n+ \"@com_google_absl//absl/memory\",\n\"@com_google_absl//absl/strings\",\n\"@com_google_googletest//:gtest\",\n],\n@@ -3362,6 +3363,7 @@ cc_binary(\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n\"@com_google_absl//absl/base:core_headers\",\n+ \"@com_google_absl//absl/memory\",\n\"@com_google_absl//absl/synchronization\",\n\"@com_google_absl//absl/time\",\n\"@com_google_googletest//:gtest\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/open.cc",
"new_path": "test/syscalls/linux/open.cc",
"diff": "#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n+#include \"absl/memory/memory.h\"\n#include \"test/syscalls/linux/file_base.h\"\n#include \"test/util/capability_util.h\"\n#include \"test/util/cleanup.h\"\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1292,10 +1292,8 @@ TEST_F(JobControlTest, ReleaseTTY) {\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect they TTY.\n- struct sigaction sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\nsigemptyset(&sa.sa_mask);\nstruct sigaction old_sa;\nEXPECT_THAT(sigaction(SIGHUP, &sa, &old_sa), SyscallSucceeds());\n@@ -1362,10 +1360,8 @@ TEST_F(JobControlTest, ReleaseTTYSignals) {\nASSERT_THAT(ioctl(slave_.get(), TIOCSCTTY, 0), SyscallSucceeds());\nreceived = 0;\n- struct sigaction sa = {\n- .sa_handler = sig_handler,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = sig_handler;\nsigemptyset(&sa.sa_mask);\nsigaddset(&sa.sa_mask, SIGHUP);\nsigaddset(&sa.sa_mask, SIGCONT);\n@@ -1403,10 +1399,8 @@ TEST_F(JobControlTest, ReleaseTTYSignals) {\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect they TTY.\n- struct sigaction sighup_sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sighup_sa = {};\n+ sighup_sa.sa_handler = SIG_IGN;\nsigemptyset(&sighup_sa.sa_mask);\nstruct sigaction old_sa;\nEXPECT_THAT(sigaction(SIGHUP, &sighup_sa, &old_sa), SyscallSucceeds());\n@@ -1456,10 +1450,8 @@ TEST_F(JobControlTest, SetForegroundProcessGroup) {\nASSERT_THAT(ioctl(slave_.get(), TIOCSCTTY, 0), SyscallSucceeds());\n// Ignore SIGTTOU so that we don't stop ourself when calling tcsetpgrp.\n- struct sigaction sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\nsigemptyset(&sa.sa_mask);\nsigaction(SIGTTOU, &sa, NULL);\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/semaphore.cc",
"new_path": "test/syscalls/linux/semaphore.cc",
"diff": "#include <sys/ipc.h>\n#include <sys/sem.h>\n#include <sys/types.h>\n+\n#include <atomic>\n#include <cerrno>\n#include <ctime>\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"absl/base/macros.h\"\n+#include \"absl/memory/memory.h\"\n#include \"absl/synchronization/mutex.h\"\n#include \"absl/time/clock.h\"\n#include \"test/util/capability_util.h\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add C++ toolchain and fix compile issues.
This was accidentally introduced in 31f05d5d4f62c4cd4fe3b95b333d0130aae4b2c1.
Fixes #788.
PiperOrigin-RevId: 266462843 |
259,858 | 30.08.2019 15:26:26 | 25,200 | 3ec0b64d8c7d1649fd06291f3b5d0a3ca6db98d6 | Update image to install docker and fix permissions | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1604/25_docker.sh",
"diff": "+#!/bin/bash\n+\n+# Copyright 2019 The gVisor Authors.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+# Add dependencies.\n+apt-get update && apt-get -y install \\\n+ apt-transport-https \\\n+ ca-certificates \\\n+ curl \\\n+ gnupg-agent \\\n+ software-properties-common\n+\n+# Install the key.\n+curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -\n+\n+# Add the repository.\n+add-apt-repository \\\n+ \"deb [arch=amd64] https://download.docker.com/linux/ubuntu \\\n+ $(lsb_release -cs) \\\n+ stable\"\n+\n+# Install docker.\n+apt-get update && apt-get install -y docker-ce docker-ce-cli containerd.io\n"
},
{
"change_type": "MODIFY",
"old_path": "kokoro/ubuntu1604/40_kokoro.sh",
"new_path": "kokoro/ubuntu1604/40_kokoro.sh",
"diff": "@@ -23,7 +23,7 @@ declare -r ssh_public_keys=(\n)\n# Install dependencies.\n-apt-get update && apt-get install -y rsync coreutils python-psutil\n+apt-get update && apt-get install -y rsync coreutils python-psutil qemu-kvm\n# We need a kbuilder user.\nif useradd -c \"kbuilder user\" -m -s /bin/bash kbuilder; then\n@@ -39,6 +39,12 @@ cat > /etc/sudoers.d/kokoro <<EOF\nkbuilder ALL=(ALL) NOPASSWD:ALL\nEOF\n+# Ensure we can run Docker without sudo.\n+usermod -aG docker kbuilder\n+\n+# Ensure that we can access kvm.\n+usermod -aG kvm kbuilder\n+\n# Ensure that /tmpfs exists and is writable by kokoro.\n#\n# Note that kokoro will typically attach a second disk (sdb) to the instance\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "kokoro/ubuntu1804/25_docker.sh",
"diff": "+../ubuntu1604/25_docker.sh\n\\ No newline at end of file\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update image to install docker and fix permissions
PiperOrigin-RevId: 266467361 |
259,992 | 30.08.2019 17:17:45 | 25,200 | 502c47f7a70a088213faf27b60e6f62ece4dd765 | Return correct buffer size for ioctl(socket, FIONREAD)
Ioctl was returning just the buffer size from epsocket.endpoint
and it was not considering data from epsocket.SocketOperations
that was read from the endpoint, but not yet sent to the caller. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -2104,7 +2104,8 @@ func (s *SocketOperations) Ioctl(ctx context.Context, _ *fs.File, io usermem.IO,\n// SIOCGSTAMP is implemented by epsocket rather than all commonEndpoint\n// sockets.\n// TODO(b/78348848): Add a commonEndpoint method to support SIOCGSTAMP.\n- if int(args[1].Int()) == syscall.SIOCGSTAMP {\n+ switch args[1].Int() {\n+ case syscall.SIOCGSTAMP:\ns.readMu.Lock()\ndefer s.readMu.Unlock()\nif !s.timestampValid {\n@@ -2116,6 +2117,25 @@ func (s *SocketOperations) Ioctl(ctx context.Context, _ *fs.File, io usermem.IO,\nAddressSpaceActive: true,\n})\nreturn 0, err\n+\n+ case linux.TIOCINQ:\n+ v, terr := s.Endpoint.GetSockOptInt(tcpip.ReceiveQueueSizeOption)\n+ if terr != nil {\n+ return 0, syserr.TranslateNetstackError(terr).ToError()\n+ }\n+\n+ // Add bytes removed from the endpoint but not yet sent to the caller.\n+ v += len(s.readView)\n+\n+ if v > math.MaxInt32 {\n+ v = math.MaxInt32\n+ }\n+\n+ // Copy result to user-space.\n+ _, err := usermem.CopyObjectOut(ctx, io, args[2].Pointer(), int32(v), usermem.IOOpts{\n+ AddressSpaceActive: true,\n+ })\n+ return 0, err\n}\nreturn Ioctl(ctx, s.Endpoint, io, args)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/tcp_socket.cc",
"new_path": "test/syscalls/linux/tcp_socket.cc",
"diff": "@@ -579,7 +579,7 @@ TEST_P(TcpSocketTest, TcpInq) {\nif (size == sizeof(buf)) {\nbreak;\n}\n- usleep(10000);\n+ absl::SleepFor(absl::Milliseconds(10));\n}\nstruct msghdr msg = {};\n@@ -610,6 +610,25 @@ TEST_P(TcpSocketTest, TcpInq) {\n}\n}\n+TEST_P(TcpSocketTest, Tiocinq) {\n+ char buf[1024];\n+ size_t size = sizeof(buf);\n+ ASSERT_THAT(RetryEINTR(write)(s_, buf, size), SyscallSucceedsWithValue(size));\n+\n+ uint32_t seed = time(nullptr);\n+ const size_t max_chunk = size / 10;\n+ while (size > 0) {\n+ size_t chunk = (rand_r(&seed) % max_chunk) + 1;\n+ ssize_t read = RetryEINTR(recvfrom)(t_, buf, chunk, 0, nullptr, nullptr);\n+ ASSERT_THAT(read, SyscallSucceeds());\n+ size -= read;\n+\n+ int inq = 0;\n+ ASSERT_THAT(ioctl(t_, TIOCINQ, &inq), SyscallSucceeds());\n+ ASSERT_EQ(inq, size);\n+ }\n+}\n+\nTEST_P(TcpSocketTest, TcpSCMPriority) {\nchar buf[1024];\nASSERT_THAT(RetryEINTR(write)(s_, buf, sizeof(buf)),\n"
}
] | Go | Apache License 2.0 | google/gvisor | Return correct buffer size for ioctl(socket, FIONREAD)
Ioctl was returning just the buffer size from epsocket.endpoint
and it was not considering data from epsocket.SocketOperations
that was read from the endpoint, but not yet sent to the caller.
PiperOrigin-RevId: 266485461 |
260,006 | 30.08.2019 17:18:05 | 25,200 | afbdf2f212739880e70a5450a9292e3265caecba | Fix data race accessing referencedNetworkEndpoint.kind
Wrapping "kind" into atomic access functions.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -139,7 +139,7 @@ func (n *NIC) getMainNICAddress(protocol tcpip.NetworkProtocolNumber) (tcpip.Add\nif list, ok := n.primary[protocol]; ok {\nfor e := list.Front(); e != nil; e = e.Next() {\nref := e.(*referencedNetworkEndpoint)\n- if ref.kind == permanent && ref.tryIncRef() {\n+ if ref.getKind() == permanent && ref.tryIncRef() {\nr = ref\nbreak\n}\n@@ -205,7 +205,7 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\nif ref, ok := n.endpoints[id]; ok {\n// An endpoint with this id exists, check if it can be used and return it.\n- switch ref.kind {\n+ switch ref.getKind() {\ncase permanentExpired:\nif !spoofingOrPromiscuous {\nn.mu.RUnlock()\n@@ -276,14 +276,14 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\nfunc (n *NIC) addPermanentAddressLocked(protocolAddress tcpip.ProtocolAddress, peb PrimaryEndpointBehavior) (*referencedNetworkEndpoint, *tcpip.Error) {\nid := NetworkEndpointID{protocolAddress.AddressWithPrefix.Address}\nif ref, ok := n.endpoints[id]; ok {\n- switch ref.kind {\n+ switch ref.getKind() {\ncase permanent:\n// The NIC already have a permanent endpoint with that address.\nreturn nil, tcpip.ErrDuplicateAddress\ncase permanentExpired, temporary:\n// Promote the endpoint to become permanent.\nif ref.tryIncRef() {\n- ref.kind = permanent\n+ ref.setKind(permanent)\nreturn ref, nil\n}\n// tryIncRef failing means the endpoint is scheduled to be removed once\n@@ -366,7 +366,7 @@ func (n *NIC) Addresses() []tcpip.ProtocolAddress {\nfor nid, ref := range n.endpoints {\n// Don't include expired or tempory endpoints to avoid confusion and\n// prevent the caller from using those.\n- switch ref.kind {\n+ switch ref.getKind() {\ncase permanentExpired, temporary:\ncontinue\n}\n@@ -444,7 +444,7 @@ func (n *NIC) removeEndpointLocked(r *referencedNetworkEndpoint) {\nreturn\n}\n- if r.kind == permanent {\n+ if r.getKind() == permanent {\npanic(\"Reference count dropped to zero before being removed\")\n}\n@@ -465,11 +465,11 @@ func (n *NIC) removeEndpoint(r *referencedNetworkEndpoint) {\nfunc (n *NIC) removePermanentAddressLocked(addr tcpip.Address) *tcpip.Error {\nr := n.endpoints[NetworkEndpointID{addr}]\n- if r == nil || r.kind != permanent {\n+ if r == nil || r.getKind() != permanent {\nreturn tcpip.ErrBadLocalAddress\n}\n- r.kind = permanentExpired\n+ r.setKind(permanentExpired)\nr.decRefLocked()\nreturn nil\n@@ -720,7 +720,7 @@ func (n *NIC) ID() tcpip.NICID {\nreturn n.id\n}\n-type networkEndpointKind int\n+type networkEndpointKind int32\nconst (\n// A permanent endpoint is created by adding a permanent address (vs. a\n@@ -759,21 +759,30 @@ type referencedNetworkEndpoint struct {\n// triggers the automatic removal of the endpoint from the NIC.\nrefs int32\n+ // networkEndpointKind must only be accessed using {get,set}Kind().\nkind networkEndpointKind\n}\n+func (r *referencedNetworkEndpoint) getKind() networkEndpointKind {\n+ return networkEndpointKind(atomic.LoadInt32((*int32)(&r.kind)))\n+}\n+\n+func (r *referencedNetworkEndpoint) setKind(kind networkEndpointKind) {\n+ atomic.StoreInt32((*int32)(&r.kind), int32(kind))\n+}\n+\n// isValidForOutgoing returns true if the endpoint can be used to send out a\n// packet. It requires the endpoint to not be marked expired (i.e., its address\n// has been removed), or the NIC to be in spoofing mode.\nfunc (r *referencedNetworkEndpoint) isValidForOutgoing() bool {\n- return r.kind != permanentExpired || r.nic.spoofing\n+ return r.getKind() != permanentExpired || r.nic.spoofing\n}\n// isValidForIncoming returns true if the endpoint can accept an incoming\n// packet. It requires the endpoint to not be marked expired (i.e., its address\n// has been removed), or the NIC to be in promiscuous mode.\nfunc (r *referencedNetworkEndpoint) isValidForIncoming() bool {\n- return r.kind != permanentExpired || r.nic.promiscuous\n+ return r.getKind() != permanentExpired || r.nic.promiscuous\n}\n// decRef decrements the ref count and cleans up the endpoint once it reaches\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix data race accessing referencedNetworkEndpoint.kind
Wrapping "kind" into atomic access functions.
Fixes #789
PiperOrigin-RevId: 266485501 |
259,885 | 30.08.2019 18:09:25 | 25,200 | f3dabdfc486874edc986ff63abe74ec1c85e18e1 | Fix async-signal-unsafety in MlockallTest_Future. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/mlock.cc",
"new_path": "test/syscalls/linux/mlock.cc",
"diff": "@@ -169,26 +169,24 @@ TEST(MlockallTest, Future) {\n// Run this test in a separate (single-threaded) subprocess to ensure that a\n// background thread doesn't try to mmap a large amount of memory, fail due\n// to hitting RLIMIT_MEMLOCK, and explode the process violently.\n- EXPECT_THAT(InForkedProcess([] {\n+ auto const do_test = [] {\nauto const mapping =\n- MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE)\n- .ValueOrDie();\n+ MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE).ValueOrDie();\nTEST_CHECK(!IsPageMlocked(mapping.addr()));\nTEST_PCHECK(mlockall(MCL_FUTURE) == 0);\n- // Ensure that mlockall(MCL_FUTURE) is turned off before the end\n- // of the test, as otherwise mmaps may fail unexpectedly.\n+ // Ensure that mlockall(MCL_FUTURE) is turned off before the end of the\n+ // test, as otherwise mmaps may fail unexpectedly.\nCleanup do_munlockall([] { TEST_PCHECK(munlockall() == 0); });\n- auto const mapping2 = ASSERT_NO_ERRNO_AND_VALUE(\n- MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n+ auto const mapping2 =\n+ MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE).ValueOrDie();\nTEST_CHECK(IsPageMlocked(mapping2.addr()));\n- // Fire munlockall() and check that it disables\n- // mlockall(MCL_FUTURE).\n+ // Fire munlockall() and check that it disables mlockall(MCL_FUTURE).\ndo_munlockall.Release()();\n- auto const mapping3 = ASSERT_NO_ERRNO_AND_VALUE(\n- MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE));\n+ auto const mapping3 =\n+ MmapAnon(kPageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE).ValueOrDie();\nTEST_CHECK(!IsPageMlocked(mapping2.addr()));\n- }),\n- IsPosixErrorOkAndHolds(0));\n+ };\n+ EXPECT_THAT(InForkedProcess(do_test), IsPosixErrorOkAndHolds(0));\n}\nTEST(MunlockallTest, Basic) {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix async-signal-unsafety in MlockallTest_Future.
PiperOrigin-RevId: 266491246 |
259,885 | 30.08.2019 19:05:30 | 25,200 | 0352cf5866ddb5eea24fa35c69e2e43038cfb60a | Remove support for non-incremental mapped accounting. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"new_path": "pkg/sentry/fs/fsutil/inode_cached.go",
"diff": "@@ -796,11 +796,6 @@ func (c *CachingInodeOperations) AddMapping(ctx context.Context, ms memmap.Mappi\nmf.MarkUnevictable(c, pgalloc.EvictableRange{r.Start, r.End})\n}\n}\n- if c.useHostPageCache() && !usage.IncrementalMappedAccounting {\n- for _, r := range mapped {\n- usage.MemoryAccounting.Inc(r.Length(), usage.Mapped)\n- }\n- }\nc.mapsMu.Unlock()\nreturn nil\n}\n@@ -814,11 +809,6 @@ func (c *CachingInodeOperations) RemoveMapping(ctx context.Context, ms memmap.Ma\nc.hostFileMapper.DecRefOn(r)\n}\nif c.useHostPageCache() {\n- if !usage.IncrementalMappedAccounting {\n- for _, r := range unmapped {\n- usage.MemoryAccounting.Dec(r.Length(), usage.Mapped)\n- }\n- }\nc.mapsMu.Unlock()\nreturn\n}\n@@ -1001,9 +991,7 @@ func (c *CachingInodeOperations) IncRef(fr platform.FileRange) {\nseg, gap = seg.NextNonEmpty()\ncase gap.Ok() && gap.Start() < fr.End:\nnewRange := gap.Range().Intersect(fr)\n- if usage.IncrementalMappedAccounting {\nusage.MemoryAccounting.Inc(newRange.Length(), usage.Mapped)\n- }\nseg, gap = c.refs.InsertWithoutMerging(gap, newRange, 1).NextNonEmpty()\ndefault:\nc.refs.MergeAdjacent(fr)\n@@ -1024,9 +1012,7 @@ func (c *CachingInodeOperations) DecRef(fr platform.FileRange) {\nfor seg.Ok() && seg.Start() < fr.End {\nseg = c.refs.Isolate(seg, fr)\nif old := seg.Value(); old == 1 {\n- if usage.IncrementalMappedAccounting {\nusage.MemoryAccounting.Dec(seg.Range().Length(), usage.Mapped)\n- }\nseg = c.refs.Remove(seg).NextSegment()\n} else {\nseg.SetValue(old - 1)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/usage/memory.go",
"new_path": "pkg/sentry/usage/memory.go",
"diff": "@@ -277,8 +277,3 @@ func TotalMemory(memSize, used uint64) uint64 {\n}\nreturn memSize\n}\n-\n-// IncrementalMappedAccounting controls whether host mapped memory is accounted\n-// incrementally during map translation. This may be modified during early\n-// initialization, and is read-only afterward.\n-var IncrementalMappedAccounting = false\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove support for non-incremental mapped accounting.
PiperOrigin-RevId: 266496644 |
259,885 | 03.09.2019 15:09:34 | 25,200 | eb94066ef26fc95d6b645124642b4f1248ad5e11 | Ensure that flipcall.Endpoint.Shutdown() shuts down inactive peers. | [
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/ctrl_futex.go",
"new_path": "pkg/flipcall/ctrl_futex.go",
"diff": "@@ -121,7 +121,16 @@ func (ep *Endpoint) enterFutexWait() error {\n}\nfunc (ep *Endpoint) exitFutexWait() {\n- atomic.AddInt32(&ep.ctrl.state, -epsBlocked)\n+ switch eps := atomic.AddInt32(&ep.ctrl.state, -epsBlocked); eps {\n+ case 0:\n+ return\n+ case epsShutdown:\n+ // ep.ctrlShutdown() was called while we were blocked, so we are\n+ // repsonsible for indicating connection shutdown.\n+ ep.shutdownConn()\n+ default:\n+ panic(fmt.Sprintf(\"invalid flipcall.Endpoint.ctrl.state after flipcall.Endpoint.exitFutexWait(): %v\", eps+epsBlocked))\n+ }\n}\nfunc (ep *Endpoint) ctrlShutdown() {\n@@ -142,5 +151,25 @@ func (ep *Endpoint) ctrlShutdown() {\nbreak\n}\n}\n+ } else {\n+ // There is no blocked thread, so we are responsible for indicating\n+ // connection shutdown.\n+ ep.shutdownConn()\n+ }\n+}\n+\n+func (ep *Endpoint) shutdownConn() {\n+ switch cs := atomic.SwapUint32(ep.connState(), csShutdown); cs {\n+ case ep.activeState:\n+ if err := ep.futexWakeConnState(1); err != nil {\n+ log.Warningf(\"failed to FUTEX_WAKE peer Endpoint for shutdown: %v\", err)\n+ }\n+ case ep.inactiveState:\n+ // The peer is currently active and will detect shutdown when it tries\n+ // to update the connection state.\n+ case csShutdown:\n+ // The peer also called Endpoint.Shutdown().\n+ default:\n+ log.Warningf(\"unexpected connection state before Endpoint.shutdownConn(): %v\", cs)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/flipcall.go",
"new_path": "pkg/flipcall/flipcall.go",
"diff": "@@ -42,11 +42,6 @@ type Endpoint struct {\n// dataCap is immutable.\ndataCap uint32\n- // shutdown is non-zero if Endpoint.Shutdown() has been called, or if the\n- // Endpoint has acknowledged shutdown initiated by the peer. shutdown is\n- // accessed using atomic memory operations.\n- shutdown uint32\n-\n// activeState is csClientActive if this is a client Endpoint and\n// csServerActive if this is a server Endpoint.\nactiveState uint32\n@@ -55,9 +50,27 @@ type Endpoint struct {\n// csClientActive if this is a server Endpoint.\ninactiveState uint32\n+ // shutdown is non-zero if Endpoint.Shutdown() has been called, or if the\n+ // Endpoint has acknowledged shutdown initiated by the peer. shutdown is\n+ // accessed using atomic memory operations.\n+ shutdown uint32\n+\nctrl endpointControlImpl\n}\n+// EndpointSide indicates which side of a connection an Endpoint belongs to.\n+type EndpointSide int\n+\n+const (\n+ // ClientSide indicates that an Endpoint is a client (initially-active;\n+ // first method call should be Connect).\n+ ClientSide EndpointSide = iota\n+\n+ // ServerSide indicates that an Endpoint is a server (initially-inactive;\n+ // first method call should be RecvFirst.)\n+ ServerSide\n+)\n+\n// Init must be called on zero-value Endpoints before first use. If it\n// succeeds, ep.Destroy() must be called once the Endpoint is no longer in use.\n//\n@@ -65,7 +78,17 @@ type Endpoint struct {\n// Endpoint. FD may differ between Endpoints if they are in different\n// processes, but must represent the same file. The packet window must\n// initially be filled with zero bytes.\n-func (ep *Endpoint) Init(pwd PacketWindowDescriptor, opts ...EndpointOption) error {\n+func (ep *Endpoint) Init(side EndpointSide, pwd PacketWindowDescriptor, opts ...EndpointOption) error {\n+ switch side {\n+ case ClientSide:\n+ ep.activeState = csClientActive\n+ ep.inactiveState = csServerActive\n+ case ServerSide:\n+ ep.activeState = csServerActive\n+ ep.inactiveState = csClientActive\n+ default:\n+ return fmt.Errorf(\"invalid EndpointSide: %v\", side)\n+ }\nif pwd.Length < pageSize {\nreturn fmt.Errorf(\"packet window size (%d) less than minimum (%d)\", pwd.Length, pageSize)\n}\n@@ -78,9 +101,6 @@ func (ep *Endpoint) Init(pwd PacketWindowDescriptor, opts ...EndpointOption) err\n}\nep.packet = m\nep.dataCap = uint32(pwd.Length) - uint32(PacketHeaderBytes)\n- // These will be overwritten by ep.Connect() for client Endpoints.\n- ep.activeState = csServerActive\n- ep.inactiveState = csClientActive\nif err := ep.ctrlInit(opts...); err != nil {\nep.unmapPacket()\nreturn err\n@@ -90,9 +110,9 @@ func (ep *Endpoint) Init(pwd PacketWindowDescriptor, opts ...EndpointOption) err\n// NewEndpoint is a convenience function that returns an initialized Endpoint\n// allocated on the heap.\n-func NewEndpoint(pwd PacketWindowDescriptor, opts ...EndpointOption) (*Endpoint, error) {\n+func NewEndpoint(side EndpointSide, pwd PacketWindowDescriptor, opts ...EndpointOption) (*Endpoint, error) {\nvar ep Endpoint\n- if err := ep.Init(pwd, opts...); err != nil {\n+ if err := ep.Init(side, pwd, opts...); err != nil {\nreturn nil, err\n}\nreturn &ep, nil\n@@ -115,9 +135,9 @@ func (ep *Endpoint) unmapPacket() {\n}\n// Shutdown causes concurrent and future calls to ep.Connect(), ep.SendRecv(),\n-// ep.RecvFirst(), and ep.SendLast() to unblock and return errors. It does not\n-// wait for concurrent calls to return. The effect of Shutdown on the peer\n-// Endpoint is unspecified. Successive calls to Shutdown have no effect.\n+// ep.RecvFirst(), and ep.SendLast(), as well as the same calls in the peer\n+// Endpoint, to unblock and return errors. It does not wait for concurrent\n+// calls to return. Successive calls to Shutdown have no effect.\n//\n// Shutdown is the only Endpoint method that may be called concurrently with\n// other methods on the same Endpoint.\n@@ -152,24 +172,22 @@ const (\n// The client is, by definition, initially active, so this must be 0.\ncsClientActive = 0\ncsServerActive = 1\n+ csShutdown = 2\n)\n-// Connect designates ep as a client Endpoint and blocks until the peer\n-// Endpoint has called Endpoint.RecvFirst().\n+// Connect blocks until the peer Endpoint has called Endpoint.RecvFirst().\n//\n-// Preconditions: ep.Connect(), ep.RecvFirst(), ep.SendRecv(), and\n-// ep.SendLast() have never been called.\n+// Preconditions: ep is a client Endpoint. ep.Connect(), ep.RecvFirst(),\n+// ep.SendRecv(), and ep.SendLast() have never been called.\nfunc (ep *Endpoint) Connect() error {\n- ep.activeState = csClientActive\n- ep.inactiveState = csServerActive\nreturn ep.ctrlConnect()\n}\n// RecvFirst blocks until the peer Endpoint calls Endpoint.SendRecv(), then\n// returns the datagram length specified by that call.\n//\n-// Preconditions: ep.SendRecv(), ep.RecvFirst(), and ep.SendLast() have never\n-// been called.\n+// Preconditions: ep is a server Endpoint. ep.SendRecv(), ep.RecvFirst(), and\n+// ep.SendLast() have never been called.\nfunc (ep *Endpoint) RecvFirst() (uint32, error) {\nif err := ep.ctrlWaitFirst(); err != nil {\nreturn 0, err\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/flipcall_example_test.go",
"new_path": "pkg/flipcall/flipcall_example_test.go",
"diff": "@@ -38,12 +38,12 @@ func Example() {\npanic(err)\n}\nvar clientEP Endpoint\n- if err := clientEP.Init(pwd); err != nil {\n+ if err := clientEP.Init(ClientSide, pwd); err != nil {\npanic(err)\n}\ndefer clientEP.Destroy()\nvar serverEP Endpoint\n- if err := serverEP.Init(pwd); err != nil {\n+ if err := serverEP.Init(ServerSide, pwd); err != nil {\npanic(err)\n}\ndefer serverEP.Destroy()\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/flipcall_test.go",
"new_path": "pkg/flipcall/flipcall_test.go",
"diff": "@@ -39,11 +39,11 @@ func newTestConnectionWithOptions(tb testing.TB, clientOpts, serverOpts []Endpoi\nc.pwa.Destroy()\ntb.Fatalf(\"PacketWindowAllocator.Allocate() failed: %v\", err)\n}\n- if err := c.clientEP.Init(pwd, clientOpts...); err != nil {\n+ if err := c.clientEP.Init(ClientSide, pwd, clientOpts...); err != nil {\nc.pwa.Destroy()\ntb.Fatalf(\"failed to create client Endpoint: %v\", err)\n}\n- if err := c.serverEP.Init(pwd, serverOpts...); err != nil {\n+ if err := c.serverEP.Init(ServerSide, pwd, serverOpts...); err != nil {\nc.pwa.Destroy()\nc.clientEP.Destroy()\ntb.Fatalf(\"failed to create server Endpoint: %v\", err)\n@@ -68,11 +68,13 @@ func testSendRecv(t *testing.T, c *testConnection) {\ndefer serverRun.Done()\nt.Logf(\"server Endpoint waiting for packet 1\")\nif _, err := c.serverEP.RecvFirst(); err != nil {\n- t.Fatalf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ t.Errorf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ return\n}\nt.Logf(\"server Endpoint got packet 1, sending packet 2 and waiting for packet 3\")\nif _, err := c.serverEP.SendRecv(0); err != nil {\n- t.Fatalf(\"server Endpoint.SendRecv() failed: %v\", err)\n+ t.Errorf(\"server Endpoint.SendRecv() failed: %v\", err)\n+ return\n}\nt.Logf(\"server Endpoint got packet 3\")\n}()\n@@ -105,7 +107,30 @@ func TestSendRecv(t *testing.T) {\ntestSendRecv(t, c)\n}\n-func testShutdownConnect(t *testing.T, c *testConnection) {\n+func testShutdownBeforeConnect(t *testing.T, c *testConnection, remoteShutdown bool) {\n+ if remoteShutdown {\n+ c.serverEP.Shutdown()\n+ } else {\n+ c.clientEP.Shutdown()\n+ }\n+ if err := c.clientEP.Connect(); err == nil {\n+ t.Errorf(\"client Endpoint.Connect() succeeded unexpectedly\")\n+ }\n+}\n+\n+func TestShutdownBeforeConnectLocal(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownBeforeConnect(t, c, false)\n+}\n+\n+func TestShutdownBeforeConnectRemote(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownBeforeConnect(t, c, true)\n+}\n+\n+func testShutdownDuringConnect(t *testing.T, c *testConnection, remoteShutdown bool) {\nvar clientRun sync.WaitGroup\nclientRun.Add(1)\ngo func() {\n@@ -115,44 +140,86 @@ func testShutdownConnect(t *testing.T, c *testConnection) {\n}\n}()\ntime.Sleep(time.Second) // to allow c.clientEP.Connect() to block\n+ if remoteShutdown {\n+ c.serverEP.Shutdown()\n+ } else {\nc.clientEP.Shutdown()\n+ }\nclientRun.Wait()\n}\n-func TestShutdownConnect(t *testing.T) {\n+func TestShutdownDuringConnectLocal(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringConnect(t, c, false)\n+}\n+\n+func TestShutdownDuringConnectRemote(t *testing.T) {\nc := newTestConnection(t)\ndefer c.destroy()\n- testShutdownConnect(t, c)\n+ testShutdownDuringConnect(t, c, true)\n}\n-func testShutdownRecvFirstBeforeConnect(t *testing.T, c *testConnection) {\n+func testShutdownBeforeRecvFirst(t *testing.T, c *testConnection, remoteShutdown bool) {\n+ if remoteShutdown {\n+ c.clientEP.Shutdown()\n+ } else {\n+ c.serverEP.Shutdown()\n+ }\n+ if _, err := c.serverEP.RecvFirst(); err == nil {\n+ t.Errorf(\"server Endpoint.RecvFirst() succeeded unexpectedly\")\n+ }\n+}\n+\n+func TestShutdownBeforeRecvFirstLocal(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownBeforeRecvFirst(t, c, false)\n+}\n+\n+func TestShutdownBeforeRecvFirstRemote(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownBeforeRecvFirst(t, c, true)\n+}\n+\n+func testShutdownDuringRecvFirstBeforeConnect(t *testing.T, c *testConnection, remoteShutdown bool) {\nvar serverRun sync.WaitGroup\nserverRun.Add(1)\ngo func() {\ndefer serverRun.Done()\n- _, err := c.serverEP.RecvFirst()\n- if err == nil {\n+ if _, err := c.serverEP.RecvFirst(); err == nil {\nt.Errorf(\"server Endpoint.RecvFirst() succeeded unexpectedly\")\n}\n}()\ntime.Sleep(time.Second) // to allow c.serverEP.RecvFirst() to block\n+ if remoteShutdown {\n+ c.clientEP.Shutdown()\n+ } else {\nc.serverEP.Shutdown()\n+ }\nserverRun.Wait()\n}\n-func TestShutdownRecvFirstBeforeConnect(t *testing.T) {\n+func TestShutdownDuringRecvFirstBeforeConnectLocal(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringRecvFirstBeforeConnect(t, c, false)\n+}\n+\n+func TestShutdownDuringRecvFirstBeforeConnectRemote(t *testing.T) {\nc := newTestConnection(t)\ndefer c.destroy()\n- testShutdownRecvFirstBeforeConnect(t, c)\n+ testShutdownDuringRecvFirstBeforeConnect(t, c, true)\n}\n-func testShutdownRecvFirstAfterConnect(t *testing.T, c *testConnection) {\n+func testShutdownDuringRecvFirstAfterConnect(t *testing.T, c *testConnection, remoteShutdown bool) {\nvar serverRun sync.WaitGroup\nserverRun.Add(1)\ngo func() {\ndefer serverRun.Done()\nif _, err := c.serverEP.RecvFirst(); err == nil {\n- t.Fatalf(\"server Endpoint.RecvFirst() succeeded unexpectedly\")\n+ t.Errorf(\"server Endpoint.RecvFirst() succeeded unexpectedly\")\n}\n}()\ndefer func() {\n@@ -164,23 +231,75 @@ func testShutdownRecvFirstAfterConnect(t *testing.T, c *testConnection) {\nif err := c.clientEP.Connect(); err != nil {\nt.Fatalf(\"client Endpoint.Connect() failed: %v\", err)\n}\n+ if remoteShutdown {\n+ c.clientEP.Shutdown()\n+ } else {\n+ c.serverEP.Shutdown()\n+ }\n+ serverRun.Wait()\n+}\n+\n+func TestShutdownDuringRecvFirstAfterConnectLocal(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringRecvFirstAfterConnect(t, c, false)\n+}\n+\n+func TestShutdownDuringRecvFirstAfterConnectRemote(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringRecvFirstAfterConnect(t, c, true)\n+}\n+\n+func testShutdownDuringClientSendRecv(t *testing.T, c *testConnection, remoteShutdown bool) {\n+ var serverRun sync.WaitGroup\n+ serverRun.Add(1)\n+ go func() {\n+ defer serverRun.Done()\n+ if _, err := c.serverEP.RecvFirst(); err != nil {\n+ t.Errorf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ }\n+ // At this point, the client must be blocked in c.clientEP.SendRecv().\n+ if remoteShutdown {\n+ c.serverEP.Shutdown()\n+ } else {\n+ c.clientEP.Shutdown()\n+ }\n+ }()\n+ defer func() {\n+ // Ensure that the server goroutine is cleaned up before\n+ // c.serverEP.Destroy(), even if the test fails.\nc.serverEP.Shutdown()\nserverRun.Wait()\n+ }()\n+ if err := c.clientEP.Connect(); err != nil {\n+ t.Fatalf(\"client Endpoint.Connect() failed: %v\", err)\n+ }\n+ if _, err := c.clientEP.SendRecv(0); err == nil {\n+ t.Errorf(\"client Endpoint.SendRecv() succeeded unexpectedly\")\n+ }\n}\n-func TestShutdownRecvFirstAfterConnect(t *testing.T) {\n+func TestShutdownDuringClientSendRecvLocal(t *testing.T) {\nc := newTestConnection(t)\ndefer c.destroy()\n- testShutdownRecvFirstAfterConnect(t, c)\n+ testShutdownDuringClientSendRecv(t, c, false)\n}\n-func testShutdownSendRecv(t *testing.T, c *testConnection) {\n+func TestShutdownDuringClientSendRecvRemote(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringClientSendRecv(t, c, true)\n+}\n+\n+func testShutdownDuringServerSendRecv(t *testing.T, c *testConnection, remoteShutdown bool) {\nvar serverRun sync.WaitGroup\nserverRun.Add(1)\ngo func() {\ndefer serverRun.Done()\nif _, err := c.serverEP.RecvFirst(); err != nil {\n- t.Fatalf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ t.Errorf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ return\n}\nif _, err := c.serverEP.SendRecv(0); err == nil {\nt.Errorf(\"server Endpoint.SendRecv() succeeded unexpectedly\")\n@@ -199,14 +318,24 @@ func testShutdownSendRecv(t *testing.T, c *testConnection) {\nt.Fatalf(\"client Endpoint.SendRecv() failed: %v\", err)\n}\ntime.Sleep(time.Second) // to allow serverEP.SendRecv() to block\n+ if remoteShutdown {\n+ c.clientEP.Shutdown()\n+ } else {\nc.serverEP.Shutdown()\n+ }\nserverRun.Wait()\n}\n-func TestShutdownSendRecv(t *testing.T) {\n+func TestShutdownDuringServerSendRecvLocal(t *testing.T) {\nc := newTestConnection(t)\ndefer c.destroy()\n- testShutdownSendRecv(t, c)\n+ testShutdownDuringServerSendRecv(t, c, false)\n+}\n+\n+func TestShutdownDuringServerSendRecvRemote(t *testing.T) {\n+ c := newTestConnection(t)\n+ defer c.destroy()\n+ testShutdownDuringServerSendRecv(t, c, true)\n}\nfunc benchmarkSendRecv(b *testing.B, c *testConnection) {\n@@ -218,15 +347,17 @@ func benchmarkSendRecv(b *testing.B, c *testConnection) {\nreturn\n}\nif _, err := c.serverEP.RecvFirst(); err != nil {\n- b.Fatalf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ b.Errorf(\"server Endpoint.RecvFirst() failed: %v\", err)\n+ return\n}\nfor i := 1; i < b.N; i++ {\nif _, err := c.serverEP.SendRecv(0); err != nil {\n- b.Fatalf(\"server Endpoint.SendRecv() failed: %v\", err)\n+ b.Errorf(\"server Endpoint.SendRecv() failed: %v\", err)\n+ return\n}\n}\nif err := c.serverEP.SendLast(0); err != nil {\n- b.Fatalf(\"server Endpoint.SendLast() failed: %v\", err)\n+ b.Errorf(\"server Endpoint.SendLast() failed: %v\", err)\n}\n}()\ndefer func() {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/flipcall_unsafe.go",
"new_path": "pkg/flipcall/flipcall_unsafe.go",
"diff": "@@ -19,15 +19,15 @@ import (\n\"unsafe\"\n)\n-// Packets consist of an 8-byte header followed by an arbitrarily-sized\n+// Packets consist of a 16-byte header followed by an arbitrarily-sized\n// datagram. The header consists of:\n//\n// - A 4-byte native-endian connection state.\n//\n// - A 4-byte native-endian datagram length in bytes.\n+//\n+// - 8 reserved bytes.\nconst (\n- sizeofUint32 = unsafe.Sizeof(uint32(0))\n-\n// PacketHeaderBytes is the size of a flipcall packet header in bytes. The\n// maximum datagram size supported by a flipcall connection is equal to the\n// length of the packet window minus PacketHeaderBytes.\n@@ -35,7 +35,7 @@ const (\n// PacketHeaderBytes is exported to support its use in constant\n// expressions. Non-constant expressions may prefer to use\n// PacketWindowLengthForDataCap().\n- PacketHeaderBytes = 2 * sizeofUint32\n+ PacketHeaderBytes = 16\n)\nfunc (ep *Endpoint) connState() *uint32 {\n@@ -43,7 +43,7 @@ func (ep *Endpoint) connState() *uint32 {\n}\nfunc (ep *Endpoint) dataLen() *uint32 {\n- return (*uint32)((unsafe.Pointer)(ep.packet + sizeofUint32))\n+ return (*uint32)((unsafe.Pointer)(ep.packet + 4))\n}\n// Data returns the datagram part of ep's packet window as a byte slice.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/flipcall/futex_linux.go",
"new_path": "pkg/flipcall/futex_linux.go",
"diff": "@@ -59,7 +59,12 @@ func (ep *Endpoint) futexConnect(req *ctrlHandshakeRequest) (ctrlHandshakeRespon\nfunc (ep *Endpoint) futexSwitchToPeer() error {\n// Update connection state to indicate that the peer should be active.\nif !atomic.CompareAndSwapUint32(ep.connState(), ep.activeState, ep.inactiveState) {\n- return fmt.Errorf(\"unexpected connection state before FUTEX_WAKE: %v\", atomic.LoadUint32(ep.connState()))\n+ switch cs := atomic.LoadUint32(ep.connState()); cs {\n+ case csShutdown:\n+ return shutdownError{}\n+ default:\n+ return fmt.Errorf(\"unexpected connection state before FUTEX_WAKE: %v\", cs)\n+ }\n}\n// Wake the peer's Endpoint.futexSwitchFromPeer().\n@@ -75,16 +80,18 @@ func (ep *Endpoint) futexSwitchFromPeer() error {\ncase ep.activeState:\nreturn nil\ncase ep.inactiveState:\n- // Continue to FUTEX_WAIT.\n- default:\n- return fmt.Errorf(\"unexpected connection state before FUTEX_WAIT: %v\", cs)\n- }\nif ep.isShutdownLocally() {\nreturn shutdownError{}\n}\nif err := ep.futexWaitConnState(ep.inactiveState); err != nil {\nreturn fmt.Errorf(\"failed to FUTEX_WAIT for peer Endpoint: %v\", err)\n}\n+ continue\n+ case csShutdown:\n+ return shutdownError{}\n+ default:\n+ return fmt.Errorf(\"unexpected connection state before FUTEX_WAIT: %v\", cs)\n+ }\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure that flipcall.Endpoint.Shutdown() shuts down inactive peers.
PiperOrigin-RevId: 267022978 |
260,004 | 03.09.2019 18:41:40 | 25,200 | 144127e5e1c548150f49501a7decb82ec2e239f2 | Validate IPv6 Hop Limit field for received NDP packets
Make sure that NDP packets are only received if their IP header's hop limit
field is set to 255, as per RFC 4861. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/BUILD",
"new_path": "pkg/tcpip/network/ipv6/BUILD",
"diff": "@@ -23,7 +23,10 @@ go_library(\ngo_test(\nname = \"ipv6_test\",\nsize = \"small\",\n- srcs = [\"icmp_test.go\"],\n+ srcs = [\n+ \"icmp_test.go\",\n+ \"ndp_test.go\",\n+ ],\nembed = [\":ipv6\"],\ndeps = [\n\"//pkg/tcpip\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ipv6/icmp.go",
"new_path": "pkg/tcpip/network/ipv6/icmp.go",
"diff": "@@ -21,6 +21,15 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n+const (\n+ // ndpHopLimit is the expected IP hop limit value of 255 for received\n+ // NDP packets, as per RFC 4861 sections 4.1 - 4.5, 6.1.1, 6.1.2, 7.1.1,\n+ // 7.1.2 and 8.1. If the hop limit value is not 255, nodes MUST silently\n+ // drop the NDP packet. All outgoing NDP packets must use this value for\n+ // its IP hop limit field.\n+ ndpHopLimit = 255\n+)\n+\n// handleControl handles the case when an ICMP packet contains the headers of\n// the original packet that caused the ICMP one to be sent. This information is\n// used to find out which transport endpoint must be notified about the ICMP\n@@ -71,6 +80,21 @@ func (e *endpoint) handleICMP(r *stack.Route, netHeader buffer.View, vv buffer.V\n}\nh := header.ICMPv6(v)\n+ // As per RFC 4861 sections 4.1 - 4.5, 6.1.1, 6.1.2, 7.1.1, 7.1.2 and\n+ // 8.1, nodes MUST silently drop NDP packets where the Hop Limit field\n+ // in the IPv6 header is not set to 255.\n+ switch h.Type() {\n+ case header.ICMPv6NeighborSolicit,\n+ header.ICMPv6NeighborAdvert,\n+ header.ICMPv6RouterSolicit,\n+ header.ICMPv6RouterAdvert,\n+ header.ICMPv6RedirectMsg:\n+ if header.IPv6(netHeader).HopLimit() != ndpHopLimit {\n+ received.Invalid.Increment()\n+ return\n+ }\n+ }\n+\n// TODO(b/112892170): Meaningfully handle all ICMP types.\nswitch h.Type() {\ncase header.ICMPv6PacketTooBig:\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "pkg/tcpip/network/ipv6/ndp_test.go",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package ipv6\n+\n+import (\n+ \"strings\"\n+ \"testing\"\n+\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/stack\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/transport/icmp\"\n+)\n+\n+// setupStackAndEndpoint creates a stack with a single NIC with a link-local\n+// address llladdr and an IPv6 endpoint to a remote with link-local address\n+// rlladdr\n+func setupStackAndEndpoint(t *testing.T, llladdr, rlladdr tcpip.Address) (*stack.Stack, stack.NetworkEndpoint) {\n+ t.Helper()\n+\n+ s := stack.New([]string{ProtocolName}, []string{icmp.ProtocolName6}, stack.Options{})\n+ {\n+ id := stack.RegisterLinkEndpoint(&stubLinkEndpoint{})\n+ if err := s.CreateNIC(1, id); err != nil {\n+ t.Fatalf(\"CreateNIC(_) = %s\", err)\n+ }\n+ if err := s.AddAddress(1, ProtocolNumber, llladdr); err != nil {\n+ t.Fatalf(\"AddAddress(_, %d, %s) = %s\", ProtocolNumber, llladdr, err)\n+ }\n+ }\n+ {\n+ subnet, err := tcpip.NewSubnet(rlladdr, tcpip.AddressMask(strings.Repeat(\"\\xff\", len(rlladdr))))\n+ if err != nil {\n+ t.Fatal(err)\n+ }\n+ s.SetRouteTable(\n+ []tcpip.Route{{\n+ Destination: subnet,\n+ NIC: 1,\n+ }},\n+ )\n+ }\n+\n+ netProto := s.NetworkProtocolInstance(ProtocolNumber)\n+ if netProto == nil {\n+ t.Fatalf(\"cannot find protocol instance for network protocol %d\", ProtocolNumber)\n+ }\n+\n+ ep, err := netProto.NewEndpoint(0, tcpip.AddressWithPrefix{rlladdr, netProto.DefaultPrefixLen()}, &stubLinkAddressCache{}, &stubDispatcher{}, nil)\n+ if err != nil {\n+ t.Fatalf(\"NewEndpoint(_) = _, %s, want = _, nil\", err)\n+ }\n+\n+ return s, ep\n+}\n+\n+// TestHopLimitValidation is a test that makes sure that NDP packets are only\n+// received if their IP header's hop limit is set to 255.\n+func TestHopLimitValidation(t *testing.T) {\n+ setup := func(t *testing.T) (*stack.Stack, stack.NetworkEndpoint, stack.Route) {\n+ t.Helper()\n+\n+ // Create a stack with the assigned link-local address lladdr0\n+ // and an endpoint to lladdr1.\n+ s, ep := setupStackAndEndpoint(t, lladdr0, lladdr1)\n+\n+ r, err := s.FindRoute(1, lladdr0, lladdr1, ProtocolNumber, false /* multicastLoop */)\n+ if err != nil {\n+ t.Fatalf(\"FindRoute(_) = _, %s, want = _, nil\", err)\n+ }\n+\n+ return s, ep, r\n+ }\n+\n+ handleIPv6Payload := func(hdr buffer.Prependable, hopLimit uint8, ep stack.NetworkEndpoint, r *stack.Route) {\n+ payloadLength := hdr.UsedLength()\n+ ip := header.IPv6(hdr.Prepend(header.IPv6MinimumSize))\n+ ip.Encode(&header.IPv6Fields{\n+ PayloadLength: uint16(payloadLength),\n+ NextHeader: uint8(header.ICMPv6ProtocolNumber),\n+ HopLimit: hopLimit,\n+ SrcAddr: r.LocalAddress,\n+ DstAddr: r.RemoteAddress,\n+ })\n+ ep.HandlePacket(r, hdr.View().ToVectorisedView())\n+ }\n+\n+ types := []struct {\n+ name string\n+ typ header.ICMPv6Type\n+ size int\n+ statCounter func(tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter\n+ }{\n+ {\"RouterSolicit\", header.ICMPv6RouterSolicit, header.ICMPv6MinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ return stats.RouterSolicit\n+ }},\n+ {\"RouterAdvert\", header.ICMPv6RouterAdvert, header.ICMPv6MinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ return stats.RouterAdvert\n+ }},\n+ {\"NeighborSolicit\", header.ICMPv6NeighborSolicit, header.ICMPv6NeighborSolicitMinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ return stats.NeighborSolicit\n+ }},\n+ {\"NeighborAdvert\", header.ICMPv6NeighborAdvert, header.ICMPv6NeighborAdvertSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ return stats.NeighborAdvert\n+ }},\n+ {\"RedirectMsg\", header.ICMPv6RedirectMsg, header.ICMPv6MinimumSize, func(stats tcpip.ICMPv6ReceivedPacketStats) *tcpip.StatCounter {\n+ return stats.RedirectMsg\n+ }},\n+ }\n+\n+ for _, typ := range types {\n+ t.Run(typ.name, func(t *testing.T) {\n+ s, ep, r := setup(t)\n+ defer r.Release()\n+\n+ stats := s.Stats().ICMP.V6PacketsReceived\n+ invalid := stats.Invalid\n+ typStat := typ.statCounter(stats)\n+\n+ hdr := buffer.NewPrependable(header.IPv6MinimumSize + typ.size)\n+ pkt := header.ICMPv6(hdr.Prepend(typ.size))\n+ pkt.SetType(typ.typ)\n+ pkt.SetChecksum(header.ICMPv6Checksum(pkt, r.LocalAddress, r.RemoteAddress, buffer.VectorisedView{}))\n+\n+ // Invalid count should initially be 0.\n+ if got := invalid.Value(); got != 0 {\n+ t.Fatalf(\"got invalid = %d, want = 0\", got)\n+ }\n+\n+ // Should not have received any ICMPv6 packets with\n+ // type = typ.typ.\n+ if got := typStat.Value(); got != 0 {\n+ t.Fatalf(\"got %s = %d, want = 0\", typ.name, got)\n+ }\n+\n+ // Receive the NDP packet with an invalid hop limit\n+ // value.\n+ handleIPv6Payload(hdr, ndpHopLimit-1, ep, &r)\n+\n+ // Invalid count should have increased.\n+ if got := invalid.Value(); got != 1 {\n+ t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ }\n+\n+ // Rx count of NDP packet of type typ.typ should not\n+ // have increased.\n+ if got := typStat.Value(); got != 0 {\n+ t.Fatalf(\"got %s = %d, want = 0\", typ.name, got)\n+ }\n+\n+ // Receive the NDP packet with a valid hop limit value.\n+ handleIPv6Payload(hdr, ndpHopLimit, ep, &r)\n+\n+ // Rx count of NDP packet of type typ.typ should have\n+ // increased.\n+ if got := typStat.Value(); got != 1 {\n+ t.Fatalf(\"got %s = %d, want = 1\", typ.name, got)\n+ }\n+\n+ // Invalid count should not have increased again.\n+ if got := invalid.Value(); got != 1 {\n+ t.Fatalf(\"got invalid = %d, want = 1\", got)\n+ }\n+ })\n+ }\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Validate IPv6 Hop Limit field for received NDP packets
Make sure that NDP packets are only received if their IP header's hop limit
field is set to 255, as per RFC 4861.
PiperOrigin-RevId: 267061457 |
260,006 | 04.09.2019 14:18:02 | 25,200 | 7bf1d426d5f8ba5a3ddfc8f0cd73cc12e8a83c16 | Handle subnet and broadcast addresses correctly with NIC.subnets
This also renames "subnet" to "addressRange" to avoid any more confusion with
an interface IP's subnet.
Lastly, this also removes the Stack.ContainsSubnet(..) API since it isn't used
by anyone. Plus the same information can be obtained from
Stack.NICAddressRanges(). | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/nic.go",
"new_path": "pkg/tcpip/stack/nic.go",
"diff": "@@ -41,7 +41,7 @@ type NIC struct {\npromiscuous bool\nprimary map[tcpip.NetworkProtocolNumber]*ilist.List\nendpoints map[NetworkEndpointID]*referencedNetworkEndpoint\n- subnets []tcpip.Subnet\n+ addressRanges []tcpip.Subnet\nmcastJoins map[NetworkEndpointID]int32\nstats NICStats\n@@ -224,7 +224,17 @@ func (n *NIC) getRefOrCreateTemp(protocol tcpip.NetworkProtocolNumber, address t\n// the caller or if the address is found in the NIC's subnets.\ncreateTempEP := spoofingOrPromiscuous\nif !createTempEP {\n- for _, sn := range n.subnets {\n+ for _, sn := range n.addressRanges {\n+ // Skip the subnet address.\n+ if address == sn.ID() {\n+ continue\n+ }\n+ // For now just skip the broadcast address, until we support it.\n+ // FIXME(b/137608825): Add support for sending/receiving directed\n+ // (subnet) broadcast.\n+ if address == sn.Broadcast() {\n+ continue\n+ }\nif sn.Contains(address) {\ncreateTempEP = true\nbreak\n@@ -381,45 +391,38 @@ func (n *NIC) Addresses() []tcpip.ProtocolAddress {\nreturn addrs\n}\n-// AddSubnet adds a new subnet to n, so that it starts accepting packets\n-// targeted at the given address and network protocol.\n-func (n *NIC) AddSubnet(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) {\n+// AddAddressRange adds a range of addresses to n, so that it starts accepting\n+// packets targeted at the given addresses and network protocol. The range is\n+// given by a subnet address, and all addresses contained in the subnet are\n+// used except for the subnet address itself and the subnet's broadcast\n+// address.\n+func (n *NIC) AddAddressRange(protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) {\nn.mu.Lock()\n- n.subnets = append(n.subnets, subnet)\n+ n.addressRanges = append(n.addressRanges, subnet)\nn.mu.Unlock()\n}\n-// RemoveSubnet removes the given subnet from n.\n-func (n *NIC) RemoveSubnet(subnet tcpip.Subnet) {\n+// RemoveAddressRange removes the given address range from n.\n+func (n *NIC) RemoveAddressRange(subnet tcpip.Subnet) {\nn.mu.Lock()\n// Use the same underlying array.\n- tmp := n.subnets[:0]\n- for _, sub := range n.subnets {\n+ tmp := n.addressRanges[:0]\n+ for _, sub := range n.addressRanges {\nif sub != subnet {\ntmp = append(tmp, sub)\n}\n}\n- n.subnets = tmp\n+ n.addressRanges = tmp\nn.mu.Unlock()\n}\n-// ContainsSubnet reports whether this NIC contains the given subnet.\n-func (n *NIC) ContainsSubnet(subnet tcpip.Subnet) bool {\n- for _, s := range n.Subnets() {\n- if s == subnet {\n- return true\n- }\n- }\n- return false\n-}\n-\n// Subnets returns the Subnets associated with this NIC.\n-func (n *NIC) Subnets() []tcpip.Subnet {\n+func (n *NIC) AddressRanges() []tcpip.Subnet {\nn.mu.RLock()\ndefer n.mu.RUnlock()\n- sns := make([]tcpip.Subnet, 0, len(n.subnets)+len(n.endpoints))\n+ sns := make([]tcpip.Subnet, 0, len(n.addressRanges)+len(n.endpoints))\nfor nid := range n.endpoints {\nsn, err := tcpip.NewSubnet(nid.LocalAddress, tcpip.AddressMask(strings.Repeat(\"\\xff\", len(nid.LocalAddress))))\nif err != nil {\n@@ -429,7 +432,7 @@ func (n *NIC) Subnets() []tcpip.Subnet {\n}\nsns = append(sns, sn)\n}\n- return append(sns, n.subnets...)\n+ return append(sns, n.addressRanges...)\n}\nfunc (n *NIC) removeEndpointLocked(r *referencedNetworkEndpoint) {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack.go",
"new_path": "pkg/tcpip/stack/stack.go",
"diff": "@@ -702,14 +702,14 @@ func (s *Stack) CheckNIC(id tcpip.NICID) bool {\n}\n// NICSubnets returns a map of NICIDs to their associated subnets.\n-func (s *Stack) NICSubnets() map[tcpip.NICID][]tcpip.Subnet {\n+func (s *Stack) NICAddressRanges() map[tcpip.NICID][]tcpip.Subnet {\ns.mu.RLock()\ndefer s.mu.RUnlock()\nnics := map[tcpip.NICID][]tcpip.Subnet{}\nfor id, nic := range s.nics {\n- nics[id] = append(nics[id], nic.Subnets()...)\n+ nics[id] = append(nics[id], nic.AddressRanges()...)\n}\nreturn nics\n}\n@@ -810,45 +810,35 @@ func (s *Stack) AddProtocolAddressWithOptions(id tcpip.NICID, protocolAddress tc\nreturn nic.AddAddress(protocolAddress, peb)\n}\n-// AddSubnet adds a subnet range to the specified NIC.\n-func (s *Stack) AddSubnet(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error {\n+// AddAddressRange adds a range of addresses to the specified NIC. The range is\n+// given by a subnet address, and all addresses contained in the subnet are\n+// used except for the subnet address itself and the subnet's broadcast\n+// address.\n+func (s *Stack) AddAddressRange(id tcpip.NICID, protocol tcpip.NetworkProtocolNumber, subnet tcpip.Subnet) *tcpip.Error {\ns.mu.RLock()\ndefer s.mu.RUnlock()\nif nic, ok := s.nics[id]; ok {\n- nic.AddSubnet(protocol, subnet)\n+ nic.AddAddressRange(protocol, subnet)\nreturn nil\n}\nreturn tcpip.ErrUnknownNICID\n}\n-// RemoveSubnet removes the subnet range from the specified NIC.\n-func (s *Stack) RemoveSubnet(id tcpip.NICID, subnet tcpip.Subnet) *tcpip.Error {\n+// RemoveAddressRange removes the range of addresses from the specified NIC.\n+func (s *Stack) RemoveAddressRange(id tcpip.NICID, subnet tcpip.Subnet) *tcpip.Error {\ns.mu.RLock()\ndefer s.mu.RUnlock()\nif nic, ok := s.nics[id]; ok {\n- nic.RemoveSubnet(subnet)\n+ nic.RemoveAddressRange(subnet)\nreturn nil\n}\nreturn tcpip.ErrUnknownNICID\n}\n-// ContainsSubnet reports whether the specified NIC contains the specified\n-// subnet.\n-func (s *Stack) ContainsSubnet(id tcpip.NICID, subnet tcpip.Subnet) (bool, *tcpip.Error) {\n- s.mu.RLock()\n- defer s.mu.RUnlock()\n-\n- if nic, ok := s.nics[id]; ok {\n- return nic.ContainsSubnet(subnet), nil\n- }\n-\n- return false, tcpip.ErrUnknownNICID\n-}\n-\n// RemoveAddress removes an existing network-layer address from the specified\n// NIC.\nfunc (s *Stack) RemoveAddress(id tcpip.NICID, addr tcpip.Address) *tcpip.Error {\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/stack_test.go",
"new_path": "pkg/tcpip/stack/stack_test.go",
"diff": "@@ -1128,8 +1128,8 @@ func TestMulticastOrIPv6LinkLocalNeedsNoRoute(t *testing.T) {\n}\n}\n-// Set the subnet, then check that packet is delivered.\n-func TestSubnetAcceptsMatchingPacket(t *testing.T) {\n+// Add a range of addresses, then check that a packet is delivered.\n+func TestAddressRangeAcceptsMatchingPacket(t *testing.T) {\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\nid, linkEP := channel.New(10, defaultMTU, \"\")\n@@ -1155,14 +1155,45 @@ func TestSubnetAcceptsMatchingPacket(t *testing.T) {\nif err != nil {\nt.Fatal(\"NewSubnet failed:\", err)\n}\n- if err := s.AddSubnet(1, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddSubnet failed:\", err)\n+ if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {\n+ t.Fatal(\"AddAddressRange failed:\", err)\n}\ntestRecv(t, fakeNet, localAddrByte, linkEP, buf)\n}\n-// Set the subnet, then check that CheckLocalAddress returns the correct NIC.\n+func testNicForAddressRange(t *testing.T, nicID tcpip.NICID, s *stack.Stack, subnet tcpip.Subnet, rangeExists bool) {\n+ t.Helper()\n+\n+ // Loop over all addresses and check them.\n+ numOfAddresses := 1 << uint(8-subnet.Prefix())\n+ if numOfAddresses < 1 || numOfAddresses > 255 {\n+ t.Fatalf(\"got numOfAddresses = %d, want = [1 .. 255] (subnet=%s)\", numOfAddresses, subnet)\n+ }\n+\n+ addrBytes := []byte(subnet.ID())\n+ for i := 0; i < numOfAddresses; i++ {\n+ addr := tcpip.Address(addrBytes)\n+ wantNicID := nicID\n+ // The subnet and broadcast addresses are skipped.\n+ if !rangeExists || addr == subnet.ID() || addr == subnet.Broadcast() {\n+ wantNicID = 0\n+ }\n+ if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, addr); gotNicID != wantNicID {\n+ t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, addr, gotNicID, wantNicID)\n+ }\n+ addrBytes[0]++\n+ }\n+\n+ // Trying the next address should always fail since it is outside the range.\n+ if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addrBytes)); gotNicID != 0 {\n+ t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addrBytes), gotNicID, 0)\n+ }\n+}\n+\n+// Set a range of addresses, then remove it again, and check at each step that\n+// CheckLocalAddress returns the correct NIC for each address or zero if not\n+// existent.\nfunc TestCheckLocalAddressForSubnet(t *testing.T) {\nconst nicID tcpip.NICID = 1\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\n@@ -1181,35 +1212,28 @@ func TestCheckLocalAddressForSubnet(t *testing.T) {\n}\nsubnet, err := tcpip.NewSubnet(tcpip.Address(\"\\xa0\"), tcpip.AddressMask(\"\\xf0\"))\n-\nif err != nil {\nt.Fatal(\"NewSubnet failed:\", err)\n}\n- if err := s.AddSubnet(nicID, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddSubnet failed:\", err)\n- }\n- // Loop over all subnet addresses and check them.\n- numOfAddresses := 1 << uint(8-subnet.Prefix())\n- if numOfAddresses < 1 || numOfAddresses > 255 {\n- t.Fatalf(\"got numOfAddresses = %d, want = [1 .. 255] (subnet=%s)\", numOfAddresses, subnet)\n- }\n- addr := []byte(subnet.ID())\n- for i := 0; i < numOfAddresses; i++ {\n- if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addr)); gotNicID != nicID {\n- t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addr), gotNicID, nicID)\n- }\n- addr[0]++\n+ testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)\n+\n+ if err := s.AddAddressRange(nicID, fakeNetNumber, subnet); err != nil {\n+ t.Fatal(\"AddAddressRange failed:\", err)\n}\n- // Trying the next address should fail since it is outside the subnet range.\n- if gotNicID := s.CheckLocalAddress(0, fakeNetNumber, tcpip.Address(addr)); gotNicID != 0 {\n- t.Errorf(\"got CheckLocalAddress(0, %d, %s) = %d, want = %d\", fakeNetNumber, tcpip.Address(addr), gotNicID, 0)\n+ testNicForAddressRange(t, nicID, s, subnet, true /* rangeExists */)\n+\n+ if err := s.RemoveAddressRange(nicID, subnet); err != nil {\n+ t.Fatal(\"RemoveAddressRange failed:\", err)\n}\n+\n+ testNicForAddressRange(t, nicID, s, subnet, false /* rangeExists */)\n}\n-// Set destination outside the subnet, then check it doesn't get delivered.\n-func TestSubnetRejectsNonmatchingPacket(t *testing.T) {\n+// Set a range of addresses, then send a packet to a destination outside the\n+// range and then check it doesn't get delivered.\n+func TestAddressRangeRejectsNonmatchingPacket(t *testing.T) {\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\nid, linkEP := channel.New(10, defaultMTU, \"\")\n@@ -1235,8 +1259,8 @@ func TestSubnetRejectsNonmatchingPacket(t *testing.T) {\nif err != nil {\nt.Fatal(\"NewSubnet failed:\", err)\n}\n- if err := s.AddSubnet(1, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddSubnet failed:\", err)\n+ if err := s.AddAddressRange(1, fakeNetNumber, subnet); err != nil {\n+ t.Fatal(\"AddAddressRange failed:\", err)\n}\ntestFailingRecv(t, fakeNet, localAddrByte, linkEP, buf)\n}\n@@ -1281,7 +1305,20 @@ func TestNetworkOptions(t *testing.T) {\n}\n}\n-func TestSubnetAddRemove(t *testing.T) {\n+func stackContainsAddressRange(s *stack.Stack, id tcpip.NICID, addrRange tcpip.Subnet) bool {\n+ ranges, ok := s.NICAddressRanges()[id]\n+ if !ok {\n+ return false\n+ }\n+ for _, r := range ranges {\n+ if r == addrRange {\n+ return true\n+ }\n+ }\n+ return false\n+}\n+\n+func TestAddresRangeAddRemove(t *testing.T) {\ns := stack.New([]string{\"fakeNet\"}, nil, stack.Options{})\nid, _ := channel.New(10, defaultMTU, \"\")\nif err := s.CreateNIC(1, id); err != nil {\n@@ -1290,35 +1327,29 @@ func TestSubnetAddRemove(t *testing.T) {\naddr := tcpip.Address(\"\\x01\\x01\\x01\\x01\")\nmask := tcpip.AddressMask(strings.Repeat(\"\\xff\", len(addr)))\n- subnet, err := tcpip.NewSubnet(addr, mask)\n+ addrRange, err := tcpip.NewSubnet(addr, mask)\nif err != nil {\nt.Fatal(\"NewSubnet failed:\", err)\n}\n- if contained, err := s.ContainsSubnet(1, subnet); err != nil {\n- t.Fatal(\"ContainsSubnet failed:\", err)\n- } else if contained {\n- t.Fatal(\"got s.ContainsSubnet(...) = true, want = false\")\n+ if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {\n+ t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n}\n- if err := s.AddSubnet(1, fakeNetNumber, subnet); err != nil {\n- t.Fatal(\"AddSubnet failed:\", err)\n+ if err := s.AddAddressRange(1, fakeNetNumber, addrRange); err != nil {\n+ t.Fatal(\"AddAddressRange failed:\", err)\n}\n- if contained, err := s.ContainsSubnet(1, subnet); err != nil {\n- t.Fatal(\"ContainsSubnet failed:\", err)\n- } else if !contained {\n- t.Fatal(\"got s.ContainsSubnet(...) = false, want = true\")\n+ if got, want := stackContainsAddressRange(s, 1, addrRange), true; got != want {\n+ t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n}\n- if err := s.RemoveSubnet(1, subnet); err != nil {\n- t.Fatal(\"RemoveSubnet failed:\", err)\n+ if err := s.RemoveAddressRange(1, addrRange); err != nil {\n+ t.Fatal(\"RemoveAddressRange failed:\", err)\n}\n- if contained, err := s.ContainsSubnet(1, subnet); err != nil {\n- t.Fatal(\"ContainsSubnet failed:\", err)\n- } else if contained {\n- t.Fatal(\"got s.ContainsSubnet(...) = true, want = false\")\n+ if got, want := stackContainsAddressRange(s, 1, addrRange), false; got != want {\n+ t.Fatalf(\"got stackContainsAddressRange(...) = %t, want = %t\", got, want)\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/tcpip.go",
"new_path": "pkg/tcpip/tcpip.go",
"diff": "@@ -219,6 +219,15 @@ func (s *Subnet) Mask() AddressMask {\nreturn s.mask\n}\n+// Broadcast returns the subnet's broadcast address.\n+func (s *Subnet) Broadcast() Address {\n+ addr := []byte(s.address)\n+ for i := range addr {\n+ addr[i] |= ^s.mask[i]\n+ }\n+ return Address(addr)\n+}\n+\n// NICID is a number that uniquely identifies a NIC.\ntype NICID int32\n"
}
] | Go | Apache License 2.0 | google/gvisor | Handle subnet and broadcast addresses correctly with NIC.subnets
This also renames "subnet" to "addressRange" to avoid any more confusion with
an interface IP's subnet.
Lastly, this also removes the Stack.ContainsSubnet(..) API since it isn't used
by anyone. Plus the same information can be obtained from
Stack.NICAddressRanges().
PiperOrigin-RevId: 267229843 |
259,858 | 04.09.2019 18:47:47 | 25,200 | bcddd0a4778916f6a5347246a81fbe236050d2c4 | Fix continuous build breakage | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -20,7 +20,7 @@ source $(dirname $0)/common.sh\nrunsc=$(build -c opt //runsc)\n# Build packages.\n-pkg=$(build -c opt --host_force_python=py2 //runsc:debian)\n+pkg=$(build -c opt --host_force_python=py2 //runsc:runsc-debian)\n# Build a repository, if the key is available.\nif [[ -v KOKORO_REPO_KEY ]]; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix continuous build breakage
PiperOrigin-RevId: 267277711 |
259,992 | 04.09.2019 18:55:39 | 25,200 | 0f5cdc1e00488823f1f7b9884c15b899677362b6 | Resolve flakes with TestMultiContainerDestroy
Some processes are reparented to the root container depending
on the kill order and the root container would not reap in time.
So some zombie processes were still present when the test checked.
Fix it by running the second container inside a PID namespace. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/loader.go",
"new_path": "runsc/boot/loader.go",
"diff": "@@ -760,12 +760,11 @@ func (l *Loader) destroyContainer(cid string) error {\nif err := l.signalAllProcesses(cid, int32(linux.SIGKILL)); err != nil {\nreturn fmt.Errorf(\"sending SIGKILL to all container processes: %v\", err)\n}\n- }\n-\n- // Remove all container thread groups from the map.\n- for key := range l.processes {\n- if key.cid == cid {\n- delete(l.processes, key)\n+ // Wait for all processes that belong to the container to exit (including\n+ // exec'd processes).\n+ for _, t := range l.k.TaskSet().Root.Tasks() {\n+ if t.ContainerID() == cid {\n+ t.ThreadGroup().WaitExited()\n}\n}\n@@ -779,6 +778,15 @@ func (l *Loader) destroyContainer(cid string) error {\n// before returning, otherwise the caller may kill the gofer before\n// they complete, causing a cascade of failing RPCs.\nfs.AsyncBarrier()\n+ }\n+\n+ // No more failure from this point on. Remove all container thread groups\n+ // from the map.\n+ for key := range l.processes {\n+ if key.cid == cid {\n+ delete(l.processes, key)\n+ }\n+ }\nlog.Debugf(\"Container destroyed %q\", cid)\nreturn nil\n@@ -1037,21 +1045,8 @@ func (l *Loader) signalAllProcesses(cid string, signo int32) error {\n// the signal is delivered. This prevents process leaks when SIGKILL is\n// sent to the entire container.\nl.k.Pause()\n- if err := l.k.SendContainerSignal(cid, &arch.SignalInfo{Signo: signo}); err != nil {\n- l.k.Unpause()\n- return err\n- }\n- l.k.Unpause()\n-\n- // If SIGKILLing all processes, wait for them to exit.\n- if linux.Signal(signo) == linux.SIGKILL {\n- for _, t := range l.k.TaskSet().Root.Tasks() {\n- if t.ContainerID() == cid {\n- t.ThreadGroup().WaitExited()\n- }\n- }\n- }\n- return nil\n+ defer l.k.Unpause()\n+ return l.k.SendContainerSignal(cid, &arch.SignalInfo{Signo: signo})\n}\n// threadGroupFromID same as threadGroupFromIDLocked except that it acquires\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/multi_container_test.go",
"new_path": "runsc/container/multi_container_test.go",
"diff": "@@ -549,10 +549,16 @@ func TestMultiContainerDestroy(t *testing.T) {\nt.Logf(\"Running test with conf: %+v\", conf)\n// First container will remain intact while the second container is killed.\n- specs, ids := createSpecs(\n- []string{app, \"reaper\"},\n+ podSpecs, ids := createSpecs(\n+ []string{\"sleep\", \"100\"},\n[]string{app, \"fork-bomb\"})\n- containers, cleanup, err := startContainers(conf, specs, ids)\n+\n+ // Run the fork bomb in a PID namespace to prevent processes to be\n+ // re-parented to PID=1 in the root container.\n+ podSpecs[1].Linux = &specs.Linux{\n+ Namespaces: []specs.LinuxNamespace{{Type: \"pid\"}},\n+ }\n+ containers, cleanup, err := startContainers(conf, podSpecs, ids)\nif err != nil {\nt.Fatalf(\"error starting containers: %v\", err)\n}\n@@ -580,7 +586,7 @@ func TestMultiContainerDestroy(t *testing.T) {\nif err != nil {\nt.Fatalf(\"error getting process data from sandbox: %v\", err)\n}\n- expectedPL := []*control.Process{{PID: 1, Cmd: \"test_app\"}}\n+ expectedPL := []*control.Process{{PID: 1, Cmd: \"sleep\"}}\nif !procListsEqual(pss, expectedPL) {\nt.Errorf(\"container got process list: %s, want: %s\", procListToString(pss), procListToString(expectedPL))\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Resolve flakes with TestMultiContainerDestroy
Some processes are reparented to the root container depending
on the kill order and the root container would not reap in time.
So some zombie processes were still present when the test checked.
Fix it by running the second container inside a PID namespace.
PiperOrigin-RevId: 267278591 |
259,854 | 04.09.2019 19:06:44 | 25,200 | fbbb2f7ed6a2f735c8e8d48e8b5264d2057e93ad | Run proc_net tests. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -305,6 +305,8 @@ syscall_test(\nsyscall_test(test = \"//test/syscalls/linux:proc_pid_uid_gid_map_test\")\n+syscall_test(test = \"//test/syscalls/linux:proc_net_test\")\n+\nsyscall_test(\nsize = \"medium\",\ntest = \"//test/syscalls/linux:pselect_test\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1521,6 +1521,7 @@ cc_binary(\nsrcs = [\"proc_net.cc\"],\nlinkstatic = 1,\ndeps = [\n+ \"//test/util:capability_util\",\n\"//test/util:file_descriptor\",\n\"//test/util:fs_util\",\n\"//test/util:test_main\",\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net.cc",
"new_path": "test/syscalls/linux/proc_net.cc",
"diff": "#include \"gtest/gtest.h\"\n#include \"gtest/gtest.h\"\n+#include \"test/util/capability_util.h\"\n#include \"test/util/file_descriptor.h\"\n#include \"test/util/fs_util.h\"\n#include \"test/util/test_util.h\"\n@@ -35,6 +36,8 @@ TEST(ProcSysNetIpv4Sack, Exists) {\n}\nTEST(ProcSysNetIpv4Sack, CanReadAndWrite) {\n+ SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability((CAP_DAC_OVERRIDE))));\n+\nauto const fd =\nASSERT_NO_ERRNO_AND_VALUE(Open(\"/proc/sys/net/ipv4/tcp_sack\", O_RDWR));\n"
}
] | Go | Apache License 2.0 | google/gvisor | Run proc_net tests.
PiperOrigin-RevId: 267280086 |
259,858 | 04.09.2019 22:24:42 | 25,200 | 91518fd553b828ce9f3fa84d91f20a45a8f0c81d | Fix build when no tags are present
This should correct the continuous build. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -49,7 +49,7 @@ if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\n# Is it a tagged release? Build that instead. In that case, we also try to\n# update the base release directory, in case this is an update. Finally, we\n# update the \"release\" directory, which has the last released version.\n- tag=\"$(git describe --exact-match --tags HEAD)\"\n+ tag=\"$(git describe --exact-match --tags HEAD || true)\"\nif ! [[ -z \"${tag}\" ]]; then\ninstall \"${KOKORO_ARTIFACTS_DIR}/${tag}\"\nbase=$(echo \"${tag}\" | cut -d'.' -f1)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix build when no tags are present
This should correct the continuous build. |
259,884 | 04.09.2019 23:19:09 | 25,200 | e31686500db56a5fcd4070561643d702a94da0c3 | Allow non-unique group IDs in bazel docker containers
Allow non-unique group IDs in the bazel docker container in order to avoid
failures using host group IDs that are already present in the image.
Issue | [
{
"change_type": "MODIFY",
"old_path": "Makefile",
"new_path": "Makefile",
"diff": "@@ -22,7 +22,7 @@ bazel-server-start: docker-build\n--privileged \\\ngvisor-bazel \\\nsh -c \"while :; do sleep 100; done\" && \\\n- docker exec --user 0:0 -i gvisor-bazel sh -c \"groupadd --gid $(GID) gvisor && useradd --uid $(UID) --gid $(GID) -d $(HOME) gvisor\"\n+ docker exec --user 0:0 -i gvisor-bazel sh -c \"groupadd --gid $(GID) --non-unique gvisor && useradd --uid $(UID) --gid $(GID) -d $(HOME) gvisor\"\nbazel-server:\ndocker exec gvisor-bazel true || \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow non-unique group IDs in bazel docker containers
Allow non-unique group IDs in the bazel docker container in order to avoid
failures using host group IDs that are already present in the image.
Issue #801
PiperOrigin-RevId: 267306089 |
259,993 | 05.09.2019 07:16:36 | 14,400 | 4573efe84b2d52112a9370dd5a469e9d11959ab4 | Switch from net to unet to open Unix Domain Sockets. | [
{
"change_type": "MODIFY",
"old_path": "pkg/fd/BUILD",
"new_path": "pkg/fd/BUILD",
"diff": "@@ -7,6 +7,9 @@ go_library(\nsrcs = [\"fd.go\"],\nimportpath = \"gvisor.dev/gvisor/pkg/fd\",\nvisibility = [\"//visibility:public\"],\n+ deps = [\n+ \"//pkg/unet\",\n+ ],\n)\ngo_test(\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/fd/fd.go",
"new_path": "pkg/fd/fd.go",
"diff": "@@ -22,7 +22,7 @@ import (\n\"runtime\"\n\"sync/atomic\"\n\"syscall\"\n- \"net\"\n+ \"gvisor.dev/gvisor/pkg/unet\"\n)\n// ReadWriter implements io.ReadWriter, io.ReaderAt, and io.WriterAt for fd. It\n@@ -186,19 +186,10 @@ func OpenAt(dir *FD, path string, flags int, mode uint32) (*FD, error) {\nreturn New(f), nil\n}\n-// OpenUnix TODO: DOC\n+// OpenUnix Open a Unix Domain Socket and return the file descriptor for it.\nfunc OpenUnix(path string) (*FD, error) {\n- addr, _ := net.ResolveUnixAddr(\"unix\", path)\n- f, err := net.DialUnix(\"unix\", nil, addr); if err != nil {\n- return nil, fmt.Errorf(\"unable to open socket: %q, err: %v\", path, err)\n- }\n- fConnd, err := f.File(); if err != nil {\n- return nil, fmt.Errorf(\"unable to convert to os.File: %q, err: %v\", path, err)\n- }\n- fdConnd, err := NewFromFile(fConnd); if err != nil {\n- return nil, fmt.Errorf(\"unable to convert os.File to fd.FD: %q, err: %v\", path, err)\n- }\n- return fdConnd, nil\n+ socket, err := unet.Connect(path, false)\n+ return New(socket.FD()), err\n}\n// Close closes the file descriptor contained in the FD.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Switch from net to unet to open Unix Domain Sockets. |
259,993 | 05.09.2019 15:26:16 | 14,400 | 4288a578832eae652f73ae411ece2d4b6590062e | Remove seccomp permissions, and clean up the Attach logic. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -36,23 +36,6 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.AllowAny{},\n},\n},\n- syscall.SYS_SETSOCKOPT: []seccomp.Rule{\n- {\n- seccomp.AllowAny{},\n- seccomp.AllowValue(syscall.SOL_SOCKET),\n- seccomp.AllowValue(syscall.SO_BROADCAST),\n- },\n- },\n- syscall.SYS_GETSOCKNAME: []seccomp.Rule{\n- {\n- seccomp.AllowAny{},\n- },\n- },\n- syscall.SYS_GETPEERNAME: []seccomp.Rule{\n- {\n- seccomp.AllowAny{},\n- },\n- },\nsyscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n{seccomp.AllowValue(linux.ARCH_GET_FS)},\n{seccomp.AllowValue(linux.ARCH_SET_FS)},\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -128,31 +128,22 @@ func (a *attachPoint) Attach() (p9.File, error) {\nreturn nil, fmt.Errorf(\"stat file %q, err: %v\", a.prefix, err)\n}\n- // Apply the S_IFMT bitmask so we can detect file type appropriately\n- fmtStat := stat.Mode & syscall.S_IFMT\n+ // Hold the file descriptor we are converting into a p9.File\n+ var f *fd.FD\n- switch fmtStat{\n- case syscall.S_IFSOCK:\n+ // Apply the S_IFMT bitmask so we can detect file type appropriately\n+ switch fmtStat := stat.Mode & syscall.S_IFMT; {\n+ case fmtStat == syscall.S_IFSOCK:\n// Attempt to open a connection. Bubble up the failures.\n- f, err := fd.OpenUnix(a.prefix); if err != nil {\n+ f, err = fd.OpenUnix(a.prefix)\n+ if err != nil {\nreturn nil, err\n}\n- // Close the connection if the UDS is already attached.\n- a.attachedMu.Lock()\n- defer a.attachedMu.Unlock()\n- if a.attached {\n- f.Close()\n- return nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n- }\n- a.attached = true\n-\n- // Return a localFile object to the caller with the UDS FD included.\n- return newLocalFile(a, f, a.prefix, stat)\n-\ndefault:\n// Default to Read/Write permissions.\nmode := syscall.O_RDWR\n+\n// If the configuration is Read Only & the mount point is a directory,\n// set the mode to Read Only.\nif a.conf.ROMount || fmtStat == syscall.S_IFDIR {\n@@ -160,12 +151,13 @@ func (a *attachPoint) Attach() (p9.File, error) {\n}\n// Open the mount point & capture the FD.\n- f, err := fd.Open(a.prefix, openFlags|mode, 0)\n+ f, err = fd.Open(a.prefix, openFlags|mode, 0)\nif err != nil {\nreturn nil, fmt.Errorf(\"unable to open file %q, err: %v\", a.prefix, err)\n}\n+ }\n- // If the mount point has already been attached, close the FD.\n+ // Close the connection if the UDS is already attached.\na.attachedMu.Lock()\ndefer a.attachedMu.Unlock()\nif a.attached {\n@@ -174,10 +166,9 @@ func (a *attachPoint) Attach() (p9.File, error) {\n}\na.attached = true\n- // Return a localFile object to the caller with the mount point FD\n+ // Return a localFile object to the caller with the UDS FD included.\nreturn newLocalFile(a, f, a.prefix, stat)\n}\n-}\n// makeQID returns a unique QID for the given stat buffer.\nfunc (a *attachPoint) makeQID(stat syscall.Stat_t) p9.QID {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove seccomp permissions, and clean up the Attach logic. |
259,858 | 05.09.2019 16:37:06 | 25,200 | 1a0a940587e4db8923ca81b78d7bba395eb56ce1 | Fix repository build scripts
This has the following fixes:
* Packages are passed to the tools/make_repository.sh command.
* All matching tags are built, for commits with multiple.
* The binary path is generated by the build command.
* Output from signing the repository is supressed.
* Allow a release author. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -24,16 +24,17 @@ pkg=$(build -c opt --host_force_python=py2 //runsc:runsc-debian)\n# Build a repository, if the key is available.\nif [[ -v KOKORO_REPO_KEY ]]; then\n- repo=$(tools/make_repository.sh \"${KOKORO_REPO_KEY}\" [email protected])\n+ repo=$(tools/make_repository.sh \"${KOKORO_REPO_KEY}\" [email protected] ${pkg})\nfi\n# Install installs artifacts.\ninstall() {\n- mkdir -p $1\n- cp \"${runsc}\" \"$1\"/runsc\n- sha512sum \"$1\"/runsc | awk '{print $1 \" runsc\"}' > \"$1\"/runsc.sha512\n+ local dir=\"$1\"\n+ mkdir -p \"${dir}\"\n+ cp -f \"${runsc}\" \"${dir}\"/runsc\n+ sha512sum \"${dir}\"/runsc | awk '{print $1 \" runsc\"}' > \"${dir}\"/runsc.sha512\nif [[ -v repo ]]; then\n- cp -a \"${repo}\" \"${latest_dir}\"/repo\n+ rm -rf \"${dir}\"/repo && cp -a \"${repo}\" \"$dir\"/repo\nfi\n}\n@@ -49,14 +50,19 @@ if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\n# Is it a tagged release? Build that instead. In that case, we also try to\n# update the base release directory, in case this is an update. Finally, we\n# update the \"release\" directory, which has the last released version.\n- tag=\"$(git describe --exact-match --tags HEAD || true)\"\n- if ! [[ -z \"${tag}\" ]]; then\n- install \"${KOKORO_ARTIFACTS_DIR}/${tag}\"\n- base=$(echo \"${tag}\" | cut -d'.' -f1)\n+ tags=\"$(git tag --points-at HEAD)\"\n+ if ! [[ -z \"${tags}\" ]]; then\n+ # Note that a given commit can match any number of tags. We have to\n+ # iterate through all possible tags and produce associated artifacts.\n+ for tag in ${tags}; do\n+ name=$(echo \"${tag}\" | cut -d'-' -f2)\n+ base=$(echo \"${name}\" | cut -d'.' -f1)\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/${name}\"\nif [[ \"${base}\" != \"${tag}\" ]]; then\n- install \"${KOKORO_ARTIFACTS_DIR}/${base}\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/${base}\"\nfi\n- install \"${KOKORO_ARTIFACTS_DIR}/release\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/latest\"\n+ done\nfi\nfi\nfi\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/common_bazel.sh",
"new_path": "scripts/common_bazel.sh",
"diff": "@@ -48,7 +48,8 @@ fi\n# Wrap bazel.\nfunction build() {\n- bazel build \"${BAZEL_RBE_FLAGS[@]}\" \"${BAZEL_RBE_AUTH_FLAGS[@]}\" \"${BAZEL_FLAGS[@]}\" \"$@\"\n+ bazel build \"${BAZEL_RBE_FLAGS[@]}\" \"${BAZEL_RBE_AUTH_FLAGS[@]}\" \"${BAZEL_FLAGS[@]}\" \"$@\" 2>&1 |\n+ tee /dev/fd/2 | grep -E '^ bazel-bin/' | awk '{ print $1; }'\n}\nfunction test() {\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/release.sh",
"new_path": "scripts/release.sh",
"diff": "@@ -26,9 +26,13 @@ if ! [[ -v KOKORO_RELEASE_TAG ]]; then\nexit 1\nfi\n+# Unless an explicit releaser is provided, use the bot e-mail.\n+declare -r KOKORO_RELEASE_AUTHOR=${KOKORO_RELEASE_AUTHOR:-gvisor-bot}\n+declare -r EMAIL=${EMAIL:-${KOKORO_RELEASE_AUTHOR}@google.com}\n+\n# Ensure we have an appropriate configuration for the tag.\ngit config --get user.name || git config user.name \"gVisor-bot\"\n-git config --get user.email || git config user.email \"[email protected]\"\n+git config --get user.email || git config user.email \"${EMAIL}\"\n# Run the release tool, which pushes to the origin repository.\ntools/tag_release.sh \"${KOKORO_RELEASE_COMMIT}\" \"${KOKORO_RELEASE_TAG}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/make_repository.sh",
"new_path": "tools/make_repository.sh",
"diff": "@@ -37,10 +37,10 @@ cleanup() {\nrm -f \"${keyring}\"\n}\ntrap cleanup EXIT\n-gpg --no-default-keyring --keyring \"${keyring}\" --import \"${private_key}\"\n+gpg --no-default-keyring --keyring \"${keyring}\" --import \"${private_key}\" >&2\n# Export the public key from the keyring.\n-gpg --no-default-keyring --keyring \"${keyring}\" --armor --export \"${signer}\" > \"${tmpdir}\"/keyFile\n+gpg --no-default-keyring --keyring \"${keyring}\" --armor --export \"${signer}\" > \"${tmpdir}\"/keyFile >&2\n# Copy the packages, and ensure permissions are correct.\ncp -a \"$@\" \"${tmpdir}\" && chmod 0644 \"${tmpdir}\"/*\n@@ -52,7 +52,7 @@ find \"${tmpdir}\" -type l -exec rm -f {} \\;\n# Sign all packages.\nfor file in \"${tmpdir}\"/*.deb; do\n- dpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\"\n+ dpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\" >&2\ndone\n# Build the package list.\n@@ -62,8 +62,8 @@ done\n(cd \"${tmpdir}\" && apt-ftparchive release . > Release)\n# Sign the release.\n-(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" --clearsign -o InRelease Release)\n-(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" -abs -o Release.gpg Release)\n+(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" --clearsign -o InRelease Release >&2)\n+(cd \"${tmpdir}\" && gpg --no-default-keyring --keyring \"${keyring}\" -abs -o Release.gpg Release >&2)\n# Show the results.\necho \"${tmpdir}\"\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix repository build scripts
This has the following fixes:
* Packages are passed to the tools/make_repository.sh command.
* All matching tags are built, for commits with multiple.
* The binary path is generated by the build command.
* Output from signing the repository is supressed.
* Allow a release author.
Change-Id: I2d08954ba76e35612f352be99d5bb99080f80892 |
259,992 | 05.09.2019 11:13:59 | 25,200 | cac17854648c71d00e8067314fd144525964dd53 | Add that Docker user defined network doesn't work to the FAQ | [
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/FAQ.md",
"new_path": "content/docs/user_guide/FAQ.md",
"diff": "@@ -27,6 +27,14 @@ Binaries run in gVisor should be built for the\nYes. Please see the [Docker Quick Start](/docs/user_guide/docker/).\n+### Can I run Kubernets pods using gVisor.\n+\n+Yes. Please see the [Docker Quick Start](/docs/user_guide/kubernetes/).\n+\n+### What's the security model?\n+\n+See the [Security Model](../../architecture_guide/security/).\n+\n## Troubleshooting\n### My container runs fine with `runc` but fails with `runsc`\n@@ -70,8 +78,22 @@ sudo chown root:root /usr/local/bin/runsc\nsudo chmod 0755 /usr/local/bin/runsc\n```\n-### What's the security model?\n+### My container cannot resolve another container's name when using Docker user defined bridge\n-See the [Security Model](../../architecture_guide/security/).\n+Docker user defined bridge uses an embedded DNS server bound to the loopback\n+interface on address 127.0.0.10. This requires access to the host network in\n+order to communicate to the DNS server. runsc network is isolated from the\n+host, therefore it cannot access the DNS server on the host network without\n+breaking the sandbox isolation. There are a few different workarounds you can\n+try:\n+\n+* Use default bridge network with `--link` to connect containers. Default\n+ bridge doesn't use embedded DNS.\n+* Use [`--network=host`][host-net] option in runsc, however beware that it will\n+ use the host network stack and is less secure.\n+* Use IPs instead of container names.\n+* Use [Kubernetes][k8s]. Container name lookup works fine in Kubernetes.\n[old-linux]: /docs/user_guide/networking/#gso\n+[host-net]: /docs/user_guide/networking/#network-passthrough\n+[k8s]: /docs/user_guide/kubernetes\n\\ No newline at end of file\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add that Docker user defined network doesn't work to the FAQ |
259,884 | 10.09.2019 07:09:08 | 0 | b9b719dcb6acde3b58e983b27bf34ad591bae16b | Add note about some days not having releases
Issue | [
{
"change_type": "MODIFY",
"old_path": "content/docs/includes/install_gvisor.md",
"new_path": "content/docs/includes/install_gvisor.md",
"diff": "@@ -2,10 +2,13 @@ The easiest way to get `runsc` is from the [latest nightly\nbuild][latest-nightly]. After you download the binary, check it against the\nSHA512 [checksum file][latest-hash].\n-Older builds can also be found here:\n+Older builds can also be found here (note that some days may not have releases\n+due to failing builds):\n+\n`https://storage.googleapis.com/gvisor/releases/nightly/${yyyy-mm-dd}/runsc`\nWith corresponding SHA512 checksums here:\n+\n`https://storage.googleapis.com/gvisor/releases/nightly/${yyyy-mm-dd}/runsc.sha512`\n**It is important to copy this binary to a location that is accessible to all\n@@ -26,5 +29,7 @@ a good place to put the `runsc` binary.\n```\n[latest-nightly]: https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc\n+\n[latest-hash]: https://storage.googleapis.com/gvisor/releases/nightly/latest/runsc.sha512\n+\n[oci]: https://www.opencontainers.org\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add note about some days not having releases
Issue #107 |
259,884 | 11.09.2019 00:07:25 | 25,200 | d24be656c9321de8b65e9d21c41f756056847eb1 | Update required Bazel version in README. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -48,7 +48,7 @@ Make sure the following dependencies are installed:\n* Linux 4.14.77+ ([older linux][old-linux])\n* [git][git]\n-* [Bazel][bazel] 0.23.0+\n+* [Bazel][bazel] 0.28.0+\n* [Python][python]\n* [Docker version 17.09.0 or greater][docker]\n* Gold linker (e.g. `binutils-gold` package on Ubuntu)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update required Bazel version in README.
PiperOrigin-RevId: 268397389 |
259,858 | 11.09.2019 18:48:26 | 25,200 | c06ef5131f1ccd3106ccf4fa4e787db079db2d96 | Fix authorization for continuous integration.
The credentials must be explicitly refreshed for pushing to
the repository on the Go branch. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/go.cfg",
"new_path": "kokoro/go.cfg",
"diff": "build_file: \"repo/scripts/go.sh\"\n+before_action {\n+ fetch_keystore {\n+ keystore_resource {\n+ keystore_config_id: 73898\n+ keyname: \"kokoro-github-access-token\"\n+ }\n+ }\n+}\n+\n+env_vars {\n+ key: \"KOKORO_GITHUB_ACCESS_TOKEN\"\n+ value: \"$KOKORO_ROOT/src/keystore/73898_kokoro-github-access-token\"\n+}\n+\nenv_vars {\nkey: \"KOKORO_GO_PUSH\"\nvalue: \"true\"\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/go.sh",
"new_path": "scripts/go.sh",
"diff": "@@ -30,5 +30,14 @@ go build ./...\n# Push, if required.\nif [[ \"${KOKORO_GO_PUSH}\" == \"true\" ]]; then\n+ if [[ -v KOKORO_GITHUB_ACCESS_TOKEN ]]; then\n+ git config --global credential.helper cache\n+ git credential approve <<EOF\n+protocol=https\n+host=github.com\n+username=$(cat \"${KOKORO_GITHUB_ACCESS_TOKEN}\")\n+password=x-oauth-basic\n+EOF\n+ fi\ngit push origin go:go\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix authorization for continuous integration.
The credentials must be explicitly refreshed for pushing to
the repository on the Go branch.
PiperOrigin-RevId: 268589817 |
259,858 | 11.09.2019 21:03:12 | 25,200 | 1e6bdd58551246f6ae662a20b733a9c9dd5ef225 | Update key environment variables. | [
{
"change_type": "MODIFY",
"old_path": "kokoro/build.cfg",
"new_path": "kokoro/build.cfg",
"diff": "@@ -11,7 +11,7 @@ before_action {\nenv_vars {\nkey: \"KOKORO_REPO_KEY\"\n- value: \"$KOKORO_ROOT/src/keystore/73898_kokoro-repo-key\"\n+ value: \"73898_kokoro-repo-key\"\n}\naction {\n"
},
{
"change_type": "MODIFY",
"old_path": "kokoro/go.cfg",
"new_path": "kokoro/go.cfg",
"diff": "@@ -11,7 +11,7 @@ before_action {\nenv_vars {\nkey: \"KOKORO_GITHUB_ACCESS_TOKEN\"\n- value: \"$KOKORO_ROOT/src/keystore/73898_kokoro-github-access-token\"\n+ value: \"73898_kokoro-github-access-token\"\n}\nenv_vars {\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -24,7 +24,7 @@ pkg=$(build -c opt --host_force_python=py2 //runsc:runsc-debian)\n# Build a repository, if the key is available.\nif [[ -v KOKORO_REPO_KEY ]]; then\n- repo=$(tools/make_repository.sh \"${KOKORO_REPO_KEY}\" [email protected] ${pkg})\n+ repo=$(tools/make_repository.sh \"${KOKORO_KEYSTORE_DIR}/${KOKORO_REPO_KEY}\" [email protected] ${pkg})\nfi\n# Install installs artifacts.\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/go.sh",
"new_path": "scripts/go.sh",
"diff": "@@ -35,7 +35,7 @@ if [[ \"${KOKORO_GO_PUSH}\" == \"true\" ]]; then\ngit credential approve <<EOF\nprotocol=https\nhost=github.com\n-username=$(cat \"${KOKORO_GITHUB_ACCESS_TOKEN}\")\n+username=$(cat \"${KOKORO_KEYSTORE_DIR}/${KOKORO_GITHUB_ACCESS_TOKEN}\")\npassword=x-oauth-basic\nEOF\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update key environment variables.
PiperOrigin-RevId: 268604220 |
259,858 | 11.09.2019 21:49:18 | 25,200 | 96a25e080c2b2e10e0d92b544f5830f85f8540e0 | Ensure appropriate tools are installed on image. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "source $(dirname $0)/common.sh\n+# Install required packages for make_repository.sh et al.\n+sudo apt-get update && sudo apt-get install -y dpkg-sig coreutils gpg apt-utils\n+\n# Build runsc.\nrunsc=$(build -c opt //runsc)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Ensure appropriate tools are installed on image.
PiperOrigin-RevId: 268608466 |
259,858 | 11.09.2019 22:29:07 | 25,200 | 69f2c41b7acc4b72df9fe5fad984e05f78bfe6cd | Drop unavailable package. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "source $(dirname $0)/common.sh\n# Install required packages for make_repository.sh et al.\n-sudo apt-get update && sudo apt-get install -y dpkg-sig coreutils gpg apt-utils\n+sudo apt-get update && sudo apt-get install -y dpkg-sig coreutils apt-utils\n# Build runsc.\nrunsc=$(build -c opt //runsc)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Drop unavailable package.
PiperOrigin-RevId: 268614014 |
259,858 | 12.09.2019 13:43:07 | 25,200 | 574eda88808138b2dd72ebe6bbca80a09a13c7fb | Update repository directory structure.
Currently it will not work with apt out of the box, as we
require the dists/ prefix, along with a distribution name.
This tweaks the overall structure to allow for the same URL
prefix to be used for all repositories, and enables multiple
architectures.
Fixes | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -32,12 +32,14 @@ fi\n# Install installs artifacts.\ninstall() {\n- local dir=\"$1\"\n- mkdir -p \"${dir}\"\n- cp -f \"${runsc}\" \"${dir}\"/runsc\n- sha512sum \"${dir}\"/runsc | awk '{print $1 \" runsc\"}' > \"${dir}\"/runsc.sha512\n+ local -r binaries_dir=\"$1\"\n+ local -r repo_dir=\"$2\"\n+ mkdir -p \"${binaries_dir}\"\n+ cp -f \"${runsc}\" \"${binaries_dir}\"/runsc\n+ sha512sum \"${binaries_dir}\"/runsc | awk '{print $1 \" runsc\"}' > \"${binaries_dir}\"/runsc.sha512\nif [[ -v repo ]]; then\n- rm -rf \"${dir}\"/repo && cp -a \"${repo}\" \"$dir\"/repo\n+ rm -rf \"${repo_dir}\" && mkdir -p \"$(dirname \"${repo_dir}\")\"\n+ cp -a \"${repo}\" \"${repo_dir}\"\nfi\n}\n@@ -47,8 +49,11 @@ install() {\nif [[ -v KOKORO_ARTIFACTS_DIR ]]; then\nif [[ \"${KOKORO_BUILD_NIGHTLY}\" == \"true\" ]]; then\n# The \"latest\" directory and current date.\n- install \"${KOKORO_ARTIFACTS_DIR}/nightly/latest\"\n- install \"${KOKORO_ARTIFACTS_DIR}/nightly/$(date -Idate)\"\n+ stamp=\"$(date -Idate)\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/nightly/latest\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/nightly/main\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/nightly/${stamp}\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/nightly/${stamp}\"\nelse\n# Is it a tagged release? Build that instead. In that case, we also try to\n# update the base release directory, in case this is an update. Finally, we\n@@ -60,11 +65,14 @@ if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\nfor tag in ${tags}; do\nname=$(echo \"${tag}\" | cut -d'-' -f2)\nbase=$(echo \"${name}\" | cut -d'.' -f1)\n- install \"${KOKORO_ARTIFACTS_DIR}/release/${name}\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/${name}\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/${name}/main\"\nif [[ \"${base}\" != \"${tag}\" ]]; then\n- install \"${KOKORO_ARTIFACTS_DIR}/release/${base}\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/${base}\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/${base}/main\"\nfi\n- install \"${KOKORO_ARTIFACTS_DIR}/release/latest\"\n+ install \"${KOKORO_ARTIFACTS_DIR}/release/latest\" \\\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/latest/main\"\ndone\nfi\nfi\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/make_repository.sh",
"new_path": "tools/make_repository.sh",
"diff": "@@ -39,11 +39,18 @@ cleanup() {\ntrap cleanup EXIT\ngpg --no-default-keyring --keyring \"${keyring}\" --import \"${private_key}\" >&2\n-# Export the public key from the keyring.\n-gpg --no-default-keyring --keyring \"${keyring}\" --armor --export \"${signer}\" > \"${tmpdir}\"/keyFile >&2\n-\n# Copy the packages, and ensure permissions are correct.\n-cp -a \"$@\" \"${tmpdir}\" && chmod 0644 \"${tmpdir}\"/*\n+for pkg in \"$@\"; do\n+ name=$(basename \"${pkg}\" .deb)\n+ name=$(basename \"${name}\" .changes)\n+ arch=${name##*_}\n+ if [[ \"${name}\" == \"${arch}\" ]]; then\n+ continue # Not a regular package.\n+ fi\n+ mkdir -p \"${tmpdir}\"/binary-\"${arch}\"\n+ cp -a \"${pkg}\" \"${tmpdir}\"/binary-\"${arch}\"\n+done\n+find \"${tmpdir}\" -type f -exec chmod 0644 {} \\;\n# Ensure there are no symlinks hanging around; these may be remnants of the\n# build process. They may be useful for other things, but we are going to build\n@@ -51,12 +58,14 @@ cp -a \"$@\" \"${tmpdir}\" && chmod 0644 \"${tmpdir}\"/*\nfind \"${tmpdir}\" -type l -exec rm -f {} \\;\n# Sign all packages.\n-for file in \"${tmpdir}\"/*.deb; do\n+for file in \"${tmpdir}\"/binary-*/*.deb; do\ndpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\" >&2\ndone\n# Build the package list.\n-(cd \"${tmpdir}\" && apt-ftparchive packages . | gzip > Packages.gz)\n+for dir in \"${tmpdir}\"/binary-*; do\n+ (cd \"${dir}\" && apt-ftparchive packages . | gzip > Packages.gz)\n+done\n# Build the release list.\n(cd \"${tmpdir}\" && apt-ftparchive release . > Release)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update repository directory structure.
Currently it will not work with apt out of the box, as we
require the dists/ prefix, along with a distribution name.
This tweaks the overall structure to allow for the same URL
prefix to be used for all repositories, and enables multiple
architectures.
Fixes #852
PiperOrigin-RevId: 268756104 |
259,858 | 13.09.2019 11:38:40 | 25,200 | 2bbf73d9ed85bbff81f1e56a6753dfe402682459 | Remove stale configurations. | [
{
"change_type": "DELETE",
"old_path": "cloudbuild/go.Dockerfile",
"new_path": null,
"diff": "-FROM ubuntu\n-RUN apt-get -q update && apt-get install -qqy git rsync\n"
},
{
"change_type": "DELETE",
"old_path": "cloudbuild/go.yaml",
"new_path": null,
"diff": "-steps:\n-- name: 'gcr.io/cloud-builders/git'\n- args: ['fetch', '--all', '--unshallow']\n-- name: 'gcr.io/cloud-builders/bazel'\n- args: ['build', ':gopath']\n-- name: 'gcr.io/cloud-builders/docker'\n- args: ['build', '-t', 'gcr.io/$PROJECT_ID/go-branch', '-f', 'cloudbuild/go.Dockerfile', '.']\n-- name: 'gcr.io/$PROJECT_ID/go-branch'\n- args: ['tools/go_branch.sh']\n-- name: 'gcr.io/cloud-builders/git'\n- args: ['checkout', 'go']\n-- name: 'gcr.io/cloud-builders/git'\n- args: ['clean', '-f']\n-- name: 'golang'\n- args: ['go', 'build', './...']\n-- name: 'gcr.io/cloud-builders/git'\n- entrypoint: 'bash'\n- args:\n- - '-c'\n- - 'if [[ \"$BRANCH_NAME\" == \"master\" ]]; then git push \"${_ORIGIN}\" go:go; fi'\n-substitutions:\n- _ORIGIN: origin\n"
},
{
"change_type": "DELETE",
"old_path": "kokoro/continuous.cfg",
"new_path": null,
"diff": "-# This is a temporary file. It will be removed when new Kokoro jobs exist for\n-# all the other presubmits.\n-build_file: \"repo/scripts/build.sh\"\n-\n-action {\n- define_artifacts {\n- regex: \"**/sponge_log.xml\"\n- regex: \"**/sponge_log.log\"\n- regex: \"**/outputs.zip\"\n- }\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "kokoro/presubmit.cfg",
"new_path": null,
"diff": "-# This is a temporary file. It will be removed when new Kokoro jobs exist for\n-# all the other presubmits.\n-build_file: \"repo/kokoro/run_tests.sh\"\n-\n-action {\n- define_artifacts {\n- regex: \"**/sponge_log.xml\"\n- regex: \"**/sponge_log.log\"\n- regex: \"**/outputs.zip\"\n- }\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "kokoro/release-nightly.cfg",
"new_path": null,
"diff": "-# This file is a temporary bridge. It will be removed shortly, when Kokoro jobs\n-# are configured to point at the new build and release configurations.\n-build_file: \"repo/kokoro/run_build.sh\"\n-\n-action {\n- define_artifacts {\n- regex: \"**/runsc\"\n- regex: \"**/runsc.sha512\"\n- }\n-}\n"
},
{
"change_type": "DELETE",
"old_path": "kokoro/run_build.sh",
"new_path": null,
"diff": "-#!/bin/bash\n-\n-# Copyright 2018 The gVisor Authors.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# http://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-# This file is a temporary bridge. We will create multiple independent Kokoro\n-# workflows that call each of the build scripts independently.\n-KOKORO_BUILD_NIGHTLY=true $(dirname $0)/../scripts/build.sh\n"
},
{
"change_type": "DELETE",
"old_path": "kokoro/run_tests.sh",
"new_path": null,
"diff": "-#!/bin/bash\n-\n-# Copyright 2019 The gVisor Authors.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# http://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-\n-set -xeo pipefail\n-\n-# This file is a temporary bridge. We will create multiple independent Kokoro\n-# workflows that call each of the test scripts independently.\n-\n-# Run all the tests in sequence.\n-$(dirname $0)/../scripts/do_tests.sh\n-$(dirname $0)/../scripts/make_tests.sh\n-$(dirname $0)/../scripts/root_tests.sh\n-$(dirname $0)/../scripts/docker_tests.sh\n-$(dirname $0)/../scripts/overlay_tests.sh\n-$(dirname $0)/../scripts/hostnet_tests.sh\n-$(dirname $0)/../scripts/simple_tests.sh\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove stale configurations.
PiperOrigin-RevId: 268947847 |
259,853 | 13.09.2019 21:43:12 | 25,200 | 239a07aabfad8991556b43c85c30270d09353f86 | gvisor: return ENOTDIR from the unlink syscall
ENOTDIR has to be returned when a component used as a directory in
pathname is not, in fact, a directory. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dirent.go",
"new_path": "pkg/sentry/fs/dirent.go",
"diff": "@@ -1126,7 +1126,7 @@ func (d *Dirent) unmount(ctx context.Context, replacement *Dirent) error {\n// Remove removes the given file or symlink. The root dirent is used to\n// resolve name, and must not be nil.\n-func (d *Dirent) Remove(ctx context.Context, root *Dirent, name string) error {\n+func (d *Dirent) Remove(ctx context.Context, root *Dirent, name string, dirPath bool) error {\n// Check the root.\nif root == nil {\npanic(\"Dirent.Remove: root must not be nil\")\n@@ -1151,6 +1151,8 @@ func (d *Dirent) Remove(ctx context.Context, root *Dirent, name string) error {\n// Remove cannot remove directories.\nif IsDir(child.Inode.StableAttr) {\nreturn syscall.EISDIR\n+ } else if dirPath {\n+ return syscall.ENOTDIR\n}\n// Remove cannot remove a mount point.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/dirent_refs_test.go",
"new_path": "pkg/sentry/fs/dirent_refs_test.go",
"diff": "@@ -343,7 +343,7 @@ func TestRemoveExtraRefs(t *testing.T) {\n}\nd := f.Dirent\n- if err := test.root.Remove(contexttest.Context(t), test.root, name); err != nil {\n+ if err := test.root.Remove(contexttest.Context(t), test.root, name, false /* dirPath */); err != nil {\nt.Fatalf(\"root.Remove(root, %q) failed: %v\", name, err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_file.go",
"new_path": "pkg/sentry/syscalls/linux/sys_file.go",
"diff": "@@ -1423,9 +1423,6 @@ func unlinkAt(t *kernel.Task, dirFD int32, addr usermem.Addr) error {\nif err != nil {\nreturn err\n}\n- if dirPath {\n- return syserror.ENOENT\n- }\nreturn fileOpAt(t, dirFD, path, func(root *fs.Dirent, d *fs.Dirent, name string, _ uint) error {\nif !fs.IsDir(d.Inode.StableAttr) {\n@@ -1436,7 +1433,7 @@ func unlinkAt(t *kernel.Task, dirFD int32, addr usermem.Addr) error {\nreturn err\n}\n- return d.Remove(t, root, name)\n+ return d.Remove(t, root, name, dirPath)\n})\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/unlink.cc",
"new_path": "test/syscalls/linux/unlink.cc",
"diff": "@@ -123,6 +123,8 @@ TEST(UnlinkTest, AtBad) {\nSyscallSucceeds());\nEXPECT_THAT(unlinkat(dirfd, \"UnlinkAtFile\", AT_REMOVEDIR),\nSyscallFailsWithErrno(ENOTDIR));\n+ EXPECT_THAT(unlinkat(dirfd, \"UnlinkAtFile/\", 0),\n+ SyscallFailsWithErrno(ENOTDIR));\nASSERT_THAT(close(fd), SyscallSucceeds());\nEXPECT_THAT(unlinkat(dirfd, \"UnlinkAtFile\", 0), SyscallSucceeds());\n"
}
] | Go | Apache License 2.0 | google/gvisor | gvisor: return ENOTDIR from the unlink syscall
ENOTDIR has to be returned when a component used as a directory in
pathname is not, in fact, a directory.
PiperOrigin-RevId: 269037893 |
259,854 | 17.09.2019 11:29:03 | 25,200 | 747320a7aa013f6b987f8f52173f51ff3aedb66c | Update remaining users of LinkEndpoints to not refer to them as an ID. | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/sample/tun_tcp_connect/main.go",
"new_path": "pkg/tcpip/sample/tun_tcp_connect/main.go",
"diff": "@@ -138,11 +138,11 @@ func main() {\nlog.Fatal(err)\n}\n- linkID, err := fdbased.New(&fdbased.Options{FDs: []int{fd}, MTU: mtu})\n+ linkEP, err := fdbased.New(&fdbased.Options{FDs: []int{fd}, MTU: mtu})\nif err != nil {\nlog.Fatal(err)\n}\n- if err := s.CreateNIC(1, sniffer.New(linkID)); err != nil {\n+ if err := s.CreateNIC(1, sniffer.New(linkEP)); err != nil {\nlog.Fatal(err)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/sample/tun_tcp_echo/main.go",
"new_path": "pkg/tcpip/sample/tun_tcp_echo/main.go",
"diff": "@@ -128,7 +128,7 @@ func main() {\nlog.Fatal(err)\n}\n- linkID, err := fdbased.New(&fdbased.Options{\n+ linkEP, err := fdbased.New(&fdbased.Options{\nFDs: []int{fd},\nMTU: mtu,\nEthernetHeader: *tap,\n@@ -137,7 +137,7 @@ func main() {\nif err != nil {\nlog.Fatal(err)\n}\n- if err := s.CreateNIC(1, linkID); err != nil {\n+ if err := s.CreateNIC(1, linkEP); err != nil {\nlog.Fatal(err)\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update remaining users of LinkEndpoints to not refer to them as an ID.
PiperOrigin-RevId: 269614517 |
259,853 | 17.09.2019 12:44:05 | 25,200 | 3b7119a7c91789f69d8637401a1359229a33b213 | platform/ptrace: log exit code for stub processes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/ptrace_unsafe.go",
"new_path": "pkg/sentry/platform/ptrace/ptrace_unsafe.go",
"diff": "@@ -154,3 +154,19 @@ func (t *thread) clone() (*thread, error) {\ncpu: ^uint32(0),\n}, nil\n}\n+\n+// getEventMessage retrieves a message about the ptrace event that just happened.\n+func (t *thread) getEventMessage() (uintptr, error) {\n+ var msg uintptr\n+ _, _, errno := syscall.RawSyscall6(\n+ syscall.SYS_PTRACE,\n+ syscall.PTRACE_GETEVENTMSG,\n+ uintptr(t.tid),\n+ 0,\n+ uintptr(unsafe.Pointer(&msg)),\n+ 0, 0)\n+ if errno != 0 {\n+ return msg, errno\n+ }\n+ return msg, nil\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/platform/ptrace/subprocess.go",
"new_path": "pkg/sentry/platform/ptrace/subprocess.go",
"diff": "@@ -355,7 +355,8 @@ func (t *thread) wait(outcome waitOutcome) syscall.Signal {\n}\nif stopSig == syscall.SIGTRAP {\nif status.TrapCause() == syscall.PTRACE_EVENT_EXIT {\n- t.dumpAndPanic(\"wait failed: the process exited\")\n+ msg, err := t.getEventMessage()\n+ t.dumpAndPanic(fmt.Sprintf(\"wait failed: the process %d:%d exited: %x (err %v)\", t.tgid, t.tid, msg, err))\n}\n// Re-encode the trap cause the way it's expected.\nreturn stopSig | syscall.Signal(status.TrapCause()<<8)\n@@ -426,6 +427,9 @@ func (t *thread) syscall(regs *syscall.PtraceRegs) (uintptr, error) {\nbreak\n} else {\n// Some other signal caused a thread stop; ignore.\n+ if sig != syscall.SIGSTOP && sig != syscall.SIGCHLD {\n+ log.Warningf(\"The thread %d:%d has been interrupted by %d\", t.tgid, t.tid, sig)\n+ }\ncontinue\n}\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | platform/ptrace: log exit code for stub processes
PiperOrigin-RevId: 269631877 |
259,853 | 17.09.2019 17:24:39 | 25,200 | b63d56b0b4430de7273e3b759667a823927c0473 | scripts/build.sh: fix kokoro failure "KOKORO_BUILD_NIGHTLY: unbound variable" | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -47,7 +47,7 @@ install() {\n# current date. If the current commit happens to correpond to a tag, then we\n# will also move everything into a directory named after the given tag.\nif [[ -v KOKORO_ARTIFACTS_DIR ]]; then\n- if [[ \"${KOKORO_BUILD_NIGHTLY}\" == \"true\" ]]; then\n+ if [[ \"${KOKORO_BUILD_NIGHTLY:-false}\" == \"true\" ]]; then\n# The \"latest\" directory and current date.\nstamp=\"$(date -Idate)\"\ninstall \"${KOKORO_ARTIFACTS_DIR}/nightly/latest\" \\\n"
}
] | Go | Apache License 2.0 | google/gvisor | scripts/build.sh: fix kokoro failure "KOKORO_BUILD_NIGHTLY: unbound variable"
PiperOrigin-RevId: 269690988 |
259,858 | 18.09.2019 14:55:55 | 25,200 | 461123ea3510a401423181e8ea8f2cae27fcbc8f | Move the component into the repository structure.
The RELEASE file must be at the top-level for the signed
repository to work correctly. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -27,7 +27,7 @@ pkg=$(build -c opt --host_force_python=py2 //runsc:runsc-debian)\n# Build a repository, if the key is available.\nif [[ -v KOKORO_REPO_KEY ]]; then\n- repo=$(tools/make_repository.sh \"${KOKORO_KEYSTORE_DIR}/${KOKORO_REPO_KEY}\" [email protected] ${pkg})\n+ repo=$(tools/make_repository.sh \"${KOKORO_KEYSTORE_DIR}/${KOKORO_REPO_KEY}\" [email protected] main ${pkg})\nfi\n# Install installs artifacts.\n@@ -51,7 +51,7 @@ if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\n# The \"latest\" directory and current date.\nstamp=\"$(date -Idate)\"\ninstall \"${KOKORO_ARTIFACTS_DIR}/nightly/latest\" \\\n- \"${KOKORO_ARTIFACTS_DIR}/dists/nightly/main\"\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/nightly/latest\"\ninstall \"${KOKORO_ARTIFACTS_DIR}/nightly/${stamp}\" \\\n\"${KOKORO_ARTIFACTS_DIR}/dists/nightly/${stamp}\"\nelse\n@@ -66,13 +66,13 @@ if [[ -v KOKORO_ARTIFACTS_DIR ]]; then\nname=$(echo \"${tag}\" | cut -d'-' -f2)\nbase=$(echo \"${name}\" | cut -d'.' -f1)\ninstall \"${KOKORO_ARTIFACTS_DIR}/release/${name}\" \\\n- \"${KOKORO_ARTIFACTS_DIR}/dists/${name}/main\"\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/${name}\"\nif [[ \"${base}\" != \"${tag}\" ]]; then\ninstall \"${KOKORO_ARTIFACTS_DIR}/release/${base}\" \\\n- \"${KOKORO_ARTIFACTS_DIR}/dists/${base}/main\"\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/${base}\"\nfi\ninstall \"${KOKORO_ARTIFACTS_DIR}/release/latest\" \\\n- \"${KOKORO_ARTIFACTS_DIR}/dists/latest/main\"\n+ \"${KOKORO_ARTIFACTS_DIR}/dists/latest\"\ndone\nfi\nfi\n"
},
{
"change_type": "MODIFY",
"old_path": "tools/make_repository.sh",
"new_path": "tools/make_repository.sh",
"diff": "# Parse arguments. We require more than two arguments, which are the private\n# keyring, the e-mail associated with the signer, and the list of packages.\n-if [ \"$#\" -le 2 ]; then\n- echo \"usage: $0 <private-key> <signer-email> <packages...>\"\n+if [ \"$#\" -le 3 ]; then\n+ echo \"usage: $0 <private-key> <signer-email> <component> <packages...>\"\nexit 1\nfi\ndeclare -r private_key=$(readlink -e \"$1\")\ndeclare -r signer=\"$2\"\n-shift; shift\n+declare -r component=\"$3\"\n+shift; shift; shift\n# Verbose from this point.\nset -xeo pipefail\n@@ -47,8 +48,8 @@ for pkg in \"$@\"; do\nif [[ \"${name}\" == \"${arch}\" ]]; then\ncontinue # Not a regular package.\nfi\n- mkdir -p \"${tmpdir}\"/binary-\"${arch}\"\n- cp -a \"${pkg}\" \"${tmpdir}\"/binary-\"${arch}\"\n+ mkdir -p \"${tmpdir}\"/\"${component}\"/binary-\"${arch}\"\n+ cp -a \"${pkg}\" \"${tmpdir}\"/\"${component}\"/binary-\"${arch}\"\ndone\nfind \"${tmpdir}\" -type f -exec chmod 0644 {} \\;\n@@ -58,12 +59,12 @@ find \"${tmpdir}\" -type f -exec chmod 0644 {} \\;\nfind \"${tmpdir}\" -type l -exec rm -f {} \\;\n# Sign all packages.\n-for file in \"${tmpdir}\"/binary-*/*.deb; do\n+for file in \"${tmpdir}\"/\"${component}\"/binary-*/*.deb; do\ndpkg-sig -g \"--no-default-keyring --keyring ${keyring}\" --sign builder \"${file}\" >&2\ndone\n# Build the package list.\n-for dir in \"${tmpdir}\"/binary-*; do\n+for dir in \"${tmpdir}\"/\"${component}\"/binary-*; do\n(cd \"${dir}\" && apt-ftparchive packages . | gzip > Packages.gz)\ndone\n"
}
] | Go | Apache License 2.0 | google/gvisor | Move the component into the repository structure.
The RELEASE file must be at the top-level for the signed
repository to work correctly.
PiperOrigin-RevId: 269897109 |
259,974 | 17.09.2019 08:27:01 | 0 | cabe10e603f36d610b7d3858c0911fc2dde26411 | Enable pkg/sentry/hostcpu support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/hostcpu/BUILD",
"new_path": "pkg/sentry/hostcpu/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nname = \"hostcpu\",\nsrcs = [\n\"getcpu_amd64.s\",\n+ \"getcpu_arm64.s\",\n\"hostcpu.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/hostcpu\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable pkg/sentry/hostcpu support on arm64.
Signed-off-by: Haibo Xu [email protected]
Change-Id: I333872da9bdf56ddfa8ab2f034dfc1f36a7d3132 |
259,993 | 19.09.2019 12:37:15 | 14,400 | ac38a7ead0870118d27d570a8a98a90a7a225a12 | Place the host UDS mounting behind --fsgofer-host-uds-allowed.
This commit allows the use of the `--fsgofer-host-uds-allowed` flag to
enable mounting sockets and add the appropriate seccomp filters. | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -138,6 +138,9 @@ type Config struct {\n// Overlay is whether to wrap the root filesystem in an overlay.\nOverlay bool\n+ // fsGoferHostUDSAllowed enables the gofer to mount a host UDS\n+ FSGoferHostUDSAllowed bool\n+\n// Network indicates what type of network to use.\nNetwork NetworkType\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -59,6 +59,7 @@ type Gofer struct {\nbundleDir string\nioFDs intFlags\napplyCaps bool\n+ hostUDSAllowed bool\nsetUpRoot bool\npanicOnWrite bool\n@@ -86,6 +87,7 @@ func (g *Gofer) SetFlags(f *flag.FlagSet) {\nf.StringVar(&g.bundleDir, \"bundle\", \"\", \"path to the root of the bundle directory, defaults to the current directory\")\nf.Var(&g.ioFDs, \"io-fds\", \"list of FDs to connect 9P servers. They must follow this order: root first, then mounts as defined in the spec\")\nf.BoolVar(&g.applyCaps, \"apply-caps\", true, \"if true, apply capabilities to restrict what the Gofer process can do\")\n+ f.BoolVar(&g.hostUDSAllowed, \"host-uds-allowed\", false, \"if true, allow the Gofer to mount a host UDS\")\nf.BoolVar(&g.panicOnWrite, \"panic-on-write\", false, \"if true, panics on attempts to write to RO mounts. RW mounts are unnaffected\")\nf.BoolVar(&g.setUpRoot, \"setup-root\", true, \"if true, set up an empty root for the process\")\nf.IntVar(&g.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\n@@ -182,6 +184,7 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ncfg := fsgofer.Config{\nROMount: isReadonlyMount(m.Options),\nPanicOnWrite: g.panicOnWrite,\n+ HostUDSAllowed: g.hostUDSAllowed,\n}\nap, err := fsgofer.NewAttachPoint(m.Destination, cfg)\nif err != nil {\n@@ -200,9 +203,15 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"too many FDs passed for mounts. mounts: %d, FDs: %d\", mountIdx, len(g.ioFDs))\n}\n+ if g.hostUDSAllowed {\n+ if err := filter.InstallUDS(); err != nil {\n+ Fatalf(\"installing UDS seccomp filters: %v\", err)\n+ }\n+ } else {\nif err := filter.Install(); err != nil {\nFatalf(\"installing seccomp filters: %v\", err)\n}\n+ }\nrunServers(ats, g.ioFDs)\nreturn subcommands.ExitSuccess\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -941,6 +941,11 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\nargs = append(args, \"--panic-on-write=true\")\n}\n+ // Add support for mounting host UDS in the gofer\n+ if conf.FSGoferHostUDSAllowed {\n+ args = append(args, \"--host-uds-allowed=true\")\n+ }\n+\n// Open the spec file to donate to the sandbox.\nspecFile, err := specutils.OpenSpec(bundleDir)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -26,16 +26,6 @@ import (\n// allowedSyscalls is the set of syscalls executed by the gofer.\nvar allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_ACCEPT: {},\n- syscall.SYS_SOCKET: []seccomp.Rule{\n- {\n- seccomp.AllowValue(syscall.AF_UNIX),\n- },\n- },\n- syscall.SYS_CONNECT: []seccomp.Rule{\n- {\n- seccomp.AllowAny{},\n- },\n- },\nsyscall.SYS_ARCH_PRCTL: []seccomp.Rule{\n{seccomp.AllowValue(linux.ARCH_GET_FS)},\n{seccomp.AllowValue(linux.ARCH_SET_FS)},\n@@ -194,3 +184,16 @@ var allowedSyscalls = seccomp.SyscallRules{\nsyscall.SYS_UTIMENSAT: {},\nsyscall.SYS_WRITE: {},\n}\n+\n+var udsSyscalls = seccomp.SyscallRules{\n+ syscall.SYS_SOCKET: []seccomp.Rule{\n+ {\n+ seccomp.AllowValue(syscall.AF_UNIX),\n+ },\n+ },\n+ syscall.SYS_CONNECT: []seccomp.Rule{\n+ {\n+ seccomp.AllowAny{},\n+ },\n+ },\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/filter.go",
"new_path": "runsc/fsgofer/filter/filter.go",
"diff": "@@ -31,3 +31,15 @@ func Install() error {\nreturn seccomp.Install(s)\n}\n+\n+// InstallUDS installs the standard Gofer seccomp filters along with filters\n+// allowing the gofer to connect to a host UDS.\n+func InstallUDS() error {\n+ // Use the base syscall\n+ s := allowedSyscalls\n+\n+ // Add additional filters required for connecting to the host's sockets.\n+ s.Merge(udsSyscalls)\n+\n+ return seccomp.Install(s)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -85,6 +85,9 @@ type Config struct {\n// PanicOnWrite panics on attempts to write to RO mounts.\nPanicOnWrite bool\n+\n+ // HostUDS prevents\n+ HostUDSAllowed bool\n}\ntype attachPoint struct {\n@@ -128,12 +131,21 @@ func (a *attachPoint) Attach() (p9.File, error) {\nreturn nil, fmt.Errorf(\"stat file %q, err: %v\", a.prefix, err)\n}\n+ // Acquire the attach point lock\n+ a.attachedMu.Lock()\n+ defer a.attachedMu.Unlock()\n+\n// Hold the file descriptor we are converting into a p9.File\nvar f *fd.FD\n// Apply the S_IFMT bitmask so we can detect file type appropriately\nswitch fmtStat := stat.Mode & syscall.S_IFMT; {\ncase fmtStat == syscall.S_IFSOCK:\n+ // Check to see if the CLI option has been set to allow the UDS mount\n+ if !a.conf.HostUDSAllowed {\n+ return nil, fmt.Errorf(\"host UDS support is disabled\")\n+ }\n+\n// Attempt to open a connection. Bubble up the failures.\nf, err = fd.OpenUnix(a.prefix)\nif err != nil {\n@@ -144,7 +156,7 @@ func (a *attachPoint) Attach() (p9.File, error) {\n// Default to Read/Write permissions.\nmode := syscall.O_RDWR\n- // If the configuration is Read Only & the mount point is a directory,\n+ // If the configuration is Read Only or the mount point is a directory,\n// set the mode to Read Only.\nif a.conf.ROMount || fmtStat == syscall.S_IFDIR {\nmode = syscall.O_RDONLY\n@@ -157,9 +169,7 @@ func (a *attachPoint) Attach() (p9.File, error) {\n}\n}\n- // Close the connection if the UDS is already attached.\n- a.attachedMu.Lock()\n- defer a.attachedMu.Unlock()\n+ // Close the connection if already attached.\nif a.attached {\nf.Close()\nreturn nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -67,6 +67,7 @@ var (\nnetwork = flag.String(\"network\", \"sandbox\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\ngso = flag.Bool(\"gso\", true, \"enable generic segmenation offload\")\nfileAccess = flag.String(\"file-access\", \"exclusive\", \"specifies which filesystem to use for the root mount: exclusive (default), shared. Volume mounts are always shared.\")\n+ fsGoferHostUDSAllowed = flag.Bool(\"fsgofer-host-uds-allowed\", false, \"Allow the gofer to mount Unix Domain Sockets.\")\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nwatchdogAction = flag.String(\"watchdog-action\", \"log\", \"sets what action the watchdog takes when triggered: log (default), panic.\")\npanicSignal = flag.Int(\"panic-signal\", -1, \"register signal handling that panics. Usually set to SIGUSR2(12) to troubleshoot hangs. -1 disables it.\")\n@@ -178,6 +179,7 @@ func main() {\nDebugLog: *debugLog,\nDebugLogFormat: *debugLogFormat,\nFileAccess: fsAccess,\n+ FSGoferHostUDSAllowed: *fsGoferHostUDSAllowed,\nOverlay: *overlay,\nNetwork: netType,\nGSO: *gso,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Place the host UDS mounting behind --fsgofer-host-uds-allowed.
This commit allows the use of the `--fsgofer-host-uds-allowed` flag to
enable mounting sockets and add the appropriate seccomp filters. |
259,858 | 19.09.2019 13:38:14 | 25,200 | 75781ab3efa7b377c6dc4cf26840323f504d5eb5 | Remove defer from hot path and ensure Atomic is applied consistently. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/epsocket.go",
"new_path": "pkg/sentry/socket/epsocket/epsocket.go",
"diff": "@@ -415,13 +415,13 @@ func (s *SocketOperations) Read(ctx context.Context, _ *fs.File, dst usermem.IOS\n// WriteTo implements fs.FileOperations.WriteTo.\nfunc (s *SocketOperations) WriteTo(ctx context.Context, _ *fs.File, dst io.Writer, count int64, dup bool) (int64, error) {\ns.readMu.Lock()\n- defer s.readMu.Unlock()\n// Copy as much data as possible.\ndone := int64(0)\nfor count > 0 {\n// This may return a blocking error.\nif err := s.fetchReadView(); err != nil {\n+ s.readMu.Unlock()\nreturn done, err.ToError()\n}\n@@ -434,16 +434,18 @@ func (s *SocketOperations) WriteTo(ctx context.Context, _ *fs.File, dst io.Write\n// supported by any Linux system calls, but the\n// expectation is that now a caller will call read to\n// actually remove these bytes from the socket.\n- return done, nil\n+ break\n}\n// Drop that part of the view.\ns.readView.TrimFront(n)\nif err != nil {\n+ s.readMu.Unlock()\nreturn done, err\n}\n}\n+ s.readMu.Unlock()\nreturn done, nil\n}\n@@ -549,7 +551,11 @@ func (r *readerPayload) Payload(size int) ([]byte, *tcpip.Error) {\n// ReadFrom implements fs.FileOperations.ReadFrom.\nfunc (s *SocketOperations) ReadFrom(ctx context.Context, _ *fs.File, r io.Reader, count int64) (int64, error) {\nf := &readerPayload{ctx: ctx, r: r, count: count}\n- n, resCh, err := s.Endpoint.Write(f, tcpip.WriteOptions{})\n+ n, resCh, err := s.Endpoint.Write(f, tcpip.WriteOptions{\n+ // Reads may be destructive but should be very fast,\n+ // so we can't release the lock while copying data.\n+ Atomic: true,\n+ })\nif err == tcpip.ErrWouldBlock {\nreturn 0, syserror.ErrWouldBlock\n}\n@@ -561,9 +567,7 @@ func (s *SocketOperations) ReadFrom(ctx context.Context, _ *fs.File, r io.Reader\n}\nn, _, err = s.Endpoint.Write(f, tcpip.WriteOptions{\n- // Reads may be destructive but should be very fast,\n- // so we can't release the lock while copying data.\n- Atomic: true,\n+ Atomic: true, // See above.\n})\n}\nif err == tcpip.ErrWouldBlock {\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove defer from hot path and ensure Atomic is applied consistently.
PiperOrigin-RevId: 270114317 |
259,993 | 19.09.2019 17:10:50 | 14,400 | 46beb919121f02d8bd110a54fb8f6de5dfd2891e | Fix documentation, clean up seccomp filter installation, rename helpers.
Filter installation has been streamlined and functions renamed.
Documentation has been fixed to be standards compliant, and missing
documentation added. gofmt has also been applied to modified files. | [
{
"change_type": "MODIFY",
"old_path": "pkg/fd/fd.go",
"new_path": "pkg/fd/fd.go",
"diff": "@@ -17,12 +17,12 @@ package fd\nimport (\n\"fmt\"\n+ \"gvisor.dev/gvisor/pkg/unet\"\n\"io\"\n\"os\"\n\"runtime\"\n\"sync/atomic\"\n\"syscall\"\n- \"gvisor.dev/gvisor/pkg/unet\"\n)\n// ReadWriter implements io.ReadWriter, io.ReaderAt, and io.WriterAt for fd. It\n@@ -186,8 +186,8 @@ func OpenAt(dir *FD, path string, flags int, mode uint32) (*FD, error) {\nreturn New(f), nil\n}\n-// OpenUnix Open a Unix Domain Socket and return the file descriptor for it.\n-func OpenUnix(path string) (*FD, error) {\n+// DialUnix connects to a Unix Domain Socket and return the file descriptor.\n+func DialUnix(path string) (*FD, error) {\nsocket, err := unet.Connect(path, false)\nreturn New(socket.FD()), err\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -138,7 +138,7 @@ type Config struct {\n// Overlay is whether to wrap the root filesystem in an overlay.\nOverlay bool\n- // fsGoferHostUDSAllowed enables the gofer to mount a host UDS\n+ // FSGoferHostUDSAllowed enables the gofer to mount a host UDS.\nFSGoferHostUDSAllowed bool\n// Network indicates what type of network to use.\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -204,14 +204,12 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nif g.hostUDSAllowed {\n- if err := filter.InstallUDS(); err != nil {\n- Fatalf(\"installing UDS seccomp filters: %v\", err)\n+ filter.InstallUDSFilters()\n}\n- } else {\n+\nif err := filter.Install(); err != nil {\nFatalf(\"installing seccomp filters: %v\", err)\n}\n- }\nrunServers(ats, g.ioFDs)\nreturn subcommands.ExitSuccess\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/filter.go",
"new_path": "runsc/fsgofer/filter/filter.go",
"diff": "@@ -23,23 +23,16 @@ import (\n// Install installs seccomp filters.\nfunc Install() error {\n- s := allowedSyscalls\n-\n// Set of additional filters used by -race and -msan. Returns empty\n// when not enabled.\n- s.Merge(instrumentationFilters())\n+ allowedSyscalls.Merge(instrumentationFilters())\n- return seccomp.Install(s)\n+ return seccomp.Install(allowedSyscalls)\n}\n-// InstallUDS installs the standard Gofer seccomp filters along with filters\n-// allowing the gofer to connect to a host UDS.\n-func InstallUDS() error {\n- // Use the base syscall\n- s := allowedSyscalls\n-\n+// InstallUDSFilters installs the seccomp filters required to let the gofer connect\n+// to a host UDS.\n+func InstallUDSFilters() {\n// Add additional filters required for connecting to the host's sockets.\n- s.Merge(udsSyscalls)\n-\n- return seccomp.Install(s)\n+ allowedSyscalls.Merge(udsSyscalls)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "package fsgofer\nimport (\n+ \"errors\"\n\"fmt\"\n\"io\"\n\"math\"\n@@ -86,7 +87,7 @@ type Config struct {\n// PanicOnWrite panics on attempts to write to RO mounts.\nPanicOnWrite bool\n- // HostUDS prevents\n+ // HostUDSAllowed signals whether the gofer can mount a host's UDS.\nHostUDSAllowed bool\n}\n@@ -131,23 +132,23 @@ func (a *attachPoint) Attach() (p9.File, error) {\nreturn nil, fmt.Errorf(\"stat file %q, err: %v\", a.prefix, err)\n}\n- // Acquire the attach point lock\n+ // Acquire the attach point lock.\na.attachedMu.Lock()\ndefer a.attachedMu.Unlock()\n- // Hold the file descriptor we are converting into a p9.File\n+ // Hold the file descriptor we are converting into a p9.File.\nvar f *fd.FD\n- // Apply the S_IFMT bitmask so we can detect file type appropriately\n- switch fmtStat := stat.Mode & syscall.S_IFMT; {\n- case fmtStat == syscall.S_IFSOCK:\n- // Check to see if the CLI option has been set to allow the UDS mount\n+ // Apply the S_IFMT bitmask so we can detect file type appropriately.\n+ switch fmtStat := stat.Mode & syscall.S_IFMT; fmtStat {\n+ case syscall.S_IFSOCK:\n+ // Check to see if the CLI option has been set to allow the UDS mount.\nif !a.conf.HostUDSAllowed {\n- return nil, fmt.Errorf(\"host UDS support is disabled\")\n+ return nil, errors.New(\"host UDS support is disabled\")\n}\n// Attempt to open a connection. Bubble up the failures.\n- f, err = fd.OpenUnix(a.prefix)\n+ f, err = fd.DialUnix(a.prefix)\nif err != nil {\nreturn nil, err\n}\n@@ -1058,7 +1059,7 @@ func (l *localFile) Flush() error {\n// Connect implements p9.File.\nfunc (l *localFile) Connect(p9.ConnectFlags) (*fd.FD, error) {\n- return fd.OpenUnix(l.hostPath)\n+ return fd.DialUnix(l.hostPath)\n}\n// Close implements p9.File.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix documentation, clean up seccomp filter installation, rename helpers.
Filter installation has been streamlined and functions renamed.
Documentation has been fixed to be standards compliant, and missing
documentation added. gofmt has also been applied to modified files. |
259,993 | 19.09.2019 17:44:46 | 14,400 | e975184bc50944e82a6bf5f4c57bbe970933fdc5 | Update InstallUDSFilters documentation to be accurate to functionality. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/filter.go",
"new_path": "runsc/fsgofer/filter/filter.go",
"diff": "@@ -30,8 +30,8 @@ func Install() error {\nreturn seccomp.Install(allowedSyscalls)\n}\n-// InstallUDSFilters installs the seccomp filters required to let the gofer connect\n-// to a host UDS.\n+// InstallUDSFilters extends the allowed syscalls to include those necessary for\n+// connecting to a host UDS.\nfunc InstallUDSFilters() {\n// Add additional filters required for connecting to the host's sockets.\nallowedSyscalls.Merge(udsSyscalls)\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update InstallUDSFilters documentation to be accurate to functionality. |
259,883 | 05.09.2019 15:03:41 | -28,800 | 329b6653ffbb29b47409a923a7fbb3bd3aff074f | Implement /proc/net/tcp6
Fixes: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/proc/net.go",
"new_path": "pkg/sentry/fs/proc/net.go",
"diff": "@@ -66,7 +66,7 @@ func (p *proc) newNetDir(ctx context.Context, k *kernel.Kernel, msrc *fs.MountSo\nif s.SupportsIPv6() {\ncontents[\"if_inet6\"] = seqfile.NewSeqFileInode(ctx, &ifinet6{s: s}, msrc)\ncontents[\"ipv6_route\"] = newStaticProcInode(ctx, msrc, []byte(\"\"))\n- contents[\"tcp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"))\n+ contents[\"tcp6\"] = seqfile.NewSeqFileInode(ctx, &netTCP6{k: k}, msrc)\ncontents[\"udp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"))\n}\n}\n@@ -310,7 +310,14 @@ func networkToHost16(n uint16) uint16 {\nreturn usermem.ByteOrder.Uint16(buf[:])\n}\n-func writeInetAddr(w io.Writer, a linux.SockAddrInet) {\n+func writeInetAddr(w io.Writer, family int, i linux.SockAddr) {\n+ switch family {\n+ case linux.AF_INET:\n+ var a linux.SockAddrInet\n+ if i != nil {\n+ a = *i.(*linux.SockAddrInet)\n+ }\n+\n// linux.SockAddrInet.Port is stored in the network byte order and is\n// printed like a number in host byte order. Note that all numbers in host\n// byte order are printed with the most-significant byte first when\n@@ -332,22 +339,22 @@ func writeInetAddr(w io.Writer, a linux.SockAddrInet) {\naddr := usermem.ByteOrder.Uint32(a.Addr[:])\nfmt.Fprintf(w, \"%08X:%04X \", addr, port)\n+ case linux.AF_INET6:\n+ var a linux.SockAddrInet6\n+ if i != nil {\n+ a = *i.(*linux.SockAddrInet6)\n}\n-// netTCP implements seqfile.SeqSource for /proc/net/tcp.\n-//\n-// +stateify savable\n-type netTCP struct {\n- k *kernel.Kernel\n+ port := networkToHost16(a.Port)\n+ addr0 := usermem.ByteOrder.Uint32(a.Addr[0:4])\n+ addr1 := usermem.ByteOrder.Uint32(a.Addr[4:8])\n+ addr2 := usermem.ByteOrder.Uint32(a.Addr[8:12])\n+ addr3 := usermem.ByteOrder.Uint32(a.Addr[12:16])\n+ fmt.Fprintf(w, \"%08X%08X%08X%08X:%04X \", addr0, addr1, addr2, addr3, port)\n}\n-\n-// NeedsUpdate implements seqfile.SeqSource.NeedsUpdate.\n-func (*netTCP) NeedsUpdate(generation int64) bool {\n- return true\n}\n-// ReadSeqFileData implements seqfile.SeqSource.ReadSeqFileData.\n-func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+func commonReadSeqFileDataTCP(n seqfile.SeqHandle, k *kernel.Kernel, ctx context.Context, h seqfile.SeqHandle, fa int, header []byte) ([]seqfile.SeqData, int64) {\n// t may be nil here if our caller is not part of a task goroutine. This can\n// happen for example if we're here for \"sentryctl cat\". When t is nil,\n// degrade gracefully and retrieve what we can.\n@@ -358,7 +365,7 @@ func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\n}\nvar buf bytes.Buffer\n- for _, se := range n.k.ListSockets() {\n+ for _, se := range k.ListSockets() {\ns := se.Sock.Get()\nif s == nil {\nlog.Debugf(\"Couldn't resolve weakref with ID %v in socket table, racing with destruction?\", se.ID)\n@@ -369,7 +376,7 @@ func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nif !ok {\npanic(fmt.Sprintf(\"Found non-socket file in socket table: %+v\", sfile))\n}\n- if family, stype, _ := sops.Type(); !(family == linux.AF_INET && stype == linux.SOCK_STREAM) {\n+ if family, stype, _ := sops.Type(); !(family == fa && stype == linux.SOCK_STREAM) {\ns.DecRef()\n// Not tcp4 sockets.\ncontinue\n@@ -384,22 +391,22 @@ func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nfmt.Fprintf(&buf, \"%4d: \", se.ID)\n// Field: local_adddress.\n- var localAddr linux.SockAddrInet\n+ var localAddr linux.SockAddr\nif t != nil {\nif local, _, err := sops.GetSockName(t); err == nil {\n- localAddr = *local.(*linux.SockAddrInet)\n+ localAddr = local\n}\n}\n- writeInetAddr(&buf, localAddr)\n+ writeInetAddr(&buf, fa, localAddr)\n// Field: rem_address.\n- var remoteAddr linux.SockAddrInet\n+ var remoteAddr linux.SockAddr\nif t != nil {\nif remote, _, err := sops.GetPeerName(t); err == nil {\n- remoteAddr = *remote.(*linux.SockAddrInet)\n+ remoteAddr = remote\n}\n}\n- writeInetAddr(&buf, remoteAddr)\n+ writeInetAddr(&buf, fa, remoteAddr)\n// Field: state; socket state.\nfmt.Fprintf(&buf, \"%02X \", sops.State())\n@@ -465,7 +472,7 @@ func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\ndata := []seqfile.SeqData{\n{\n- Buf: []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode \\n\"),\n+ Buf: header,\nHandle: n,\n},\n{\n@@ -476,6 +483,42 @@ func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nreturn data, 0\n}\n+// netTCP implements seqfile.SeqSource for /proc/net/tcp.\n+//\n+// +stateify savable\n+type netTCP struct {\n+ k *kernel.Kernel\n+}\n+\n+// NeedsUpdate implements seqfile.SeqSource.NeedsUpdate.\n+func (*netTCP) NeedsUpdate(generation int64) bool {\n+ return true\n+}\n+\n+// ReadSeqFileData implements seqfile.SeqSource.ReadSeqFileData.\n+func (n *netTCP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+ header := []byte(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode \\n\")\n+ return commonReadSeqFileDataTCP(n, n.k, ctx, h, linux.AF_INET, header)\n+}\n+\n+// netTCP6 implements seqfile.SeqSource for /proc/net/tcp6.\n+//\n+// +stateify savable\n+type netTCP6 struct {\n+ k *kernel.Kernel\n+}\n+\n+// NeedsUpdate implements seqfile.SeqSource.NeedsUpdate.\n+func (*netTCP6) NeedsUpdate(generation int64) bool {\n+ return true\n+}\n+\n+// ReadSeqFileData implements seqfile.SeqSource.ReadSeqFileData.\n+func (n *netTCP6) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]seqfile.SeqData, int64) {\n+ header := []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\\n\")\n+ return commonReadSeqFileDataTCP(n, n.k, ctx, h, linux.AF_INET6, header)\n+}\n+\n// netUDP implements seqfile.SeqSource for /proc/net/udp.\n//\n// +stateify savable\n@@ -529,7 +572,7 @@ func (n *netUDP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nlocalAddr = *local.(*linux.SockAddrInet)\n}\n}\n- writeInetAddr(&buf, localAddr)\n+ writeInetAddr(&buf, linux.AF_INET, &localAddr)\n// Field: rem_address.\nvar remoteAddr linux.SockAddrInet\n@@ -538,7 +581,7 @@ func (n *netUDP) ReadSeqFileData(ctx context.Context, h seqfile.SeqHandle) ([]se\nremoteAddr = *remote.(*linux.SockAddrInet)\n}\n}\n- writeInetAddr(&buf, remoteAddr)\n+ writeInetAddr(&buf, linux.AF_INET, &remoteAddr)\n// Field: state; socket state.\nfmt.Fprintf(&buf, \"%02X \", sops.State())\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.cc",
"new_path": "test/syscalls/linux/ip_socket_test_util.cc",
"diff": "@@ -60,6 +60,14 @@ SocketPairKind IPv6TCPAcceptBindSocketPair(int type) {\n/* dual_stack = */ false)};\n}\n+SocketKind IPv6TCPUnboundSocket(int type) {\n+ std::string description =\n+ absl::StrCat(DescribeSocketType(type), \"IPv6 TCP socket\");\n+ return SocketKind{\n+ description, AF_INET6, type | SOCK_STREAM, IPPROTO_TCP,\n+ UnboundSocketCreator(AF_INET6, type | SOCK_STREAM, IPPROTO_TCP)};\n+}\n+\nSocketPairKind IPv4TCPAcceptBindSocketPair(int type) {\nstd::string description =\nabsl::StrCat(DescribeSocketType(type), \"connected IPv4 TCP socket\");\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/ip_socket_test_util.h",
"new_path": "test/syscalls/linux/ip_socket_test_util.h",
"diff": "@@ -96,6 +96,10 @@ SocketKind IPv4UDPUnboundSocket(int type);\n// a SimpleSocket created with AF_INET, SOCK_STREAM and the given type.\nSocketKind IPv4TCPUnboundSocket(int type);\n+// IPv6TCPUnboundSocketPair returns a SocketKind that represents\n+// a SimpleSocket created with AF_INET6, SOCK_STREAM and the given type.\n+SocketKind IPv6TCPUnboundSocket(int type);\n+\n// IfAddrHelper is a helper class that determines the local interfaces present\n// and provides functions to obtain their names, index numbers, and IP address.\nclass IfAddrHelper {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/proc_net_tcp.cc",
"new_path": "test/syscalls/linux/proc_net_tcp.cc",
"diff": "@@ -250,6 +250,248 @@ TEST(ProcNetTCP, State) {\nEXPECT_EQ(accepted_entry.state, TCP_ESTABLISHED);\n}\n+constexpr char kProcNetTCP6Header[] =\n+ \" sl local_address remote_address\"\n+ \" st tx_queue rx_queue tr tm->when retrnsmt\"\n+ \" uid timeout inode\";\n+\n+// TCP6Entry represents a single entry from /proc/net/tcp6.\n+struct TCP6Entry {\n+ struct in6_addr local_addr;\n+ uint16_t local_port;\n+\n+ struct in6_addr remote_addr;\n+ uint16_t remote_port;\n+\n+ uint64_t state;\n+ uint64_t uid;\n+ uint64_t inode;\n+};\n+\n+bool IPv6AddrEqual(const struct in6_addr* a1, const struct in6_addr* a2) {\n+ if (memcmp(a1, a2, sizeof(struct in6_addr)) == 0)\n+ return true;\n+ return false;\n+}\n+\n+// Finds the first entry in 'entries' for which 'predicate' returns true.\n+// Returns true on match, and sets 'match' to a copy of the matching entry. If\n+// 'match' is null, it's ignored.\n+bool FindBy6(const std::vector<TCP6Entry>& entries, TCP6Entry* match,\n+ std::function<bool(const TCP6Entry&)> predicate) {\n+ for (const TCP6Entry& entry : entries) {\n+ if (predicate(entry)) {\n+ if (match != nullptr) {\n+ *match = entry;\n+ }\n+ return true;\n+ }\n+ }\n+ return false;\n+}\n+\n+const struct in6_addr* IP6FromInetSockaddr(const struct sockaddr* addr) {\n+ auto* addr6 = reinterpret_cast<const struct sockaddr_in6*>(addr);\n+ return &addr6->sin6_addr;\n+}\n+\n+bool FindByLocalAddr6(const std::vector<TCP6Entry>& entries, TCP6Entry* match,\n+ const struct sockaddr* addr) {\n+ const struct in6_addr* local = IP6FromInetSockaddr(addr);\n+ uint16_t port = PortFromInetSockaddr(addr);\n+ return FindBy6(entries, match, [local, port](const TCP6Entry& e) {\n+ return (IPv6AddrEqual(&e.local_addr, local) && e.local_port == port);\n+ });\n+}\n+\n+bool FindByRemoteAddr6(const std::vector<TCP6Entry>& entries, TCP6Entry* match,\n+ const struct sockaddr* addr) {\n+ const struct in6_addr* remote = IP6FromInetSockaddr(addr);\n+ uint16_t port = PortFromInetSockaddr(addr);\n+ return FindBy6(entries, match, [remote, port](const TCP6Entry& e) {\n+ return (IPv6AddrEqual(&e.remote_addr, remote) && e.remote_port == port);\n+ });\n+}\n+\n+void ReadIPv6Address(std::string s, struct in6_addr* addr) {\n+ uint32_t a0, a1, a2, a3;\n+ const char *fmt = \"%08X%08X%08X%08X\";\n+ EXPECT_EQ(sscanf(s.c_str(), fmt, &a0, &a1, &a2, &a3), 4);\n+\n+ uint8_t *b = addr->s6_addr;\n+ *((uint32_t *)&b[0]) = a0;\n+ *((uint32_t *)&b[4]) = a1;\n+ *((uint32_t *)&b[8]) = a2;\n+ *((uint32_t *)&b[12]) = a3;\n+}\n+\n+// Returns a parsed representation of /proc/net/tcp6 entries.\n+PosixErrorOr<std::vector<TCP6Entry>> ProcNetTCP6Entries() {\n+ std::string content;\n+ RETURN_IF_ERRNO(GetContents(\"/proc/net/tcp6\", &content));\n+\n+ bool found_header = false;\n+ std::vector<TCP6Entry> entries;\n+ std::vector<std::string> lines = StrSplit(content, '\\n');\n+ std::cerr << \"<contents of /proc/net/tcp6>\" << std::endl;\n+ for (const std::string& line : lines) {\n+ std::cerr << line << std::endl;\n+\n+ if (!found_header) {\n+ EXPECT_EQ(line, kProcNetTCP6Header);\n+ found_header = true;\n+ continue;\n+ }\n+ if (line.empty()) {\n+ continue;\n+ }\n+\n+ // Parse a single entry from /proc/net/tcp6.\n+ //\n+ // Example entries:\n+ //\n+ // clang-format off\n+ //\n+ // sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n+ // 0: 00000000000000000000000000000000:1F90 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 876340 1 ffff8803da9c9380 100 0 0 10 0\n+ // 1: 00000000000000000000000000000000:C350 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 876987 1 ffff8803ec408000 100 0 0 10 0\n+ // ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n+ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n+ //\n+ // clang-format on\n+\n+ TCP6Entry entry;\n+ std::vector<std::string> fields =\n+ StrSplit(line, absl::ByAnyChar(\": \"), absl::SkipEmpty());\n+\n+ ReadIPv6Address(fields[1], &entry.local_addr);\n+ ASSIGN_OR_RETURN_ERRNO(entry.local_port, AtoiBase(fields[2], 16));\n+ ReadIPv6Address(fields[3], &entry.remote_addr);\n+ ASSIGN_OR_RETURN_ERRNO(entry.remote_port, AtoiBase(fields[4], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.state, AtoiBase(fields[5], 16));\n+ ASSIGN_OR_RETURN_ERRNO(entry.uid, Atoi<uint64_t>(fields[11]));\n+ ASSIGN_OR_RETURN_ERRNO(entry.inode, Atoi<uint64_t>(fields[13]));\n+\n+ entries.push_back(entry);\n+ }\n+ std::cerr << \"<end of /proc/net/tcp6>\" << std::endl;\n+\n+ return entries;\n+}\n+\n+TEST(ProcNetTCP6, Exists) {\n+ const std::string content =\n+ ASSERT_NO_ERRNO_AND_VALUE(GetContents(\"/proc/net/tcp6\"));\n+ const std::string header_line = StrCat(kProcNetTCP6Header, \"\\n\");\n+ if (IsRunningOnGvisor()) {\n+ // Should be just the header since we don't have any tcp sockets yet.\n+ EXPECT_EQ(content, header_line);\n+ } else {\n+ // On a general linux machine, we could have abitrary sockets on the system,\n+ // so just check the header.\n+ EXPECT_THAT(content, ::testing::StartsWith(header_line));\n+ }\n+}\n+\n+TEST(ProcNetTCP6, EntryUID) {\n+ auto sockets =\n+ ASSERT_NO_ERRNO_AND_VALUE(IPv6TCPAcceptBindSocketPair(0).Create());\n+ std::vector<TCP6Entry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+ TCP6Entry e;\n+\n+ ASSERT_TRUE(FindByLocalAddr6(entries, &e, sockets->first_addr()));\n+ EXPECT_EQ(e.uid, geteuid());\n+ ASSERT_TRUE(FindByRemoteAddr6(entries, &e, sockets->first_addr()));\n+ EXPECT_EQ(e.uid, geteuid());\n+}\n+\n+TEST(ProcNetTCP6, BindAcceptConnect) {\n+ auto sockets =\n+ ASSERT_NO_ERRNO_AND_VALUE(IPv6TCPAcceptBindSocketPair(0).Create());\n+ std::vector<TCP6Entry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+ // We can only make assertions about the total number of entries if we control\n+ // the entire \"machine\".\n+ if (IsRunningOnGvisor()) {\n+ EXPECT_EQ(entries.size(), 2);\n+ }\n+\n+ EXPECT_TRUE(FindByLocalAddr6(entries, nullptr, sockets->first_addr()));\n+ EXPECT_TRUE(FindByRemoteAddr6(entries, nullptr, sockets->first_addr()));\n+}\n+\n+TEST(ProcNetTCP6, InodeReasonable) {\n+ auto sockets =\n+ ASSERT_NO_ERRNO_AND_VALUE(IPv6TCPAcceptBindSocketPair(0).Create());\n+ std::vector<TCP6Entry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+\n+ TCP6Entry accepted_entry;\n+\n+ ASSERT_TRUE(FindByLocalAddr6(entries, &accepted_entry, sockets->first_addr()));\n+ EXPECT_NE(accepted_entry.inode, 0);\n+\n+ TCP6Entry client_entry;\n+ ASSERT_TRUE(FindByRemoteAddr6(entries, &client_entry, sockets->first_addr()));\n+ EXPECT_NE(client_entry.inode, 0);\n+ EXPECT_NE(accepted_entry.inode, client_entry.inode);\n+}\n+\n+TEST(ProcNetTCP6, State) {\n+ std::unique_ptr<FileDescriptor> server =\n+ ASSERT_NO_ERRNO_AND_VALUE(IPv6TCPUnboundSocket(0).Create());\n+\n+ auto test_addr = V6Loopback();\n+ ASSERT_THAT(\n+ bind(server->get(), reinterpret_cast<struct sockaddr*>(&test_addr.addr),\n+ test_addr.addr_len),\n+ SyscallSucceeds());\n+\n+ struct sockaddr_in6 addr6;\n+ socklen_t addrlen = sizeof(struct sockaddr_in6);\n+ auto* addr = reinterpret_cast<struct sockaddr*>(&addr6);\n+ ASSERT_THAT(getsockname(server->get(), addr, &addrlen), SyscallSucceeds());\n+ ASSERT_EQ(addrlen, sizeof(struct sockaddr_in6));\n+\n+ ASSERT_THAT(listen(server->get(), 10), SyscallSucceeds());\n+ std::vector<TCP6Entry> entries =\n+ ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+ TCP6Entry listen_entry;\n+\n+ ASSERT_TRUE(FindByLocalAddr6(entries, &listen_entry, addr));\n+ EXPECT_EQ(listen_entry.state, TCP_LISTEN);\n+\n+ std::unique_ptr<FileDescriptor> client =\n+ ASSERT_NO_ERRNO_AND_VALUE(IPv6TCPUnboundSocket(0).Create());\n+ ASSERT_THAT(RetryEINTR(connect)(client->get(), addr, addrlen),\n+ SyscallSucceeds());\n+ entries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+ ASSERT_TRUE(FindByLocalAddr6(entries, &listen_entry, addr));\n+ EXPECT_EQ(listen_entry.state, TCP_LISTEN);\n+ TCP6Entry client_entry;\n+ ASSERT_TRUE(FindByRemoteAddr6(entries, &client_entry, addr));\n+ EXPECT_EQ(client_entry.state, TCP_ESTABLISHED);\n+\n+ FileDescriptor accepted =\n+ ASSERT_NO_ERRNO_AND_VALUE(Accept(server->get(), nullptr, nullptr));\n+\n+ const struct in6_addr* local = IP6FromInetSockaddr(addr);\n+ const uint16_t accepted_local_port = PortFromInetSockaddr(addr);\n+\n+ entries = ASSERT_NO_ERRNO_AND_VALUE(ProcNetTCP6Entries());\n+ TCP6Entry accepted_entry;\n+ ASSERT_TRUE(FindBy6(entries, &accepted_entry,\n+ [client_entry, local,\n+ accepted_local_port](const TCP6Entry& e) {\n+ return IPv6AddrEqual(&e.local_addr, local) &&\n+ e.local_port == accepted_local_port &&\n+ IPv6AddrEqual(&e.remote_addr, &client_entry.local_addr) &&\n+ e.remote_port == client_entry.local_port;\n+ }));\n+ EXPECT_EQ(accepted_entry.state, TCP_ESTABLISHED);\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Implement /proc/net/tcp6
Fixes: #829
Signed-off-by: Jianfeng Tan <[email protected]>
Signed-off-by: Jielong Zhou <[email protected]> |
259,854 | 20.09.2019 14:08:46 | 25,200 | 002f1d4aaefa9abdd50e3e8906ae828c31d038e6 | Allow waiting for LinkEndpoint worker goroutines to finish.
Previously, the only safe way to use an fdbased endpoint was to leak the FD.
This change makes it possible to safely close the FD.
This is the first step towards having stoppable stacks.
Updates | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/channel/channel.go",
"new_path": "pkg/tcpip/link/channel/channel.go",
"diff": "@@ -133,3 +133,6 @@ func (e *Endpoint) WritePacket(_ *stack.Route, gso *stack.GSO, hdr buffer.Prepen\nreturn nil\n}\n+\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (*Endpoint) Wait() {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -41,6 +41,7 @@ package fdbased\nimport (\n\"fmt\"\n+ \"sync\"\n\"syscall\"\n\"golang.org/x/sys/unix\"\n@@ -81,6 +82,7 @@ const (\nPacketMMap\n)\n+// An endpoint implements the link-layer using a message-oriented file descriptor.\ntype endpoint struct {\n// fds is the set of file descriptors each identifying one inbound/outbound\n// channel. The endpoint will dispatch from all inbound channels as well as\n@@ -114,6 +116,9 @@ type endpoint struct {\n// gsoMaxSize is the maximum GSO packet size. It is zero if GSO is\n// disabled.\ngsoMaxSize uint32\n+\n+ // wg keeps track of running goroutines.\n+ wg sync.WaitGroup\n}\n// Options specify the details about the fd-based endpoint to be created.\n@@ -164,7 +169,8 @@ type Options struct {\n// New creates a new fd-based endpoint.\n//\n// Makes fd non-blocking, but does not take ownership of fd, which must remain\n-// open for the lifetime of the returned endpoint.\n+// open for the lifetime of the returned endpoint (until after the endpoint has\n+// stopped being using and Wait returns).\nfunc New(opts *Options) (stack.LinkEndpoint, error) {\ncaps := stack.LinkEndpointCapabilities(0)\nif opts.RXChecksumOffload {\n@@ -290,7 +296,11 @@ func (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) {\n// saved, they stop sending outgoing packets and all incoming packets\n// are rejected.\nfor i := range e.inboundDispatchers {\n- go e.dispatchLoop(e.inboundDispatchers[i]) // S/R-SAFE: See above.\n+ e.wg.Add(1)\n+ go func(i int) { // S/R-SAFE: See above.\n+ e.dispatchLoop(e.inboundDispatchers[i])\n+ e.wg.Done()\n+ }(i)\n}\n}\n@@ -320,6 +330,12 @@ func (e *endpoint) LinkAddress() tcpip.LinkAddress {\nreturn e.addr\n}\n+// Wait implements stack.LinkEndpoint.Wait. It waits for the endpoint to stop\n+// reading from its FD.\n+func (e *endpoint) Wait() {\n+ e.wg.Wait()\n+}\n+\n// virtioNetHdr is declared in linux/virtio_net.h.\ntype virtioNetHdr struct {\nflags uint8\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/loopback/loopback.go",
"new_path": "pkg/tcpip/link/loopback/loopback.go",
"diff": "@@ -85,3 +85,6 @@ func (e *endpoint) WritePacket(_ *stack.Route, _ *stack.GSO, hdr buffer.Prependa\nreturn nil\n}\n+\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (*endpoint) Wait() {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/muxed/injectable.go",
"new_path": "pkg/tcpip/link/muxed/injectable.go",
"diff": "@@ -104,6 +104,13 @@ func (m *InjectableEndpoint) WriteRawPacket(dest tcpip.Address, packet []byte) *\nreturn endpoint.WriteRawPacket(dest, packet)\n}\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (m *InjectableEndpoint) Wait() {\n+ for _, ep := range m.routes {\n+ ep.Wait()\n+ }\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/sharedmem/sharedmem.go",
"new_path": "pkg/tcpip/link/sharedmem/sharedmem.go",
"diff": "@@ -132,7 +132,8 @@ func (e *endpoint) Close() {\n}\n}\n-// Wait waits until all workers have stopped after a Close() call.\n+// Wait implements stack.LinkEndpoint.Wait. It waits until all workers have\n+// stopped after a Close() call.\nfunc (e *endpoint) Wait() {\ne.completed.Wait()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/sniffer/sniffer.go",
"new_path": "pkg/tcpip/link/sniffer/sniffer.go",
"diff": "@@ -240,6 +240,9 @@ func (e *endpoint) WritePacket(r *stack.Route, gso *stack.GSO, hdr buffer.Prepen\nreturn e.lower.WritePacket(r, gso, hdr, payload, protocol)\n}\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (*endpoint) Wait() {}\n+\nfunc logPacket(prefix string, protocol tcpip.NetworkProtocolNumber, b buffer.View, gso *stack.GSO) {\n// Figure out the network layer info.\nvar transProto uint8\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/waitable/waitable.go",
"new_path": "pkg/tcpip/link/waitable/waitable.go",
"diff": "@@ -120,3 +120,6 @@ func (e *Endpoint) WaitWrite() {\nfunc (e *Endpoint) WaitDispatch() {\ne.dispatchGate.Close()\n}\n+\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (e *Endpoint) Wait() {}\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/waitable/waitable_test.go",
"new_path": "pkg/tcpip/link/waitable/waitable_test.go",
"diff": "@@ -70,6 +70,9 @@ func (e *countedEndpoint) WritePacket(r *stack.Route, _ *stack.GSO, hdr buffer.P\nreturn nil\n}\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (*countedEndpoint) Wait() {}\n+\nfunc TestWaitWrite(t *testing.T) {\nep := &countedEndpoint{}\nwep := New(ep)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/network/ip_test.go",
"new_path": "pkg/tcpip/network/ip_test.go",
"diff": "@@ -144,6 +144,9 @@ func (*testObject) LinkAddress() tcpip.LinkAddress {\nreturn \"\"\n}\n+// Wait implements stack.LinkEndpoint.Wait.\n+func (*testObject) Wait() {}\n+\n// WritePacket is called by network endpoints after producing a packet and\n// writing it to the link endpoint. This is used by the test object to verify\n// that the produced packet is as expected.\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/stack/registration.go",
"new_path": "pkg/tcpip/stack/registration.go",
"diff": "@@ -295,6 +295,15 @@ type LinkEndpoint interface {\n// IsAttached returns whether a NetworkDispatcher is attached to the\n// endpoint.\nIsAttached() bool\n+\n+ // Wait waits for any worker goroutines owned by the endpoint to stop.\n+ //\n+ // For now, requesting that an endpoint's worker goroutine(s) stop is\n+ // implementation specific.\n+ //\n+ // Wait will not block if the endpoint hasn't started any goroutines\n+ // yet, even if it might later.\n+ Wait()\n}\n// InjectableLinkEndpoint is a LinkEndpoint where inbound packets are\n"
}
] | Go | Apache License 2.0 | google/gvisor | Allow waiting for LinkEndpoint worker goroutines to finish.
Previously, the only safe way to use an fdbased endpoint was to leak the FD.
This change makes it possible to safely close the FD.
This is the first step towards having stoppable stacks.
Updates #837
PiperOrigin-RevId: 270346582 |
259,885 | 20.09.2019 14:23:20 | 25,200 | fb55c2bd0d5d80b240184f643967f214d3dbc259 | Change vfs.Dirent.Off to NextOff.
"d_off is the distance from the start of the directory to the start of the next
linux_dirent." - getdents(2). | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/directory.go",
"new_path": "pkg/sentry/fsimpl/ext/directory.go",
"diff": "@@ -193,7 +193,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nName: child.diskDirent.FileName(),\nType: fs.ToDirentType(childType),\nIno: uint64(child.diskDirent.Inode()),\n- Off: fd.off,\n+ NextOff: fd.off + 1,\n}) {\ndir.childList.InsertBefore(child, fd.iter)\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/ext/ext_test.go",
"new_path": "pkg/sentry/fsimpl/ext/ext_test.go",
"diff": "@@ -584,7 +584,7 @@ func TestIterDirents(t *testing.T) {\n// Ignore the inode number and offset of dirents because those are likely to\n// change as the underlying image changes.\ncmpIgnoreFields := cmp.FilterPath(func(p cmp.Path) bool {\n- return p.String() == \"Ino\" || p.String() == \"Off\"\n+ return p.String() == \"Ino\" || p.String() == \"NextOff\"\n}, cmp.Ignore())\nif diff := cmp.Diff(cb.dirents, test.want, cmpIgnoreFields); diff != \"\" {\nt.Errorf(\"dirents mismatch (-want +got):\\n%s\", diff)\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fsimpl/memfs/directory.go",
"new_path": "pkg/sentry/fsimpl/memfs/directory.go",
"diff": "@@ -78,7 +78,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nName: \".\",\nType: linux.DT_DIR,\nIno: vfsd.Impl().(*dentry).inode.ino,\n- Off: 0,\n+ NextOff: 1,\n}) {\nreturn nil\n}\n@@ -90,7 +90,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nName: \"..\",\nType: parentInode.direntType(),\nIno: parentInode.ino,\n- Off: 1,\n+ NextOff: 2,\n}) {\nreturn nil\n}\n@@ -115,7 +115,7 @@ func (fd *directoryFD) IterDirents(ctx context.Context, cb vfs.IterDirentsCallba\nName: child.vfsd.Name(),\nType: child.inode.direntType(),\nIno: child.inode.ino,\n- Off: fd.off,\n+ NextOff: fd.off + 1,\n}) {\ndir.childList.InsertBefore(child, fd.iter)\nreturn nil\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/vfs/file_description.go",
"new_path": "pkg/sentry/vfs/file_description.go",
"diff": "@@ -199,8 +199,11 @@ type Dirent struct {\n// Ino is the inode number.\nIno uint64\n- // Off is this Dirent's offset.\n- Off int64\n+ // NextOff is the offset of the *next* Dirent in the directory; that is,\n+ // FileDescription.Seek(NextOff, SEEK_SET) (as called by seekdir(3)) will\n+ // cause the next call to FileDescription.IterDirents() to yield the next\n+ // Dirent. (The offset of the first Dirent in a directory is always 0.)\n+ NextOff int64\n}\n// IterDirentsCallback receives Dirents from FileDescriptionImpl.IterDirents.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Change vfs.Dirent.Off to NextOff.
"d_off is the distance from the start of the directory to the start of the next
linux_dirent." - getdents(2).
PiperOrigin-RevId: 270349685 |
259,962 | 23.09.2019 15:59:23 | 25,200 | 9846da5e654fc5649269e4a45fa711d4519c343e | Fix bug in RstCausesPollHUP.
The test is checking the wrong poll_fd for POLLHUP. The only
reason it passed till now was because it was also checking
for POLLIN which was always true on the other fd from the
previous poll! | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"new_path": "test/syscalls/linux/socket_ip_tcp_generic.cc",
"diff": "@@ -117,7 +117,7 @@ TEST_P(TCPSocketPairTest, RSTCausesPollHUP) {\nstruct pollfd poll_fd3 = {sockets->first_fd(), POLLHUP, 0};\nASSERT_THAT(RetryEINTR(poll)(&poll_fd3, 1, kPollTimeoutMs),\nSyscallSucceedsWithValue(1));\n- ASSERT_NE(poll_fd.revents & (POLLHUP | POLLIN), 0);\n+ ASSERT_NE(poll_fd3.revents & POLLHUP, 0);\n}\n// This test validates that even if a RST is sent the other end will not\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix bug in RstCausesPollHUP.
The test is checking the wrong poll_fd for POLLHUP. The only
reason it passed till now was because it was also checking
for POLLIN which was always true on the other fd from the
previous poll!
PiperOrigin-RevId: 270780401 |
259,992 | 06.09.2019 16:41:23 | 25,200 | 0261626482865a7445e0b536feefd5ee3355a0da | Add GKE Sandbox to Kubernetes section | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/docs/tutorials/_index.md",
"diff": "++++\n+title = \"Tutorials\"\n+weight = 0\n++++\n"
},
{
"change_type": "ADD",
"old_path": "content/docs/tutorials/add-node-pool.png",
"new_path": "content/docs/tutorials/add-node-pool.png",
"diff": "Binary files /dev/null and b/content/docs/tutorials/add-node-pool.png differ\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/docs/tutorials/docker.md",
"diff": "++++\n+title = \"WordPress with Docker\"\n+weight = 10\n++++\n+\n+## Deploy a WordPress site with Docker\n+\n+This page shows you how to deploy a sample [WordPress][wordpress] site using\n+[Docker][docker].\n+\n+### Before you begin\n+\n+[Follow these instructions][docker-install] to install runsc with Docker.\n+This document assumes that the runtime name chosen is `runsc`.\n+\n+### Running WordPress\n+\n+Now, let's deploy a WordPress site using Docker. WordPress site requires\n+two containers: web server in the frontend, MySQL database in the backend.\n+\n+First, let's define a few environment variables that are shared between both\n+containers:\n+\n+```bash\n+export MYSQL_PASSWORD=${YOUR_SECRET_PASSWORD_HERE?}\n+export MYSQL_DB=wordpress\n+export MYSQL_USER=wordpress\n+```\n+\n+Next, let's start the database container running MySQL and wait until the\n+database is initialized:\n+\n+```bash\n+docker run --runtime=runsc --name mysql -d \\\n+ -e MYSQL_RANDOM_ROOT_PASSWORD=1 \\\n+ -e MYSQL_PASSWORD=\"${MYSQL_PASSWORD}\" \\\n+ -e MYSQL_DATABASE=\"${MYSQL_DB}\" \\\n+ -e MYSQL_USER=\"${MYSQL_USER}\" \\\n+ mysql:5.7\n+\n+# Wait until this message appears in the log.\n+docker logs mysql |& grep 'port: 3306 MySQL Community Server (GPL)'\n+```\n+\n+Once the database is running, you can start the WordPress frontend. We use the\n+`--link` option to connect the frontend to the database, and expose the\n+WordPress to port 8080 on the localhost.\n+\n+```bash\n+docker run --runtime=runsc --name wordpress -d \\\n+ --link mysql:mysql \\\n+ -p 8080:80 \\\n+ -e WORDPRESS_DB_HOST=mysql \\\n+ -e WORDPRESS_DB_USER=\"${MYSQL_USER}\" \\\n+ -e WORDPRESS_DB_PASSWORD=\"${MYSQL_PASSWORD}\" \\\n+ -e WORDPRESS_DB_NAME=\"${MYSQL_DB}\" \\\n+ -e WORDPRESS_TABLE_PREFIX=wp_ \\\n+ wordpress\n+```\n+\n+Now, you can access the WordPress website pointing your favorite browser to\n+http://localhost:8080.\n+\n+Congratulations! You have just deployed a WordPress site using Docker.\n+\n+### What's next\n+\n+[Learn how to deploy WordPress with Kubernetes][wordpress-k8s].\n+\n+[docker]: https://www.docker.com/\n+[docker-install]: /docs/user_guide/docker/\n+[wordpress]: https://wordpress.com/\n+[wordpress-k8s]: /docs/tutorials/kubernetes/\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "content/docs/tutorials/kubernetes.md",
"diff": "++++\n+title = \"WordPress with Kubernetes\"\n++++\n+\n+## Deploy a WordPress site using GKE Sandbox\n+\n+This page shows you how to deploy a sample [WordPress][wordpress] site using\n+[GKE Sandbox][gke-sandbox].\n+\n+### Before you begin\n+\n+Take the following steps to enable the Kubernetes Engine API:\n+\n+1. Visit the [Kubernetes Engine page][project-selector] in the Google Cloud\n+ Platform Console.\n+1. Create or select a project.\n+\n+### Creating a node pool with gVisor enabled\n+\n+Create a node pool inside your cluster with option `--sandbox type=gvisor` added\n+to the command, like below:\n+\n+```bash\n+gcloud beta container node-pools create sandbox-pool --cluster=${CLUSTER_NAME} --image-type=cos_containerd --sandbox type=gvisor\n+```\n+\n+If you prefer to use the console, select your cluster and select the **ADD NODE\n+POOL** button:\n+\n+\n+\n+Then select the **Image type** with **Containerd** and select **Enable sandbox\n+with gVisor** option. Select other options as you like:\n+\n+\n+\n+### Check that gVisor is enabled\n+\n+The gvisor RuntimeClass is instantiated during node creation. You can check for\n+the existence of the gvisor RuntimeClass using the following command:\n+\n+```bash\n+kubectl get runtimeclasses\n+```\n+\n+### Wordpress deployment\n+\n+Now, let's deploy a WordPress site using GKE Sandbox. WordPress site requires\n+two pods: web server in the frontend, MySQL database in the backend. Both\n+applications use PersistentVolumes to store the site data data.\n+In addition, they use secret store to share MySQL password between them.\n+\n+First, let's download the deployment configuration files to add the runtime\n+class annotation to them:\n+\n+```bash\n+curl -LO https://k8s.io/examples/application/wordpress/wordpress-deployment.yaml\n+curl -LO https://k8s.io/examples/application/wordpress/mysql-deployment.yaml\n+```\n+\n+Add a **spec.template.spec.runtimeClassName** set to **gvisor** to both files,\n+as shown below:\n+\n+**wordpress-deployment.yaml:**\n+```yaml\n+apiVersion: v1\n+kind: Service\n+metadata:\n+ name: wordpress\n+ labels:\n+ app: wordpress\n+spec:\n+ ports:\n+ - port: 80\n+ selector:\n+ app: wordpress\n+ tier: frontend\n+ type: LoadBalancer\n+---\n+apiVersion: v1\n+kind: PersistentVolumeClaim\n+metadata:\n+ name: wp-pv-claim\n+ labels:\n+ app: wordpress\n+spec:\n+ accessModes:\n+ - ReadWriteOnce\n+ resources:\n+ requests:\n+ storage: 20Gi\n+---\n+apiVersion: apps/v1\n+kind: Deployment\n+metadata:\n+ name: wordpress\n+ labels:\n+ app: wordpress\n+spec:\n+ selector:\n+ matchLabels:\n+ app: wordpress\n+ tier: frontend\n+ strategy:\n+ type: Recreate\n+ template:\n+ metadata:\n+ labels:\n+ app: wordpress\n+ tier: frontend\n+ spec:\n+ runtimeClassName: gvisor # ADD THIS LINE\n+ containers:\n+ - image: wordpress:4.8-apache\n+ name: wordpress\n+ env:\n+ - name: WORDPRESS_DB_HOST\n+ value: wordpress-mysql\n+ - name: WORDPRESS_DB_PASSWORD\n+ valueFrom:\n+ secretKeyRef:\n+ name: mysql-pass\n+ key: password\n+ ports:\n+ - containerPort: 80\n+ name: wordpress\n+ volumeMounts:\n+ - name: wordpress-persistent-storage\n+ mountPath: /var/www/html\n+ volumes:\n+ - name: wordpress-persistent-storage\n+ persistentVolumeClaim:\n+ claimName: wp-pv-claim\n+```\n+\n+**mysql-deployment.yaml:**\n+```yaml\n+apiVersion: v1\n+kind: Service\n+metadata:\n+ name: wordpress-mysql\n+ labels:\n+ app: wordpress\n+spec:\n+ ports:\n+ - port: 3306\n+ selector:\n+ app: wordpress\n+ tier: mysql\n+ clusterIP: None\n+---\n+apiVersion: v1\n+kind: PersistentVolumeClaim\n+metadata:\n+ name: mysql-pv-claim\n+ labels:\n+ app: wordpress\n+spec:\n+ accessModes:\n+ - ReadWriteOnce\n+ resources:\n+ requests:\n+ storage: 20Gi\n+---\n+apiVersion: apps/v1\n+kind: Deployment\n+metadata:\n+ name: wordpress-mysql\n+ labels:\n+ app: wordpress\n+spec:\n+ selector:\n+ matchLabels:\n+ app: wordpress\n+ tier: mysql\n+ strategy:\n+ type: Recreate\n+ template:\n+ metadata:\n+ labels:\n+ app: wordpress\n+ tier: mysql\n+ spec:\n+ runtimeClassName: gvisor # ADD THIS LINE\n+ containers:\n+ - image: mysql:5.6\n+ name: mysql\n+ env:\n+ - name: MYSQL_ROOT_PASSWORD\n+ valueFrom:\n+ secretKeyRef:\n+ name: mysql-pass\n+ key: password\n+ ports:\n+ - containerPort: 3306\n+ name: mysql\n+ volumeMounts:\n+ - name: mysql-persistent-storage\n+ mountPath: /var/lib/mysql\n+ volumes:\n+ - name: mysql-persistent-storage\n+ persistentVolumeClaim:\n+ claimName: mysql-pv-claim\n+```\n+\n+Note that apart from `runtimeClassName: gvisor`, nothing else about the\n+Deployment has is changed.\n+\n+You are now ready to deploy the entire application. Just create a secret to\n+store MySQL's password and *apply* both deployments:\n+\n+```bash\n+kubectl create secret generic mysql-pass --from-literal=password=${YOUR_SECRET_PASSWORD_HERE?}\n+kubectl apply -f mysql-deployment.yaml\n+kubectl apply -f wordpress-deployment.yaml\n+```\n+\n+Wait for the deployments to be ready and an external IP to be assigned to the\n+Wordpress service:\n+\n+```bash\n+watch kubectl get service wordpress\n+```\n+\n+Now, copy the service `EXTERNAL-IP` from above to your favorite browser to view\n+and configure your new WordPress site.\n+\n+Congratulations! You have just deployed a WordPress site using GKE Sandbox.\n+\n+### What's next\n+\n+To learn more about GKE Sandbox and how to run your deployment securely, take\n+a look at the [documentation][gke-sandbox-docs].\n+\n+[gke-sandbox-docs]: https://cloud.google.com/kubernetes-engine/docs/how-to/sandbox-pods\n+[gke-sandbox]: https://cloud.google.com/kubernetes-engine/sandbox/\n+[project-selector]: https://console.cloud.google.com/projectselector/kubernetes\n+[wordpress]: https://wordpress.com/\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": "content/docs/tutorials/node-pool-button.png",
"new_path": "content/docs/tutorials/node-pool-button.png",
"diff": "Binary files /dev/null and b/content/docs/tutorials/node-pool-button.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "content/docs/user_guide/kubernetes.md",
"new_path": "content/docs/user_guide/kubernetes.md",
"diff": "@@ -20,7 +20,19 @@ use either the `io.kubernetes.cri.untrusted-workload` annotation or\n[RuntimeClass][runtimeclass] to run Pods with `runsc`. You can find\ninstructions [here][gvisor-containerd-shim].\n+## Using GKE Sandbox\n+\n+[GKE Sandbox][gke-sandbox] is available in [Google Kubernetes Engine][gke]. You\n+just need to deploy a node pool with gVisor enabled in your cluster, and it will\n+run pods annotated with `runtimeClassName: gvisor` inside a gVisor sandbox for\n+you. [Here][wordpress-quick] is a quick example showing how to deploy a\n+WordPress site. You can view the full documentation [here][gke-sandbox-docs].\n+\n[containerd]: https://containerd.io/\n[minikube]: https://github.com/kubernetes/minikube/blob/master/deploy/addons/gvisor/README.md\n+[gke]: https://cloud.google.com/kubernetes-engine/\n+[gke-sandbox]: https://cloud.google.com/kubernetes-engine/sandbox/\n+[gke-sandbox-docs]: https://cloud.google.com/kubernetes-engine/docs/how-to/sandbox-pods\n[gvisor-containerd-shim]: https://github.com/google/gvisor-containerd-shim\n[runtimeclass]: https://kubernetes.io/docs/concepts/containers/runtime-class/\n+[wordpress-quick]: /docs/tutorials/kubernetes/\n\\ No newline at end of file\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add GKE Sandbox to Kubernetes section |
259,858 | 23.09.2019 16:43:09 | 25,200 | 6c88f674afb6065995d5758eb8cf288578d21c3d | Add test for concurrent reads and writes. | [
{
"change_type": "MODIFY",
"old_path": "pkg/p9/p9test/client_test.go",
"new_path": "pkg/p9/p9test/client_test.go",
"diff": "@@ -2127,3 +2127,98 @@ func TestConcurrency(t *testing.T) {\n}\n}\n}\n+\n+func TestReadWriteConcurrent(t *testing.T) {\n+ h, c := NewHarness(t)\n+ defer h.Finish()\n+\n+ _, root := newRoot(h, c)\n+ defer root.Close()\n+\n+ const (\n+ instances = 10\n+ iterations = 10000\n+ dataSize = 1024\n+ )\n+ var (\n+ dataSets [instances][dataSize]byte\n+ backends [instances]*Mock\n+ files [instances]p9.File\n+ )\n+\n+ // Walk to the file normally.\n+ for i := 0; i < instances; i++ {\n+ _, backends[i], files[i] = walkHelper(h, \"file\", root)\n+ defer files[i].Close()\n+ }\n+\n+ // Open the files.\n+ for i := 0; i < instances; i++ {\n+ backends[i].EXPECT().Open(p9.ReadWrite)\n+ if _, _, _, err := files[i].Open(p9.ReadWrite); err != nil {\n+ t.Fatalf(\"open got %v, wanted nil\", err)\n+ }\n+ }\n+\n+ // Initialize random data for each instance.\n+ for i := 0; i < instances; i++ {\n+ if _, err := rand.Read(dataSets[i][:]); err != nil {\n+ t.Fatalf(\"error initializing dataSet#%d, got %v\", i, err)\n+ }\n+ }\n+\n+ // Define our random read/write mechanism.\n+ randRead := func(h *Harness, backend *Mock, f p9.File, data, test []byte) {\n+ // Prepare the backend.\n+ backend.EXPECT().ReadAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {\n+ if n := copy(p, data); n != len(data) {\n+ // Note that we have to assert the result here, as the Return statement\n+ // below cannot be dynamic: it will be bound before this call is made.\n+ h.t.Errorf(\"wanted length %d, got %d\", len(data), n)\n+ }\n+ }).Return(len(data), nil)\n+\n+ // Execute the read.\n+ if n, err := f.ReadAt(test, 0); n != len(test) || err != nil {\n+ t.Errorf(\"failed read: wanted (%d, nil), got (%d, %v)\", len(test), n, err)\n+ return // No sense doing check below.\n+ }\n+ if !bytes.Equal(test, data) {\n+ t.Errorf(\"data integrity failed during read\") // Not as expected.\n+ }\n+ }\n+ randWrite := func(h *Harness, backend *Mock, f p9.File, data []byte) {\n+ // Prepare the backend.\n+ backend.EXPECT().WriteAt(gomock.Any(), uint64(0)).Do(func(p []byte, offset uint64) {\n+ if !bytes.Equal(p, data) {\n+ h.t.Errorf(\"data integrity failed during write\") // Not as expected.\n+ }\n+ }).Return(len(data), nil)\n+\n+ // Execute the write.\n+ if n, err := f.WriteAt(data, 0); n != len(data) || err != nil {\n+ t.Errorf(\"failed read: wanted (%d, nil), got (%d, %v)\", len(data), n, err)\n+ }\n+ }\n+ randReadWrite := func(n int, h *Harness, backend *Mock, f p9.File, data []byte) {\n+ test := make([]byte, len(data))\n+ for i := 0; i < n; i++ {\n+ if rand.Intn(2) == 0 {\n+ randRead(h, backend, f, data, test)\n+ } else {\n+ randWrite(h, backend, f, data)\n+ }\n+ }\n+ }\n+\n+ // Start reading and writing.\n+ var wg sync.WaitGroup\n+ for i := 0; i < instances; i++ {\n+ wg.Add(1)\n+ go func(i int) {\n+ defer wg.Done()\n+ randReadWrite(iterations, h, backends[i], files[i], dataSets[i][:])\n+ }(i)\n+ }\n+ wg.Wait()\n+}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add test for concurrent reads and writes.
PiperOrigin-RevId: 270789146 |
259,974 | 22.08.2019 09:01:47 | 0 | 2db866c45f44f302d666172aceaad92901db14af | Enable pkg/sleep support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sleep/BUILD",
"new_path": "pkg/sleep/BUILD",
"diff": "@@ -7,6 +7,7 @@ go_library(\nname = \"sleep\",\nsrcs = [\n\"commit_amd64.s\",\n+ \"commit_arm64.s\",\n\"commit_asm.go\",\n\"commit_noasm.go\",\n\"sleep_unsafe.go\",\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sleep/commit_asm.go",
"new_path": "pkg/sleep/commit_asm.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64\n+// +build amd64 arm64\npackage sleep\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sleep/commit_noasm.go",
"new_path": "pkg/sleep/commit_noasm.go",
"diff": "// limitations under the License.\n// +build !race\n-// +build !amd64\n+// +build !amd64,!arm64\npackage sleep\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable pkg/sleep support on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I9071e698c1f222e0fdf3b567ec4cbd97f0a8dde9 |
259,974 | 20.08.2019 09:44:05 | 0 | a26276b9498843218ee78c956c478ceebb819ad8 | Enable pkg/bits support on arm64. | [
{
"change_type": "MODIFY",
"old_path": "pkg/bits/BUILD",
"new_path": "pkg/bits/BUILD",
"diff": "@@ -11,8 +11,9 @@ go_library(\n\"bits.go\",\n\"bits32.go\",\n\"bits64.go\",\n- \"uint64_arch_amd64.go\",\n+ \"uint64_arch.go\",\n\"uint64_arch_amd64_asm.s\",\n+ \"uint64_arch_arm64_asm.s\",\n\"uint64_arch_generic.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/bits\",\n"
},
{
"change_type": "RENAME",
"old_path": "pkg/bits/uint64_arch_amd64.go",
"new_path": "pkg/bits/uint64_arch.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64\n+// +build amd64 arm64\npackage bits\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/bits/uint64_arch_generic.go",
"new_path": "pkg/bits/uint64_arch_generic.go",
"diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build !amd64\n+// +build !amd64,!arm64\npackage bits\n"
}
] | Go | Apache License 2.0 | google/gvisor | Enable pkg/bits support on arm64.
Signed-off-by: Haibo Xu <[email protected]>
Change-Id: I490716f0e6204f0b3a43f71931b10d1ca541e128 |
259,858 | 24.09.2019 13:25:25 | 25,200 | 502f8f238ea58c4828e528e563d8dbd419faeea7 | Stub out readahead implementation.
Closes | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/linux64.go",
"new_path": "pkg/sentry/syscalls/linux/linux64.go",
"diff": "@@ -232,7 +232,7 @@ var AMD64 = &kernel.SyscallTable{\n184: syscalls.Error(\"tuxcall\", syserror.ENOSYS, \"Not implemented in Linux.\", nil),\n185: syscalls.Error(\"security\", syserror.ENOSYS, \"Not implemented in Linux.\", nil),\n186: syscalls.Supported(\"gettid\", Gettid),\n- 187: syscalls.ErrorWithEvent(\"readahead\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/261\"}), // TODO(b/29351341)\n+ 187: syscalls.Supported(\"readahead\", Readahead),\n188: syscalls.Error(\"setxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n189: syscalls.Error(\"lsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n190: syscalls.Error(\"fsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n"
},
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_read.go",
"new_path": "pkg/sentry/syscalls/linux/sys_read.go",
"diff": "@@ -72,6 +72,39 @@ func Read(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallC\nreturn uintptr(n), nil, handleIOError(t, n != 0, err, kernel.ERESTARTSYS, \"read\", file)\n}\n+// Readahead implements readahead(2).\n+func Readahead(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ fd := args[0].Int()\n+ offset := args[1].Int64()\n+ size := args[2].SizeT()\n+\n+ file := t.GetFile(fd)\n+ if file == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer file.DecRef()\n+\n+ // Check that the file is readable.\n+ if !file.Flags().Read {\n+ return 0, nil, syserror.EBADF\n+ }\n+\n+ // Check that the size is valid.\n+ if int(size) < 0 {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\n+ // Check that the offset is legitimate.\n+ if offset < 0 {\n+ return 0, nil, syserror.EINVAL\n+ }\n+\n+ // Return EINVAL; if the underlying file type does not support readahead,\n+ // then Linux will return EINVAL to indicate as much. In the future, we\n+ // may extend this function to actually support readahead hints.\n+ return 0, nil, syserror.EINVAL\n+}\n+\n// Pread64 implements linux syscall pread64(2).\nfunc Pread64(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nfd := args[0].Int()\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/BUILD",
"new_path": "test/syscalls/BUILD",
"diff": "@@ -345,6 +345,11 @@ syscall_test(\ntest = \"//test/syscalls/linux:read_test\",\n)\n+syscall_test(\n+ add_overlay = True,\n+ test = \"//test/syscalls/linux:readahead_test\",\n+)\n+\nsyscall_test(\nsize = \"medium\",\nshard_count = 5,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/BUILD",
"new_path": "test/syscalls/linux/BUILD",
"diff": "@@ -1735,6 +1735,20 @@ cc_binary(\n],\n)\n+cc_binary(\n+ name = \"readahead_test\",\n+ testonly = 1,\n+ srcs = [\"readahead.cc\"],\n+ linkstatic = 1,\n+ deps = [\n+ \"//test/util:file_descriptor\",\n+ \"//test/util:temp_path\",\n+ \"//test/util:test_main\",\n+ \"//test/util:test_util\",\n+ \"@com_google_googletest//:gtest\",\n+ ],\n+)\n+\ncc_binary(\nname = \"readv_test\",\ntestonly = 1,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "test/syscalls/linux/readahead.cc",
"diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+#include <errno.h>\n+#include <fcntl.h>\n+\n+#include \"gtest/gtest.h\"\n+#include \"test/util/file_descriptor.h\"\n+#include \"test/util/temp_path.h\"\n+#include \"test/util/test_util.h\"\n+\n+namespace gvisor {\n+namespace testing {\n+\n+namespace {\n+\n+TEST(ReadaheadTest, InvalidFD) {\n+ EXPECT_THAT(readahead(-1, 1, 1), SyscallFailsWithErrno(EBADF));\n+}\n+\n+TEST(ReadaheadTest, InvalidOffset) {\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+ EXPECT_THAT(readahead(fd.get(), -1, 1), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+TEST(ReadaheadTest, ValidOffset) {\n+ constexpr char kData[] = \"123\";\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+\n+ // N.B. The implementation of readahead is filesystem-specific, and a file\n+ // backed by ram may return EINVAL because there is nothing to be read.\n+ EXPECT_THAT(readahead(fd.get(), 1, 1), AnyOf(SyscallSucceedsWithValue(0),\n+ SyscallFailsWithErrno(EINVAL)));\n+}\n+\n+TEST(ReadaheadTest, PastEnd) {\n+ constexpr char kData[] = \"123\";\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+ // See above.\n+ EXPECT_THAT(readahead(fd.get(), 2, 2), AnyOf(SyscallSucceedsWithValue(0),\n+ SyscallFailsWithErrno(EINVAL)));\n+}\n+\n+TEST(ReadaheadTest, CrossesEnd) {\n+ constexpr char kData[] = \"123\";\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ GetAbsoluteTestTmpdir(), kData, TempPath::kDefaultFileMode));\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+ // See above.\n+ EXPECT_THAT(readahead(fd.get(), 4, 2), AnyOf(SyscallSucceedsWithValue(0),\n+ SyscallFailsWithErrno(EINVAL)));\n+}\n+\n+TEST(ReadaheadTest, WriteOnly) {\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_WRONLY));\n+ EXPECT_THAT(readahead(fd.get(), 0, 1), SyscallFailsWithErrno(EBADF));\n+}\n+\n+TEST(ReadaheadTest, InvalidSize) {\n+ const TempPath in_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(in_file.path(), O_RDWR));\n+ EXPECT_THAT(readahead(fd.get(), 0, -1), SyscallFailsWithErrno(EINVAL));\n+}\n+\n+} // namespace\n+\n+} // namespace testing\n+} // namespace gvisor\n"
}
] | Go | Apache License 2.0 | google/gvisor | Stub out readahead implementation.
Closes #261
PiperOrigin-RevId: 270973347 |
259,993 | 24.09.2019 18:24:10 | 14,400 | 7810b30983ec4d3a706df01163c29814cd21d6ca | Refactor command line options and remove the allowed terminology for uds | [
{
"change_type": "MODIFY",
"old_path": "runsc/boot/config.go",
"new_path": "runsc/boot/config.go",
"diff": "@@ -138,8 +138,8 @@ type Config struct {\n// Overlay is whether to wrap the root filesystem in an overlay.\nOverlay bool\n- // FSGoferHostUDSAllowed enables the gofer to mount a host UDS.\n- FSGoferHostUDSAllowed bool\n+ // FSGoferHostUDS enables the gofer to mount a host UDS.\n+ FSGoferHostUDS bool\n// Network indicates what type of network to use.\nNetwork NetworkType\n@@ -217,6 +217,7 @@ func (c *Config) ToFlags() []string {\n\"--debug-log-format=\" + c.DebugLogFormat,\n\"--file-access=\" + c.FileAccess.String(),\n\"--overlay=\" + strconv.FormatBool(c.Overlay),\n+ \"--fsgofer-host-uds=\" + strconv.FormatBool(c.FSGoferHostUDS),\n\"--network=\" + c.Network.String(),\n\"--log-packets=\" + strconv.FormatBool(c.LogPackets),\n\"--platform=\" + c.Platform,\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/gofer.go",
"new_path": "runsc/cmd/gofer.go",
"diff": "@@ -59,7 +59,6 @@ type Gofer struct {\nbundleDir string\nioFDs intFlags\napplyCaps bool\n- hostUDSAllowed bool\nsetUpRoot bool\npanicOnWrite bool\n@@ -87,7 +86,6 @@ func (g *Gofer) SetFlags(f *flag.FlagSet) {\nf.StringVar(&g.bundleDir, \"bundle\", \"\", \"path to the root of the bundle directory, defaults to the current directory\")\nf.Var(&g.ioFDs, \"io-fds\", \"list of FDs to connect 9P servers. They must follow this order: root first, then mounts as defined in the spec\")\nf.BoolVar(&g.applyCaps, \"apply-caps\", true, \"if true, apply capabilities to restrict what the Gofer process can do\")\n- f.BoolVar(&g.hostUDSAllowed, \"host-uds-allowed\", false, \"if true, allow the Gofer to mount a host UDS\")\nf.BoolVar(&g.panicOnWrite, \"panic-on-write\", false, \"if true, panics on attempts to write to RO mounts. RW mounts are unnaffected\")\nf.BoolVar(&g.setUpRoot, \"setup-root\", true, \"if true, set up an empty root for the process\")\nf.IntVar(&g.specFD, \"spec-fd\", -1, \"required fd with the container spec\")\n@@ -184,7 +182,7 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\ncfg := fsgofer.Config{\nROMount: isReadonlyMount(m.Options),\nPanicOnWrite: g.panicOnWrite,\n- HostUDSAllowed: g.hostUDSAllowed,\n+ HostUDS: conf.FSGoferHostUDS,\n}\nap, err := fsgofer.NewAttachPoint(m.Destination, cfg)\nif err != nil {\n@@ -203,7 +201,7 @@ func (g *Gofer) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"too many FDs passed for mounts. mounts: %d, FDs: %d\", mountIdx, len(g.ioFDs))\n}\n- if g.hostUDSAllowed {\n+ if conf.FSGoferHostUDS {\nfilter.InstallUDSFilters()\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container.go",
"new_path": "runsc/container/container.go",
"diff": "@@ -941,11 +941,6 @@ func (c *Container) createGoferProcess(spec *specs.Spec, conf *boot.Config, bund\nargs = append(args, \"--panic-on-write=true\")\n}\n- // Add support for mounting host UDS in the gofer\n- if conf.FSGoferHostUDSAllowed {\n- args = append(args, \"--host-uds-allowed=true\")\n- }\n-\n// Open the spec file to donate to the sandbox.\nspecFile, err := specutils.OpenSpec(bundleDir)\nif err != nil {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -87,8 +87,8 @@ type Config struct {\n// PanicOnWrite panics on attempts to write to RO mounts.\nPanicOnWrite bool\n- // HostUDSAllowed signals whether the gofer can mount a host's UDS.\n- HostUDSAllowed bool\n+ // HostUDS signals whether the gofer can mount a host's UDS.\n+ HostUDS bool\n}\ntype attachPoint struct {\n@@ -143,7 +143,7 @@ func (a *attachPoint) Attach() (p9.File, error) {\nswitch fmtStat := stat.Mode & syscall.S_IFMT; fmtStat {\ncase syscall.S_IFSOCK:\n// Check to see if the CLI option has been set to allow the UDS mount.\n- if !a.conf.HostUDSAllowed {\n+ if !a.conf.HostUDS {\nreturn nil, errors.New(\"host UDS support is disabled\")\n}\n@@ -1059,6 +1059,10 @@ func (l *localFile) Flush() error {\n// Connect implements p9.File.\nfunc (l *localFile) Connect(p9.ConnectFlags) (*fd.FD, error) {\n+ // Check to see if the CLI option has been set to allow the UDS mount.\n+ if !l.attachPoint.conf.HostUDS {\n+ return nil, errors.New(\"host UDS support is disabled\")\n+ }\nreturn fd.DialUnix(l.hostPath)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/main.go",
"new_path": "runsc/main.go",
"diff": "@@ -67,7 +67,7 @@ var (\nnetwork = flag.String(\"network\", \"sandbox\", \"specifies which network to use: sandbox (default), host, none. Using network inside the sandbox is more secure because it's isolated from the host network.\")\ngso = flag.Bool(\"gso\", true, \"enable generic segmenation offload\")\nfileAccess = flag.String(\"file-access\", \"exclusive\", \"specifies which filesystem to use for the root mount: exclusive (default), shared. Volume mounts are always shared.\")\n- fsGoferHostUDSAllowed = flag.Bool(\"fsgofer-host-uds-allowed\", false, \"Allow the gofer to mount Unix Domain Sockets.\")\n+ fsGoferHostUDS = flag.Bool(\"fsgofer-host-uds\", false, \"Allow the gofer to mount Unix Domain Sockets.\")\noverlay = flag.Bool(\"overlay\", false, \"wrap filesystem mounts with writable overlay. All modifications are stored in memory inside the sandbox.\")\nwatchdogAction = flag.String(\"watchdog-action\", \"log\", \"sets what action the watchdog takes when triggered: log (default), panic.\")\npanicSignal = flag.Int(\"panic-signal\", -1, \"register signal handling that panics. Usually set to SIGUSR2(12) to troubleshoot hangs. -1 disables it.\")\n@@ -179,7 +179,7 @@ func main() {\nDebugLog: *debugLog,\nDebugLogFormat: *debugLogFormat,\nFileAccess: fsAccess,\n- FSGoferHostUDSAllowed: *fsGoferHostUDSAllowed,\n+ FSGoferHostUDS: *fsGoferHostUDS,\nOverlay: *overlay,\nNetwork: netType,\nGSO: *gso,\n"
}
] | Go | Apache License 2.0 | google/gvisor | Refactor command line options and remove the allowed terminology for uds |
259,993 | 24.09.2019 18:37:25 | 14,400 | 9ebd498a55fa87129cdc60cdc3bca66f26c49454 | Remove unecessary seccomp permission.
This removes the F_DUPFD_CLOEXEC support for the gofer, previously
required when depending on the STL net package. | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/filter/config.go",
"new_path": "runsc/fsgofer/filter/config.go",
"diff": "@@ -83,10 +83,6 @@ var allowedSyscalls = seccomp.SyscallRules{\nseccomp.AllowAny{},\nseccomp.AllowValue(syscall.F_GETFD),\n},\n- {\n- seccomp.AllowAny{},\n- seccomp.AllowValue(syscall.F_DUPFD_CLOEXEC),\n- },\n},\nsyscall.SYS_FSTAT: {},\nsyscall.SYS_FSTATFS: {},\n"
}
] | Go | Apache License 2.0 | google/gvisor | Remove unecessary seccomp permission.
This removes the F_DUPFD_CLOEXEC support for the gofer, previously
required when depending on the STL net package. |
259,853 | 24.09.2019 19:03:26 | 25,200 | 2fb34c8d5ccf13388371437d128cc95d577fbc8a | test: don't use designated initializers
This change fixes compile errors:
pty.cc:1460:7: error: expected primary-expression before '.' token
... | [
{
"change_type": "MODIFY",
"old_path": "scripts/make_tests.sh",
"new_path": "scripts/make_tests.sh",
"diff": "@@ -21,4 +21,5 @@ top_level=$(git rev-parse --show-toplevel 2>/dev/null)\nmake\nmake runsc\n+make BAZEL_OPTIONS=\"build //...\" bazel\nmake bazel-shutdown\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1292,10 +1292,9 @@ TEST_F(JobControlTest, ReleaseTTY) {\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect they TTY.\n- struct sigaction sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\n+ sa.sa_flags = 0;\nsigemptyset(&sa.sa_mask);\nstruct sigaction old_sa;\nEXPECT_THAT(sigaction(SIGHUP, &sa, &old_sa), SyscallSucceeds());\n@@ -1362,10 +1361,9 @@ TEST_F(JobControlTest, ReleaseTTYSignals) {\nASSERT_THAT(ioctl(slave_.get(), TIOCSCTTY, 0), SyscallSucceeds());\nreceived = 0;\n- struct sigaction sa = {\n- .sa_handler = sig_handler,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = sig_handler;\n+ sa.sa_flags = 0;\nsigemptyset(&sa.sa_mask);\nsigaddset(&sa.sa_mask, SIGHUP);\nsigaddset(&sa.sa_mask, SIGCONT);\n@@ -1403,10 +1401,9 @@ TEST_F(JobControlTest, ReleaseTTYSignals) {\n// Make sure we're ignoring SIGHUP, which will be sent to this process once we\n// disconnect they TTY.\n- struct sigaction sighup_sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sighup_sa = {};\n+ sighup_sa.sa_handler = SIG_IGN;\n+ sighup_sa.sa_flags = 0;\nsigemptyset(&sighup_sa.sa_mask);\nstruct sigaction old_sa;\nEXPECT_THAT(sigaction(SIGHUP, &sighup_sa, &old_sa), SyscallSucceeds());\n@@ -1456,10 +1453,9 @@ TEST_F(JobControlTest, SetForegroundProcessGroup) {\nASSERT_THAT(ioctl(slave_.get(), TIOCSCTTY, 0), SyscallSucceeds());\n// Ignore SIGTTOU so that we don't stop ourself when calling tcsetpgrp.\n- struct sigaction sa = {\n- .sa_handler = SIG_IGN,\n- .sa_flags = 0,\n- };\n+ struct sigaction sa = {};\n+ sa.sa_handler = SIG_IGN;\n+ sa.sa_flags = 0;\nsigemptyset(&sa.sa_mask);\nsigaction(SIGTTOU, &sa, NULL);\n"
}
] | Go | Apache License 2.0 | google/gvisor | test: don't use designated initializers
This change fixes compile errors:
pty.cc:1460:7: error: expected primary-expression before '.' token
...
PiperOrigin-RevId: 271033729 |
259,992 | 25.09.2019 14:31:40 | 25,200 | 129c67d68ee2db4aa3a45ab6970e7d26348ce5ef | Fix runsc log collection in kokoro | [
{
"change_type": "MODIFY",
"old_path": "runsc/sandbox/sandbox.go",
"new_path": "runsc/sandbox/sandbox.go",
"diff": "@@ -352,7 +352,7 @@ func (s *Sandbox) createSandboxProcess(conf *boot.Config, args *Args, startSyncF\n}\nif conf.DebugLog != \"\" {\ntest := \"\"\n- if len(conf.TestOnlyTestNameEnv) == 0 {\n+ if len(conf.TestOnlyTestNameEnv) != 0 {\n// Fetch test name if one is provided and the test only flag was set.\nif t, ok := specutils.EnvVar(args.Spec.Process.Env, conf.TestOnlyTestNameEnv); ok {\ntest = t\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/common_bazel.sh",
"new_path": "scripts/common_bazel.sh",
"diff": "@@ -80,7 +80,7 @@ function collect_logs() {\n# Collect sentry logs, if any.\nif [[ -v RUNSC_LOGS_DIR ]] && [[ -d \"${RUNSC_LOGS_DIR}\" ]]; then\nlocal -r logs=$(ls \"${RUNSC_LOGS_DIR}\")\n- if [[ -z \"${logs}\" ]]; then\n+ if [[ \"${logs}\" ]]; then\ntar --create --gzip --file=\"${KOKORO_ARTIFACTS_DIR}/${RUNTIME}.tar.gz\" -C \"${RUNSC_LOGS_DIR}\" .\nfi\nfi\n"
}
] | Go | Apache License 2.0 | google/gvisor | Fix runsc log collection in kokoro
PiperOrigin-RevId: 271207152 |
259,853 | 26.09.2019 14:35:57 | 25,200 | 3221e8372cbd41bbe74d0bef82519de6e2852e13 | kokoro: don't force to use python2
was fixed
and we don't need this hack anymore. | [
{
"change_type": "MODIFY",
"old_path": "scripts/build.sh",
"new_path": "scripts/build.sh",
"diff": "@@ -23,7 +23,7 @@ sudo apt-get update && sudo apt-get install -y dpkg-sig coreutils apt-utils\nrunsc=$(build -c opt //runsc)\n# Build packages.\n-pkg=$(build -c opt --host_force_python=py2 //runsc:runsc-debian)\n+pkg=$(build -c opt //runsc:runsc-debian)\n# Build a repository, if the key is available.\nif [[ -v KOKORO_REPO_KEY ]]; then\n"
}
] | Go | Apache License 2.0 | google/gvisor | kokoro: don't force to use python2
https://github.com/bazelbuild/bazel/issues/7899 was fixed
and we don't need this hack anymore.
PiperOrigin-RevId: 271434565 |
259,891 | 26.09.2019 15:07:59 | 25,200 | 543492650dd528c1d837d788dcd3b5138e8dc1c0 | Make raw socket tests pass in environments with or without CAP_NET_RAW. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/socket/epsocket/provider.go",
"new_path": "pkg/sentry/socket/epsocket/provider.go",
"diff": "@@ -65,7 +65,7 @@ func getTransportProtocol(ctx context.Context, stype linux.SockType, protocol in\n// Raw sockets require CAP_NET_RAW.\ncreds := auth.CredentialsFromContext(ctx)\nif !creds.HasCapability(linux.CAP_NET_RAW) {\n- return 0, true, syserr.ErrPermissionDenied\n+ return 0, true, syserr.ErrNotPermitted\n}\nswitch protocol {\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket.cc",
"new_path": "test/syscalls/linux/packet_socket.cc",
"diff": "@@ -83,9 +83,15 @@ 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- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ // (b/129292371): Remove once we support packet sockets.\nSKIP_IF(IsRunningOnGvisor());\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, ETH_P_PUP),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\n+\nFileDescriptor sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_PACKET, SOCK_DGRAM, ETH_P_PUP));\n@@ -118,19 +124,28 @@ class CookedPacketTest : public ::testing::TestWithParam<int> {\n};\nvoid CookedPacketTest::SetUp() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ // (b/129292371): Remove once we support packet sockets.\nSKIP_IF(IsRunningOnGvisor());\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\n+\nASSERT_THAT(socket_ = socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),\nSyscallSucceeds());\n}\nvoid CookedPacketTest::TearDown() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ // (b/129292371): Remove once we support packet sockets.\nSKIP_IF(IsRunningOnGvisor());\n+ // TearDown will be run even if we skip the test.\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n}\n+}\nint CookedPacketTest::GetLoopbackIndex() {\nstruct ifreq ifr;\n@@ -142,9 +157,6 @@ int CookedPacketTest::GetLoopbackIndex() {\n// Receive via a packet socket.\nTEST_P(CookedPacketTest, Receive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n- SKIP_IF(IsRunningOnGvisor());\n-\n// Let's use a simple IP payload: a UDP datagram.\nFileDescriptor udp_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n@@ -201,9 +213,6 @@ TEST_P(CookedPacketTest, Receive) {\n// Send via a packet socket.\nTEST_P(CookedPacketTest, Send) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n- SKIP_IF(IsRunningOnGvisor());\n-\n// Let's send a UDP packet and receive it using a regular UDP socket.\nFileDescriptor udp_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/packet_socket_raw.cc",
"new_path": "test/syscalls/linux/packet_socket_raw.cc",
"diff": "@@ -97,9 +97,15 @@ class RawPacketTest : public ::testing::TestWithParam<int> {\n};\nvoid RawPacketTest::SetUp() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ // (b/129292371): Remove once we support packet sockets.\nSKIP_IF(IsRunningOnGvisor());\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_PACKET, SOCK_RAW, htons(GetParam())),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\n+\nif (!IsRunningOnGvisor()) {\nFileDescriptor acceptLocal = ASSERT_NO_ERRNO_AND_VALUE(\nOpen(\"/proc/sys/net/ipv4/conf/lo/accept_local\", O_RDONLY));\n@@ -119,11 +125,14 @@ void RawPacketTest::SetUp() {\n}\nvoid RawPacketTest::TearDown() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ // (b/129292371): Remove once we support packet sockets.\nSKIP_IF(IsRunningOnGvisor());\n+ // TearDown will be run even if we skip the test.\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n}\n+}\nint RawPacketTest::GetLoopbackIndex() {\nstruct ifreq ifr;\n@@ -135,9 +144,6 @@ int RawPacketTest::GetLoopbackIndex() {\n// Receive via a packet socket.\nTEST_P(RawPacketTest, Receive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n- SKIP_IF(IsRunningOnGvisor());\n-\n// Let's use a simple IP payload: a UDP datagram.\nFileDescriptor udp_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n@@ -208,9 +214,6 @@ TEST_P(RawPacketTest, Receive) {\n// Send via a packet socket.\nTEST_P(RawPacketTest, Send) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n- SKIP_IF(IsRunningOnGvisor());\n-\n// Let's send a UDP packet and receive it using a regular UDP socket.\nFileDescriptor udp_sock =\nASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_hdrincl.cc",
"new_path": "test/syscalls/linux/raw_socket_hdrincl.cc",
"diff": "@@ -63,7 +63,11 @@ class RawHDRINCL : public ::testing::Test {\n};\nvoid RawHDRINCL::SetUp() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_INET, SOCK_RAW, IPPROTO_RAW),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\nASSERT_THAT(socket_ = socket(AF_INET, SOCK_RAW, IPPROTO_RAW),\nSyscallSucceeds());\n@@ -76,10 +80,11 @@ void RawHDRINCL::SetUp() {\n}\nvoid RawHDRINCL::TearDown() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\n+ // TearDown will be run even if we skip the test.\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\nEXPECT_THAT(close(socket_), SyscallSucceeds());\n}\n+}\nstruct iphdr RawHDRINCL::LoopbackHeader() {\nstruct iphdr hdr = {};\n@@ -123,8 +128,6 @@ bool RawHDRINCL::FillPacket(char* buf, size_t buf_size, int port,\n// We should be able to create multiple IPPROTO_RAW sockets. RawHDRINCL::Setup\n// creates the first one, so we only have to create one more here.\nTEST_F(RawHDRINCL, MultipleCreation) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nint s2;\nASSERT_THAT(s2 = socket(AF_INET, SOCK_RAW, IPPROTO_RAW), SyscallSucceeds());\n@@ -133,23 +136,17 @@ TEST_F(RawHDRINCL, MultipleCreation) {\n// Test that shutting down an unconnected socket fails.\nTEST_F(RawHDRINCL, FailShutdownWithoutConnect) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(shutdown(socket_, SHUT_WR), SyscallFailsWithErrno(ENOTCONN));\nASSERT_THAT(shutdown(socket_, SHUT_RD), SyscallFailsWithErrno(ENOTCONN));\n}\n// Test that listen() fails.\nTEST_F(RawHDRINCL, FailListen) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(listen(socket_, 1), SyscallFailsWithErrno(ENOTSUP));\n}\n// Test that accept() fails.\nTEST_F(RawHDRINCL, FailAccept) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nstruct sockaddr saddr;\nsocklen_t addrlen;\nASSERT_THAT(accept(socket_, &saddr, &addrlen),\n@@ -158,8 +155,6 @@ TEST_F(RawHDRINCL, FailAccept) {\n// Test that the socket is writable immediately.\nTEST_F(RawHDRINCL, PollWritableImmediately) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nstruct pollfd pfd = {};\npfd.fd = socket_;\npfd.events = POLLOUT;\n@@ -168,8 +163,6 @@ TEST_F(RawHDRINCL, PollWritableImmediately) {\n// Test that the socket isn't readable.\nTEST_F(RawHDRINCL, NotReadable) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\n// Try to receive data with MSG_DONTWAIT, which returns immediately if there's\n// nothing to be read.\nchar buf[117];\n@@ -179,16 +172,12 @@ TEST_F(RawHDRINCL, NotReadable) {\n// Test that we can connect() to a valid IP (loopback).\nTEST_F(RawHDRINCL, ConnectToLoopback) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(connect(socket_, reinterpret_cast<struct sockaddr*>(&addr_),\nsizeof(addr_)),\nSyscallSucceeds());\n}\nTEST_F(RawHDRINCL, SendWithoutConnectSucceeds) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nstruct iphdr hdr = LoopbackHeader();\nASSERT_THAT(send(socket_, &hdr, sizeof(hdr), 0),\nSyscallSucceedsWithValue(sizeof(hdr)));\n@@ -197,8 +186,6 @@ TEST_F(RawHDRINCL, SendWithoutConnectSucceeds) {\n// HDRINCL implies write-only. Verify that we can't read a packet sent to\n// loopback.\nTEST_F(RawHDRINCL, NotReadableAfterWrite) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(connect(socket_, reinterpret_cast<struct sockaddr*>(&addr_),\nsizeof(addr_)),\nSyscallSucceeds());\n@@ -221,8 +208,6 @@ TEST_F(RawHDRINCL, NotReadableAfterWrite) {\n}\nTEST_F(RawHDRINCL, WriteTooSmall) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(connect(socket_, reinterpret_cast<struct sockaddr*>(&addr_),\nsizeof(addr_)),\nSyscallSucceeds());\n@@ -235,8 +220,6 @@ TEST_F(RawHDRINCL, WriteTooSmall) {\n// Bind to localhost.\nTEST_F(RawHDRINCL, BindToLocalhost) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nASSERT_THAT(\nbind(socket_, reinterpret_cast<struct sockaddr*>(&addr_), sizeof(addr_)),\nSyscallSucceeds());\n@@ -244,8 +227,6 @@ TEST_F(RawHDRINCL, BindToLocalhost) {\n// Bind to a different address.\nTEST_F(RawHDRINCL, BindToInvalid) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nstruct sockaddr_in bind_addr = {};\nbind_addr.sin_family = AF_INET;\nbind_addr.sin_addr = {1}; // 1.0.0.0 - An address that we can't bind to.\n@@ -256,8 +237,6 @@ TEST_F(RawHDRINCL, BindToInvalid) {\n// Send and receive a packet.\nTEST_F(RawHDRINCL, SendAndReceive) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nint port = 40000;\nif (!IsRunningOnGvisor()) {\nport = static_cast<short>(ASSERT_NO_ERRNO_AND_VALUE(\n@@ -302,8 +281,6 @@ TEST_F(RawHDRINCL, SendAndReceive) {\n// Send and receive a packet with nonzero IP ID.\nTEST_F(RawHDRINCL, SendAndReceiveNonzeroID) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nint port = 40000;\nif (!IsRunningOnGvisor()) {\nport = static_cast<short>(ASSERT_NO_ERRNO_AND_VALUE(\n@@ -349,8 +326,6 @@ TEST_F(RawHDRINCL, SendAndReceiveNonzeroID) {\n// Send and receive a packet where the sendto address is not the same as the\n// provided destination.\nTEST_F(RawHDRINCL, SendAndReceiveDifferentAddress) {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\nint port = 40000;\nif (!IsRunningOnGvisor()) {\nport = static_cast<short>(ASSERT_NO_ERRNO_AND_VALUE(\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_icmp.cc",
"new_path": "test/syscalls/linux/raw_socket_icmp.cc",
"diff": "@@ -77,7 +77,11 @@ class RawSocketICMPTest : public ::testing::Test {\n};\nvoid RawSocketICMPTest::SetUp() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_INET, SOCK_RAW, IPPROTO_ICMP),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\nASSERT_THAT(s_ = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP), SyscallSucceeds());\n@@ -90,10 +94,11 @@ void RawSocketICMPTest::SetUp() {\n}\nvoid RawSocketICMPTest::TearDown() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\n+ // TearDown will be run even if we skip the test.\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n}\n+}\n// We'll only read an echo in this case, as the kernel won't respond to the\n// malformed ICMP checksum.\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/raw_socket_ipv4.cc",
"new_path": "test/syscalls/linux/raw_socket_ipv4.cc",
"diff": "@@ -67,7 +67,11 @@ class RawSocketTest : public ::testing::TestWithParam<int> {\n};\nvoid RawSocketTest::SetUp() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n+ if (!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\n+ ASSERT_THAT(socket(AF_INET, SOCK_RAW, Protocol()),\n+ SyscallFailsWithErrno(EPERM));\n+ GTEST_SKIP();\n+ }\nASSERT_THAT(s_ = socket(AF_INET, SOCK_RAW, Protocol()), SyscallSucceeds());\n@@ -79,10 +83,11 @@ void RawSocketTest::SetUp() {\n}\nvoid RawSocketTest::TearDown() {\n- SKIP_IF(!ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW)));\n-\n+ // TearDown will be run even if we skip the test.\n+ if (ASSERT_NO_ERRNO_AND_VALUE(HaveCapability(CAP_NET_RAW))) {\nEXPECT_THAT(close(s_), SyscallSucceeds());\n}\n+}\n// We should be able to create multiple raw sockets for the same protocol.\n// BasicRawSocket::Setup creates the first one, so we only have to create one\n"
}
] | Go | Apache License 2.0 | google/gvisor | Make raw socket tests pass in environments with or without CAP_NET_RAW.
PiperOrigin-RevId: 271442321 |
259,992 | 26.09.2019 18:14:45 | 25,200 | 8337e4f50955863c6aa3a7df70b1446b9dba66ae | Disallow opening of sockets if --fsgofer-host-uds=false
Updates | [
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer.go",
"new_path": "runsc/fsgofer/fsgofer.go",
"diff": "@@ -136,6 +136,10 @@ func (a *attachPoint) Attach() (p9.File, error) {\na.attachedMu.Lock()\ndefer a.attachedMu.Unlock()\n+ if a.attached {\n+ return nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n+ }\n+\n// Hold the file descriptor we are converting into a p9.File.\nvar f *fd.FD\n@@ -170,12 +174,6 @@ func (a *attachPoint) Attach() (p9.File, error) {\n}\n}\n- // Close the connection if already attached.\n- if a.attached {\n- f.Close()\n- return nil, fmt.Errorf(\"attach point already attached, prefix: %s\", a.prefix)\n- }\n-\n// Return a localFile object to the caller with the UDS FD included.\nrv, err := newLocalFile(a, f, a.prefix, stat)\nif err != nil {\n@@ -330,7 +328,7 @@ func openAnyFile(path string, fn func(mode int) (*fd.FD, error)) (*fd.FD, error)\nreturn file, nil\n}\n-func getSupportedFileType(stat syscall.Stat_t) (fileType, error) {\n+func getSupportedFileType(stat syscall.Stat_t, permitSocket bool) (fileType, error) {\nvar ft fileType\nswitch stat.Mode & syscall.S_IFMT {\ncase syscall.S_IFREG:\n@@ -340,6 +338,9 @@ func getSupportedFileType(stat syscall.Stat_t) (fileType, error) {\ncase syscall.S_IFLNK:\nft = symlink\ncase syscall.S_IFSOCK:\n+ if !permitSocket {\n+ return unknown, syscall.EPERM\n+ }\nft = socket\ndefault:\nreturn unknown, syscall.EPERM\n@@ -348,7 +349,7 @@ func getSupportedFileType(stat syscall.Stat_t) (fileType, error) {\n}\nfunc newLocalFile(a *attachPoint, file *fd.FD, path string, stat syscall.Stat_t) (*localFile, error) {\n- ft, err := getSupportedFileType(stat)\n+ ft, err := getSupportedFileType(stat, a.conf.HostUDS)\nif err != nil {\nreturn nil, err\n}\n@@ -1065,7 +1066,7 @@ func (l *localFile) Flush() error {\nfunc (l *localFile) Connect(p9.ConnectFlags) (*fd.FD, error) {\n// Check to see if the CLI option has been set to allow the UDS mount.\nif !l.attachPoint.conf.HostUDS {\n- return nil, errors.New(\"host UDS support is disabled\")\n+ return nil, syscall.ECONNREFUSED\n}\nreturn fd.DialUnix(l.hostPath)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/fsgofer/fsgofer_test.go",
"new_path": "runsc/fsgofer/fsgofer_test.go",
"diff": "@@ -665,7 +665,7 @@ func TestAttachInvalidType(t *testing.T) {\n}\nf, err := a.Attach()\nif f != nil || err == nil {\n- t.Fatalf(\"Attach should have failed, got (%v, nil)\", f)\n+ t.Fatalf(\"Attach should have failed, got (%v, %v)\", f, err)\n}\n})\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Disallow opening of sockets if --fsgofer-host-uds=false
Updates #235
PiperOrigin-RevId: 271475319 |
259,853 | 27.09.2019 09:48:46 | 25,200 | fa15fda6c4ea2f4f10ec0c60ccc5af3f66ed87c4 | bazel: use rules_pkg from
BUILD:85:1: in _pkg_deb rule //runsc:runsc-debian: target
'//runsc:runsc-debian' depends on deprecated target
'@bazel_tools//tools/build_defs/pkg:make_deb': The internal version of
make_deb is deprecated. Please use the replacement for pkg_deb from | [
{
"change_type": "MODIFY",
"old_path": "WORKSPACE",
"new_path": "WORKSPACE",
"diff": "@@ -75,6 +75,16 @@ load(\"@bazel_toolchains//rules:rbe_repo.bzl\", \"rbe_autoconfig\")\nrbe_autoconfig(name = \"rbe_default\")\n+http_archive(\n+ name = \"rules_pkg\",\n+ sha256 = \"5bdc04987af79bd27bc5b00fe30f59a858f77ffa0bd2d8143d5b31ad8b1bd71c\",\n+ url = \"https://github.com/bazelbuild/rules_pkg/releases/download/0.2.0/rules_pkg-0.2.0.tar.gz\",\n+)\n+\n+load(\"@rules_pkg//:deps.bzl\", \"rules_pkg_dependencies\")\n+\n+rules_pkg_dependencies()\n+\n# External repositories, in sorted order.\ngo_repository(\nname = \"com_github_cenkalti_backoff\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/BUILD",
"new_path": "runsc/BUILD",
"diff": "package(licenses = [\"notice\"]) # Apache 2.0\nload(\"@io_bazel_rules_go//go:def.bzl\", \"go_binary\")\n-load(\"@bazel_tools//tools/build_defs/pkg:pkg.bzl\", \"pkg_deb\", \"pkg_tar\")\n+load(\"@rules_pkg//:pkg.bzl\", \"pkg_deb\", \"pkg_tar\")\ngo_binary(\nname = \"runsc\",\n"
}
] | Go | Apache License 2.0 | google/gvisor | bazel: use rules_pkg from https://github.com/bazelbuild/
BUILD:85:1: in _pkg_deb rule //runsc:runsc-debian: target
'//runsc:runsc-debian' depends on deprecated target
'@bazel_tools//tools/build_defs/pkg:make_deb': The internal version of
make_deb is deprecated. Please use the replacement for pkg_deb from
https://github.com/bazelbuild/rules_pkg/blob/master/pkg.
PiperOrigin-RevId: 271590386 |
259,881 | 30.09.2019 10:02:14 | 25,200 | 981fc188f0f0250ad59e39d566a56c71430b3287 | Only copy out remaining time on nanosleep success
It looks like the old code attempted to do this, but didn't realize that err !=
nil even in the happy case. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_time.go",
"new_path": "pkg/sentry/syscalls/linux/sys_time.go",
"diff": "package linux\nimport (\n+ \"fmt\"\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -228,41 +229,35 @@ func clockNanosleepFor(t *kernel.Task, c ktime.Clock, dur time.Duration, rem use\ntimer.Destroy()\n- var remaining time.Duration\n- // Did we just block for the entire duration?\n- if err == syserror.ETIMEDOUT {\n- remaining = 0\n- } else {\n- remaining = dur - after.Sub(start)\n+ switch err {\n+ case syserror.ETIMEDOUT:\n+ // Slept for entire timeout.\n+ return nil\n+ case syserror.ErrInterrupted:\n+ // Interrupted.\n+ remaining := dur - after.Sub(start)\nif remaining < 0 {\nremaining = time.Duration(0)\n}\n- }\n// Copy out remaining time.\n- if err != nil && rem != usermem.Addr(0) {\n+ if rem != 0 {\ntimeleft := linux.NsecToTimespec(remaining.Nanoseconds())\nif err := copyTimespecOut(t, rem, &timeleft); err != nil {\nreturn err\n}\n}\n- // Did we just block for the entire duration?\n- if err == syserror.ETIMEDOUT {\n- return nil\n- }\n-\n- // If interrupted, arrange for a restart with the remaining duration.\n- if err == syserror.ErrInterrupted {\n+ // Arrange for a restart with the remaining duration.\nt.SetSyscallRestartBlock(&clockNanosleepRestartBlock{\nc: c,\nduration: remaining,\nrem: rem,\n})\nreturn kernel.ERESTART_RESTARTBLOCK\n+ default:\n+ panic(fmt.Sprintf(\"Impossible BlockWithTimer error %v\", err))\n}\n-\n- return err\n}\n// Nanosleep implements linux syscall Nanosleep(2).\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/clock_nanosleep.cc",
"new_path": "test/syscalls/linux/clock_nanosleep.cc",
"diff": "@@ -43,7 +43,7 @@ int sys_clock_nanosleep(clockid_t clkid, int flags,\nPosixErrorOr<absl::Time> GetTime(clockid_t clk) {\nstruct timespec ts = {};\n- int rc = clock_gettime(clk, &ts);\n+ const int rc = clock_gettime(clk, &ts);\nMaybeSave();\nif (rc < 0) {\nreturn PosixError(errno, \"clock_gettime\");\n@@ -67,31 +67,32 @@ TEST_P(WallClockNanosleepTest, InvalidValues) {\n}\nTEST_P(WallClockNanosleepTest, SleepOneSecond) {\n- absl::Duration const duration = absl::Seconds(1);\n- struct timespec dur = absl::ToTimespec(duration);\n+ constexpr absl::Duration kSleepDuration = absl::Seconds(1);\n+ struct timespec duration = absl::ToTimespec(kSleepDuration);\n- absl::Time const before = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n- EXPECT_THAT(RetryEINTR(sys_clock_nanosleep)(GetParam(), 0, &dur, &dur),\n+ const absl::Time before = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ EXPECT_THAT(\n+ RetryEINTR(sys_clock_nanosleep)(GetParam(), 0, &duration, &duration),\nSyscallSucceeds());\n- absl::Time const after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ const absl::Time after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n- EXPECT_GE(after - before, duration);\n+ EXPECT_GE(after - before, kSleepDuration);\n}\nTEST_P(WallClockNanosleepTest, InterruptedNanosleep) {\n- absl::Duration const duration = absl::Seconds(60);\n- struct timespec dur = absl::ToTimespec(duration);\n+ constexpr absl::Duration kSleepDuration = absl::Seconds(60);\n+ struct timespec duration = absl::ToTimespec(kSleepDuration);\n// Install no-op signal handler for SIGALRM.\nstruct sigaction sa = {};\nsigfillset(&sa.sa_mask);\nsa.sa_handler = +[](int signo) {};\n- auto const cleanup_sa =\n+ const auto cleanup_sa =\nASSERT_NO_ERRNO_AND_VALUE(ScopedSigaction(SIGALRM, sa));\n// Measure time since setting the alarm, since the alarm will interrupt the\n// sleep and hence determine how long we sleep.\n- absl::Time const before = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ const absl::Time before = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n// Set an alarm to go off while sleeping.\nstruct itimerval timer = {};\n@@ -99,26 +100,51 @@ TEST_P(WallClockNanosleepTest, InterruptedNanosleep) {\ntimer.it_value.tv_usec = 0;\ntimer.it_interval.tv_sec = 1;\ntimer.it_interval.tv_usec = 0;\n- auto const cleanup =\n+ const auto cleanup =\nASSERT_NO_ERRNO_AND_VALUE(ScopedItimer(ITIMER_REAL, timer));\n- EXPECT_THAT(sys_clock_nanosleep(GetParam(), 0, &dur, &dur),\n+ EXPECT_THAT(sys_clock_nanosleep(GetParam(), 0, &duration, &duration),\nSyscallFailsWithErrno(EINTR));\n- absl::Time const after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ const absl::Time after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+\n+ // Remaining time updated.\n+ const absl::Duration remaining = absl::DurationFromTimespec(duration);\n+ EXPECT_GE(after - before + remaining, kSleepDuration);\n+}\n- absl::Duration const remaining = absl::DurationFromTimespec(dur);\n- EXPECT_GE(after - before + remaining, duration);\n+// Remaining time is *not* updated if nanosleep completes uninterrupted.\n+TEST_P(WallClockNanosleepTest, UninterruptedNanosleep) {\n+ constexpr absl::Duration kSleepDuration = absl::Milliseconds(10);\n+ const struct timespec duration = absl::ToTimespec(kSleepDuration);\n+\n+ while (true) {\n+ constexpr int kRemainingMagic = 42;\n+ struct timespec remaining;\n+ remaining.tv_sec = kRemainingMagic;\n+ remaining.tv_nsec = kRemainingMagic;\n+\n+ int ret = sys_clock_nanosleep(GetParam(), 0, &duration, &remaining);\n+ if (ret == EINTR) {\n+ // Retry from beginning. We want a single uninterrupted call.\n+ continue;\n+ }\n+\n+ EXPECT_THAT(ret, SyscallSucceeds());\n+ EXPECT_EQ(remaining.tv_sec, kRemainingMagic);\n+ EXPECT_EQ(remaining.tv_nsec, kRemainingMagic);\n+ break;\n+ }\n}\nTEST_P(WallClockNanosleepTest, SleepUntil) {\n- absl::Time const now = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n- absl::Time const until = now + absl::Seconds(2);\n- struct timespec ts = absl::ToTimespec(until);\n+ const absl::Time now = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ const absl::Time until = now + absl::Seconds(2);\n+ const struct timespec ts = absl::ToTimespec(until);\nEXPECT_THAT(\nRetryEINTR(sys_clock_nanosleep)(GetParam(), TIMER_ABSTIME, &ts, nullptr),\nSyscallSucceeds());\n- absl::Time const after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\n+ const absl::Time after = ASSERT_NO_ERRNO_AND_VALUE(GetTime(GetParam()));\nEXPECT_GE(after, until);\n}\n@@ -127,8 +153,8 @@ INSTANTIATE_TEST_SUITE_P(Sleepers, WallClockNanosleepTest,\n::testing::Values(CLOCK_REALTIME, CLOCK_MONOTONIC));\nTEST(ClockNanosleepProcessTest, SleepFiveSeconds) {\n- absl::Duration const kDuration = absl::Seconds(5);\n- struct timespec dur = absl::ToTimespec(kDuration);\n+ const absl::Duration kSleepDuration = absl::Seconds(5);\n+ struct timespec duration = absl::ToTimespec(kSleepDuration);\n// Ensure that CLOCK_PROCESS_CPUTIME_ID advances.\nstd::atomic<bool> done(false);\n@@ -136,16 +162,16 @@ TEST(ClockNanosleepProcessTest, SleepFiveSeconds) {\nwhile (!done.load()) {\n}\n});\n- auto const cleanup_done = Cleanup([&] { done.store(true); });\n+ const auto cleanup_done = Cleanup([&] { done.store(true); });\n- absl::Time const before =\n+ const absl::Time before =\nASSERT_NO_ERRNO_AND_VALUE(GetTime(CLOCK_PROCESS_CPUTIME_ID));\n- EXPECT_THAT(\n- RetryEINTR(sys_clock_nanosleep)(CLOCK_PROCESS_CPUTIME_ID, 0, &dur, &dur),\n+ EXPECT_THAT(RetryEINTR(sys_clock_nanosleep)(CLOCK_PROCESS_CPUTIME_ID, 0,\n+ &duration, &duration),\nSyscallSucceeds());\n- absl::Time const after =\n+ const absl::Time after =\nASSERT_NO_ERRNO_AND_VALUE(GetTime(CLOCK_PROCESS_CPUTIME_ID));\n- EXPECT_GE(after - before, kDuration);\n+ EXPECT_GE(after - before, kSleepDuration);\n}\n} // namespace\n"
}
] | Go | Apache License 2.0 | google/gvisor | Only copy out remaining time on nanosleep success
It looks like the old code attempted to do this, but didn't realize that err !=
nil even in the happy case.
PiperOrigin-RevId: 272005887 |
259,891 | 30.09.2019 13:57:15 | 25,200 | c06cca66780baf81422e56badee2abaf28f017c7 | De-flake SetForegroundProcessGroupDifferentSession. | [
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/pty.cc",
"new_path": "test/syscalls/linux/pty.cc",
"diff": "@@ -1527,27 +1527,36 @@ TEST_F(JobControlTest, SetForegroundProcessGroupEmptyProcessGroup) {\nTEST_F(JobControlTest, SetForegroundProcessGroupDifferentSession) {\nASSERT_THAT(ioctl(slave_.get(), TIOCSCTTY, 0), SyscallSucceeds());\n+ int sync_setsid[2];\n+ int sync_exit[2];\n+ ASSERT_THAT(pipe(sync_setsid), SyscallSucceeds());\n+ ASSERT_THAT(pipe(sync_exit), SyscallSucceeds());\n+\n// Create a new process and put it in a new session.\npid_t child = fork();\nif (!child) {\nTEST_PCHECK(setsid() >= 0);\n// Tell the parent we're in a new session.\n- TEST_PCHECK(!raise(SIGSTOP));\n- TEST_PCHECK(!pause());\n- _exit(1);\n+ char c = 'c';\n+ TEST_PCHECK(WriteFd(sync_setsid[1], &c, 1) == 1);\n+ TEST_PCHECK(ReadFd(sync_exit[0], &c, 1) == 1);\n+ _exit(0);\n}\n// Wait for the child to tell us it's in a new session.\n- int wstatus;\n- EXPECT_THAT(waitpid(child, &wstatus, WUNTRACED),\n- SyscallSucceedsWithValue(child));\n- EXPECT_TRUE(WSTOPSIG(wstatus));\n+ char c = 'c';\n+ ASSERT_THAT(ReadFd(sync_setsid[0], &c, 1), SyscallSucceedsWithValue(1));\n// Child is in a new session, so we can't make it the foregroup process group.\nEXPECT_THAT(ioctl(slave_.get(), TIOCSPGRP, &child),\nSyscallFailsWithErrno(EPERM));\n- EXPECT_THAT(kill(child, SIGKILL), SyscallSucceeds());\n+ EXPECT_THAT(WriteFd(sync_exit[1], &c, 1), SyscallSucceedsWithValue(1));\n+\n+ int wstatus;\n+ EXPECT_THAT(waitpid(child, &wstatus, 0), SyscallSucceedsWithValue(child));\n+ EXPECT_TRUE(WIFEXITED(wstatus));\n+ EXPECT_EQ(WEXITSTATUS(wstatus), 0);\n}\n// Verify that we don't hang when creating a new session from an orphaned\n"
}
] | Go | Apache License 2.0 | google/gvisor | De-flake SetForegroundProcessGroupDifferentSession.
PiperOrigin-RevId: 272059043 |
259,962 | 30.09.2019 15:51:35 | 25,200 | bcbb3ef317cb029f2553a8cdc03801f517b0fde4 | Add a Stringer implementation to PacketDispatchMode | [
{
"change_type": "MODIFY",
"old_path": "pkg/tcpip/link/fdbased/endpoint.go",
"new_path": "pkg/tcpip/link/fdbased/endpoint.go",
"diff": "@@ -82,7 +82,19 @@ const (\nPacketMMap\n)\n-// An endpoint implements the link-layer using a message-oriented file descriptor.\n+func (p PacketDispatchMode) String() string {\n+ switch p {\n+ case Readv:\n+ return \"Readv\"\n+ case RecvMMsg:\n+ return \"RecvMMsg\"\n+ case PacketMMap:\n+ return \"PacketMMap\"\n+ default:\n+ return fmt.Sprintf(\"unknown packet dispatch mode %v\", p)\n+ }\n+}\n+\ntype endpoint struct {\n// fds is the set of file descriptors each identifying one inbound/outbound\n// channel. The endpoint will dispatch from all inbound channels as well as\n"
}
] | Go | Apache License 2.0 | google/gvisor | Add a Stringer implementation to PacketDispatchMode
PiperOrigin-RevId: 272083936 |
259,858 | 30.09.2019 17:23:03 | 25,200 | 20841b98e14dd37aa40886668e337551b18f0fd3 | Update FIXME bug with GitHub issue. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/sighandling/sighandling_unsafe.go",
"new_path": "pkg/sentry/sighandling/sighandling_unsafe.go",
"diff": "@@ -23,7 +23,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n)\n-// TODO(b/34161764): Move to pkg/abi/linux along with definitions in\n+// FIXME(gvisor.dev/issue/214): Move to pkg/abi/linux along with definitions in\n// pkg/sentry/arch.\ntype sigaction struct {\nhandler uintptr\n"
}
] | Go | Apache License 2.0 | google/gvisor | Update FIXME bug with GitHub issue.
PiperOrigin-RevId: 272101930 |
259,853 | 30.09.2019 17:55:55 | 25,200 | 29a1ba54ea427d4fdd357453d74c93d16f5eca9b | splice: compare inode numbers only if both ends are pipes
It isn't allowed to splice data from and into the same pipe.
But right now this check is broken, because we don't check that both ends are
pipes. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"new_path": "pkg/sentry/syscalls/linux/sys_splice.go",
"diff": "@@ -245,14 +245,14 @@ func Splice(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscal\nif inOffset != 0 || outOffset != 0 {\nreturn 0, nil, syserror.ESPIPE\n}\n- default:\n- return 0, nil, syserror.EINVAL\n- }\n// We may not refer to the same pipe; otherwise it's a continuous loop.\nif inFile.Dirent.Inode.StableAttr.InodeID == outFile.Dirent.Inode.StableAttr.InodeID {\nreturn 0, nil, syserror.EINVAL\n}\n+ default:\n+ return 0, nil, syserror.EINVAL\n+ }\n// Splice data.\nn, err := doSplice(t, outFile, inFile, opts, nonBlock)\n"
}
] | Go | Apache License 2.0 | google/gvisor | splice: compare inode numbers only if both ends are pipes
It isn't allowed to splice data from and into the same pipe.
But right now this check is broken, because we don't check that both ends are
pipes.
PiperOrigin-RevId: 272107022 |
259,853 | 30.09.2019 18:22:25 | 25,200 | 7a234f736fe0e91824b50631e408bd07b2c0ed31 | splice: try another fallback option only if the previous one isn't supported
Reported-by: | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/fs/splice.go",
"new_path": "pkg/sentry/fs/splice.go",
"diff": "@@ -139,7 +139,7 @@ func Splice(ctx context.Context, dst *File, src *File, opts SpliceOpts) (int64,\n// Attempt to do a WriteTo; this is likely the most efficient.\nn, err := src.FileOperations.WriteTo(ctx, src, w, opts.Length, opts.Dup)\n- if n == 0 && err != nil && err != syserror.ErrWouldBlock && !opts.Dup {\n+ if n == 0 && err == syserror.ENOSYS && !opts.Dup {\n// Attempt as a ReadFrom. If a WriteTo, a ReadFrom may also be\n// more efficient than a copy if buffers are cached or readily\n// available. (It's unlikely that they can actually be donated).\n@@ -151,7 +151,7 @@ func Splice(ctx context.Context, dst *File, src *File, opts SpliceOpts) (int64,\n// if we block at some point, we could lose data. If the source is\n// not a pipe then reading is not destructive; if the destination\n// is a regular file, then it is guaranteed not to block writing.\n- if n == 0 && err != nil && err != syserror.ErrWouldBlock && !opts.Dup && (!dstPipe || !srcPipe) {\n+ if n == 0 && err == syserror.ENOSYS && !opts.Dup && (!dstPipe || !srcPipe) {\n// Fallback to an in-kernel copy.\nn, err = io.Copy(w, &io.LimitedReader{\nR: r,\n"
}
] | Go | Apache License 2.0 | google/gvisor | splice: try another fallback option only if the previous one isn't supported
Reported-by: [email protected]
PiperOrigin-RevId: 272110815 |
259,881 | 01.10.2019 11:29:35 | 25,200 | 53cc72da90f5b5a76b024b47fe4e38a81b495eb4 | Honor X bit on extra anon pages in PT_LOAD segments
Linux changed this behavior in
(v4.11). Previously, extra pages were always mapped RW. Now, those pages will
be executable if the segment specified PF_X. They still must be writeable. | [
{
"change_type": "MODIFY",
"old_path": "pkg/sentry/loader/elf.go",
"new_path": "pkg/sentry/loader/elf.go",
"diff": "@@ -323,6 +323,14 @@ func mapSegment(ctx context.Context, m *mm.MemoryManager, f *fs.File, phdr *elf.\nreturn syserror.ENOEXEC\n}\n+ // N.B. Linux uses vm_brk_flags to map these pages, which only\n+ // honors the X bit, always mapping at least RW. ignoring These\n+ // pages are not included in the final brk region.\n+ prot := usermem.ReadWrite\n+ if phdr.Flags&elf.PF_X == elf.PF_X {\n+ prot.Execute = true\n+ }\n+\nif _, err := m.MMap(ctx, memmap.MMapOpts{\nLength: uint64(anonSize),\nAddr: anonAddr,\n@@ -330,11 +338,7 @@ func mapSegment(ctx context.Context, m *mm.MemoryManager, f *fs.File, phdr *elf.\n// already at addr.\nFixed: true,\nPrivate: true,\n- // N.B. Linux uses vm_brk to map these pages, ignoring\n- // the segment protections, instead always mapping RW.\n- // These pages are not included in the final brk\n- // region.\n- Perms: usermem.ReadWrite,\n+ Perms: prot,\nMaxPerms: usermem.AnyAccess,\n}); err != nil {\nctx.Infof(\"Error mapping PT_LOAD segment %v anonymous memory: %v\", phdr, err)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/syscalls/linux/exec_binary.cc",
"new_path": "test/syscalls/linux/exec_binary.cc",
"diff": "@@ -401,12 +401,17 @@ TEST(ElfTest, DataSegment) {\n})));\n}\n-// Additonal pages beyond filesz are always RW.\n+// Additonal pages beyond filesz honor (only) execute protections.\n//\n-// N.B. Linux uses set_brk -> vm_brk to additional pages beyond filesz (even\n-// though start_brk itself will always be beyond memsz). As a result, the\n-// segment permissions don't apply; the mapping is always RW.\n+// N.B. Linux changed this in 4.11 (16e72e9b30986 \"powerpc: do not make the\n+// entire heap executable\"). Previously, extra pages were always RW.\nTEST(ElfTest, ExtraMemPages) {\n+ // gVisor has the newer behavior.\n+ if (!IsRunningOnGvisor()) {\n+ auto version = ASSERT_NO_ERRNO_AND_VALUE(GetKernelVersion());\n+ SKIP_IF(version.major < 4 || (version.major == 4 && version.minor < 11));\n+ }\n+\nElfBinary<64> elf = StandardElf();\n// Create a standard ELF, but extend to 1.5 pages. The second page will be the\n@@ -415,7 +420,7 @@ TEST(ElfTest, ExtraMemPages) {\ndecltype(elf)::ElfPhdr phdr = {};\nphdr.p_type = PT_LOAD;\n- // RWX segment. The extra anon page will be RW anyways.\n+ // RWX segment. The extra anon page will also be RWX.\n//\n// N.B. Linux uses clear_user to clear the end of the file-mapped page, which\n// respects the mapping protections. Thus if we map this RO with memsz >\n@@ -454,7 +459,7 @@ TEST(ElfTest, ExtraMemPages) {\n{0x41000, 0x42000, true, true, true, true, kPageSize, 0, 0, 0,\nfile.path().c_str()},\n// extra page from anon.\n- {0x42000, 0x43000, true, true, false, true, 0, 0, 0, 0, \"\"},\n+ {0x42000, 0x43000, true, true, true, true, 0, 0, 0, 0, \"\"},\n})));\n}\n@@ -469,7 +474,7 @@ TEST(ElfTest, AnonOnlySegment) {\nphdr.p_offset = 0;\nphdr.p_vaddr = 0x41000;\nphdr.p_filesz = 0;\n- phdr.p_memsz = kPageSize - 0xe8;\n+ phdr.p_memsz = kPageSize;\nelf.phdrs.push_back(phdr);\nelf.UpdateOffsets();\n"
},
{
"change_type": "MODIFY",
"old_path": "test/util/proc_util.cc",
"new_path": "test/util/proc_util.cc",
"diff": "@@ -88,7 +88,7 @@ PosixErrorOr<std::vector<ProcMapsEntry>> ParseProcMaps(\nstd::vector<ProcMapsEntry> entries;\nauto lines = absl::StrSplit(contents, '\\n', absl::SkipEmpty());\nfor (const auto& l : lines) {\n- std::cout << \"line: \" << l;\n+ std::cout << \"line: \" << l << std::endl;\nASSIGN_OR_RETURN_ERRNO(auto entry, ParseProcMapsLine(l));\nentries.push_back(entry);\n}\n"
}
] | Go | Apache License 2.0 | google/gvisor | Honor X bit on extra anon pages in PT_LOAD segments
Linux changed this behavior in 16e72e9b30986ee15f17fbb68189ca842c32af58
(v4.11). Previously, extra pages were always mapped RW. Now, those pages will
be executable if the segment specified PF_X. They still must be writeable.
PiperOrigin-RevId: 272256280 |
259,992 | 01.10.2019 11:48:24 | 25,200 | 0b02c3d5e5bae87f5cdbf4ae20dad8344bef32c2 | Prevent CAP_NET_RAW from appearing in exec
'docker exec' was getting CAP_NET_RAW even when --net-raw=false
because it was not filtered out from when copying container's
capabilities. | [
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/exec.go",
"new_path": "runsc/cmd/exec.go",
"diff": "@@ -105,11 +105,11 @@ func (ex *Exec) SetFlags(f *flag.FlagSet) {\n// Execute implements subcommands.Command.Execute. It starts a process in an\n// already created container.\nfunc (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n- e, id, err := ex.parseArgs(f)\n+ conf := args[0].(*boot.Config)\n+ e, id, err := ex.parseArgs(f, conf.EnableRaw)\nif err != nil {\nFatalf(\"parsing process spec: %v\", err)\n}\n- conf := args[0].(*boot.Config)\nwaitStatus := args[1].(*syscall.WaitStatus)\nc, err := container.Load(conf.RootDir, id)\n@@ -117,6 +117,9 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\nFatalf(\"loading sandbox: %v\", err)\n}\n+ log.Debugf(\"Exec arguments: %+v\", e)\n+ log.Debugf(\"Exec capablities: %+v\", e.Capabilities)\n+\n// Replace empty settings with defaults from container.\nif e.WorkingDirectory == \"\" {\ne.WorkingDirectory = c.Spec.Process.Cwd\n@@ -129,14 +132,11 @@ func (ex *Exec) Execute(_ context.Context, f *flag.FlagSet, args ...interface{})\n}\nif e.Capabilities == nil {\n- // enableRaw is set to true to prevent the filtering out of\n- // CAP_NET_RAW. This is the opposite of Create() because exec\n- // requires the capability to be set explicitly, while 'docker\n- // run' sets it by default.\n- e.Capabilities, err = specutils.Capabilities(true /* enableRaw */, c.Spec.Process.Capabilities)\n+ e.Capabilities, err = specutils.Capabilities(conf.EnableRaw, c.Spec.Process.Capabilities)\nif err != nil {\nFatalf(\"creating capabilities: %v\", err)\n}\n+ log.Infof(\"Using exec capabilities from container: %+v\", e.Capabilities)\n}\n// containerd expects an actual process to represent the container being\n@@ -283,14 +283,14 @@ func (ex *Exec) execChildAndWait(waitStatus *syscall.WaitStatus) subcommands.Exi\n// parseArgs parses exec information from the command line or a JSON file\n// depending on whether the --process flag was used. Returns an ExecArgs and\n// the ID of the container to be used.\n-func (ex *Exec) parseArgs(f *flag.FlagSet) (*control.ExecArgs, string, error) {\n+func (ex *Exec) parseArgs(f *flag.FlagSet, enableRaw bool) (*control.ExecArgs, string, error) {\nif ex.processPath == \"\" {\n// Requires at least a container ID and command.\nif f.NArg() < 2 {\nf.Usage()\nreturn nil, \"\", fmt.Errorf(\"both a container-id and command are required\")\n}\n- e, err := ex.argsFromCLI(f.Args()[1:])\n+ e, err := ex.argsFromCLI(f.Args()[1:], enableRaw)\nreturn e, f.Arg(0), err\n}\n// Requires only the container ID.\n@@ -298,11 +298,11 @@ func (ex *Exec) parseArgs(f *flag.FlagSet) (*control.ExecArgs, string, error) {\nf.Usage()\nreturn nil, \"\", fmt.Errorf(\"a container-id is required\")\n}\n- e, err := ex.argsFromProcessFile()\n+ e, err := ex.argsFromProcessFile(enableRaw)\nreturn e, f.Arg(0), err\n}\n-func (ex *Exec) argsFromCLI(argv []string) (*control.ExecArgs, error) {\n+func (ex *Exec) argsFromCLI(argv []string, enableRaw bool) (*control.ExecArgs, error) {\nextraKGIDs := make([]auth.KGID, 0, len(ex.extraKGIDs))\nfor _, s := range ex.extraKGIDs {\nkgid, err := strconv.Atoi(s)\n@@ -315,7 +315,7 @@ func (ex *Exec) argsFromCLI(argv []string) (*control.ExecArgs, error) {\nvar caps *auth.TaskCapabilities\nif len(ex.caps) > 0 {\nvar err error\n- caps, err = capabilities(ex.caps)\n+ caps, err = capabilities(ex.caps, enableRaw)\nif err != nil {\nreturn nil, fmt.Errorf(\"capabilities error: %v\", err)\n}\n@@ -333,7 +333,7 @@ func (ex *Exec) argsFromCLI(argv []string) (*control.ExecArgs, error) {\n}, nil\n}\n-func (ex *Exec) argsFromProcessFile() (*control.ExecArgs, error) {\n+func (ex *Exec) argsFromProcessFile(enableRaw bool) (*control.ExecArgs, error) {\nf, err := os.Open(ex.processPath)\nif err != nil {\nreturn nil, fmt.Errorf(\"error opening process file: %s, %v\", ex.processPath, err)\n@@ -343,21 +343,21 @@ func (ex *Exec) argsFromProcessFile() (*control.ExecArgs, error) {\nif err := json.NewDecoder(f).Decode(&p); err != nil {\nreturn nil, fmt.Errorf(\"error parsing process file: %s, %v\", ex.processPath, err)\n}\n- return argsFromProcess(&p)\n+ return argsFromProcess(&p, enableRaw)\n}\n// argsFromProcess performs all the non-IO conversion from the Process struct\n// to ExecArgs.\n-func argsFromProcess(p *specs.Process) (*control.ExecArgs, error) {\n+func argsFromProcess(p *specs.Process, enableRaw bool) (*control.ExecArgs, error) {\n// Create capabilities.\nvar caps *auth.TaskCapabilities\nif p.Capabilities != nil {\nvar err error\n- // enableRaw is set to true to prevent the filtering out of\n- // CAP_NET_RAW. This is the opposite of Create() because exec\n- // requires the capability to be set explicitly, while 'docker\n- // run' sets it by default.\n- caps, err = specutils.Capabilities(true /* enableRaw */, p.Capabilities)\n+ // Starting from Docker 19, capabilities are explicitly set for exec (instead\n+ // of nil like before). So we can't distinguish 'exec' from\n+ // 'exec --privileged', as both specify CAP_NET_RAW. Therefore, filter\n+ // CAP_NET_RAW in the same way as container start.\n+ caps, err = specutils.Capabilities(enableRaw, p.Capabilities)\nif err != nil {\nreturn nil, fmt.Errorf(\"error creating capabilities: %v\", err)\n}\n@@ -410,7 +410,7 @@ func resolveEnvs(envs ...[]string) ([]string, error) {\n// capabilities takes a list of capabilities as strings and returns an\n// auth.TaskCapabilities struct with those capabilities in every capability set.\n// This mimics runc's behavior.\n-func capabilities(cs []string) (*auth.TaskCapabilities, error) {\n+func capabilities(cs []string, enableRaw bool) (*auth.TaskCapabilities, error) {\nvar specCaps specs.LinuxCapabilities\nfor _, cap := range cs {\nspecCaps.Ambient = append(specCaps.Ambient, cap)\n@@ -419,11 +419,11 @@ func capabilities(cs []string) (*auth.TaskCapabilities, error) {\nspecCaps.Inheritable = append(specCaps.Inheritable, cap)\nspecCaps.Permitted = append(specCaps.Permitted, cap)\n}\n- // enableRaw is set to true to prevent the filtering out of\n- // CAP_NET_RAW. This is the opposite of Create() because exec requires\n- // the capability to be set explicitly, while 'docker run' sets it by\n- // default.\n- return specutils.Capabilities(true /* enableRaw */, &specCaps)\n+ // Starting from Docker 19, capabilities are explicitly set for exec (instead\n+ // of nil like before). So we can't distinguish 'exec' from\n+ // 'exec --privileged', as both specify CAP_NET_RAW. Therefore, filter\n+ // CAP_NET_RAW in the same way as container start.\n+ return specutils.Capabilities(enableRaw, &specCaps)\n}\n// stringSlice allows a flag to be used multiple times, where each occurrence\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/cmd/exec_test.go",
"new_path": "runsc/cmd/exec_test.go",
"diff": "@@ -91,7 +91,7 @@ func TestCLIArgs(t *testing.T) {\n}\nfor _, tc := range testCases {\n- e, err := tc.ex.argsFromCLI(tc.argv)\n+ e, err := tc.ex.argsFromCLI(tc.argv, true)\nif err != nil {\nt.Errorf(\"argsFromCLI(%+v): got error: %+v\", tc.ex, err)\n} else if !cmp.Equal(*e, tc.expected, cmpopts.IgnoreUnexported(os.File{})) {\n@@ -144,7 +144,7 @@ func TestJSONArgs(t *testing.T) {\n}\nfor _, tc := range testCases {\n- e, err := argsFromProcess(&tc.p)\n+ e, err := argsFromProcess(&tc.p, true)\nif err != nil {\nt.Errorf(\"argsFromProcess(%+v): got error: %+v\", tc.p, err)\n} else if !cmp.Equal(*e, tc.expected, cmpopts.IgnoreUnexported(os.File{})) {\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/BUILD",
"new_path": "runsc/container/BUILD",
"diff": "@@ -47,6 +47,7 @@ go_test(\n],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/bits\",\n\"//pkg/log\",\n\"//pkg/sentry/control\",\n\"//pkg/sentry/kernel\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/container_test.go",
"new_path": "runsc/container/container_test.go",
"diff": "@@ -34,6 +34,7 @@ import (\n\"github.com/cenkalti/backoff\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/bits\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/control\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n@@ -2049,6 +2050,30 @@ func TestMountSymlink(t *testing.T) {\n}\n}\n+// Check that --net-raw disables the CAP_NET_RAW capability.\n+func TestNetRaw(t *testing.T) {\n+ capNetRaw := strconv.FormatUint(bits.MaskOf64(int(linux.CAP_NET_RAW)), 10)\n+ app, err := testutil.FindFile(\"runsc/container/test_app/test_app\")\n+ if err != nil {\n+ t.Fatal(\"error finding test_app:\", err)\n+ }\n+\n+ for _, enableRaw := range []bool{true, false} {\n+ conf := testutil.TestConfig()\n+ conf.EnableRaw = enableRaw\n+\n+ test := \"--enabled\"\n+ if !enableRaw {\n+ test = \"--disabled\"\n+ }\n+\n+ spec := testutil.NewSpecWithArgs(app, \"capability\", test, capNetRaw)\n+ if err := run(spec, conf); err != nil {\n+ t.Fatalf(\"Error running container: %v\", err)\n+ }\n+ }\n+}\n+\n// executeSync synchronously executes a new process.\nfunc (cont *Container) executeSync(args *control.ExecArgs) (syscall.WaitStatus, error) {\npid, err := cont.Execute(args)\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/container/test_app/test_app.go",
"new_path": "runsc/container/test_app/test_app.go",
"diff": "@@ -19,10 +19,12 @@ package main\nimport (\n\"context\"\n\"fmt\"\n+ \"io/ioutil\"\n\"log\"\n\"net\"\n\"os\"\n\"os/exec\"\n+ \"regexp\"\n\"strconv\"\nsys \"syscall\"\n\"time\"\n@@ -35,6 +37,7 @@ import (\nfunc main() {\nsubcommands.Register(subcommands.HelpCommand(), \"\")\nsubcommands.Register(subcommands.FlagsCommand(), \"\")\n+ subcommands.Register(new(capability), \"\")\nsubcommands.Register(new(fdReceiver), \"\")\nsubcommands.Register(new(fdSender), \"\")\nsubcommands.Register(new(forkBomb), \"\")\n@@ -287,3 +290,65 @@ func (s *syscall) Execute(ctx context.Context, f *flag.FlagSet, args ...interfac\n}\nreturn subcommands.ExitSuccess\n}\n+\n+type capability struct {\n+ enabled uint64\n+ disabled uint64\n+}\n+\n+// Name implements subcommands.Command.\n+func (*capability) Name() string {\n+ return \"capability\"\n+}\n+\n+// Synopsis implements subcommands.Command.\n+func (*capability) Synopsis() string {\n+ return \"checks if effective capabilities are set/unset\"\n+}\n+\n+// Usage implements subcommands.Command.\n+func (*capability) Usage() string {\n+ return \"capability [--enabled=number] [--disabled=number]\"\n+}\n+\n+// SetFlags implements subcommands.Command.\n+func (c *capability) SetFlags(f *flag.FlagSet) {\n+ f.Uint64Var(&c.enabled, \"enabled\", 0, \"\")\n+ f.Uint64Var(&c.disabled, \"disabled\", 0, \"\")\n+}\n+\n+// Execute implements subcommands.Command.\n+func (c *capability) Execute(ctx context.Context, f *flag.FlagSet, args ...interface{}) subcommands.ExitStatus {\n+ if c.enabled == 0 && c.disabled == 0 {\n+ fmt.Println(\"One of the flags must be set\")\n+ return subcommands.ExitUsageError\n+ }\n+\n+ status, err := ioutil.ReadFile(\"/proc/self/status\")\n+ if err != nil {\n+ fmt.Printf(\"Error reading %q: %v\\n\", \"proc/self/status\", err)\n+ return subcommands.ExitFailure\n+ }\n+ re := regexp.MustCompile(\"CapEff:\\t([0-9a-f]+)\\n\")\n+ matches := re.FindStringSubmatch(string(status))\n+ if matches == nil || len(matches) != 2 {\n+ fmt.Printf(\"Effective capabilities not found in\\n%s\\n\", status)\n+ return subcommands.ExitFailure\n+ }\n+ caps, err := strconv.ParseUint(matches[1], 16, 64)\n+ if err != nil {\n+ fmt.Printf(\"failed to convert capabilities %q: %v\\n\", matches[1], err)\n+ return subcommands.ExitFailure\n+ }\n+\n+ if c.enabled != 0 && (caps&c.enabled) != c.enabled {\n+ fmt.Printf(\"Missing capabilities, want: %#x: got: %#x\\n\", c.enabled, caps)\n+ return subcommands.ExitFailure\n+ }\n+ if c.disabled != 0 && (caps&c.disabled) != 0 {\n+ fmt.Printf(\"Extra capabilities found, dont_want: %#x: got: %#x\\n\", c.disabled, caps)\n+ return subcommands.ExitFailure\n+ }\n+\n+ return subcommands.ExitSuccess\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/dockerutil/dockerutil.go",
"new_path": "runsc/dockerutil/dockerutil.go",
"diff": "@@ -282,7 +282,14 @@ func (d *Docker) Logs() (string, error) {\n// Exec calls 'docker exec' with the arguments provided.\nfunc (d *Docker) Exec(args ...string) (string, error) {\n- a := []string{\"exec\", d.Name}\n+ return d.ExecWithFlags(nil, args...)\n+}\n+\n+// ExecWithFlags calls 'docker exec <flags> name <args>'.\n+func (d *Docker) ExecWithFlags(flags []string, args ...string) (string, error) {\n+ a := []string{\"exec\"}\n+ a = append(a, flags...)\n+ a = append(a, d.Name)\na = append(a, args...)\nreturn do(a...)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/BUILD",
"new_path": "runsc/specutils/BUILD",
"diff": "@@ -13,6 +13,7 @@ go_library(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/bits\",\n\"//pkg/log\",\n\"//pkg/sentry/kernel/auth\",\n\"@com_github_cenkalti_backoff//:go_default_library\",\n"
},
{
"change_type": "MODIFY",
"old_path": "runsc/specutils/specutils.go",
"new_path": "runsc/specutils/specutils.go",
"diff": "@@ -31,6 +31,7 @@ import (\n\"github.com/cenkalti/backoff\"\nspecs \"github.com/opencontainers/runtime-spec/specs-go\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/bits\"\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n)\n@@ -241,6 +242,15 @@ func AllCapabilities() *specs.LinuxCapabilities {\n}\n}\n+// AllCapabilitiesUint64 returns a bitmask containing all capabilities set.\n+func AllCapabilitiesUint64() uint64 {\n+ var rv uint64\n+ for _, cap := range capFromName {\n+ rv |= bits.MaskOf64(int(cap))\n+ }\n+ return rv\n+}\n+\nvar capFromName = map[string]linux.Capability{\n\"CAP_CHOWN\": linux.CAP_CHOWN,\n\"CAP_DAC_OVERRIDE\": linux.CAP_DAC_OVERRIDE,\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/BUILD",
"new_path": "test/e2e/BUILD",
"diff": "@@ -19,7 +19,9 @@ go_test(\nvisibility = [\"//:sandbox\"],\ndeps = [\n\"//pkg/abi/linux\",\n+ \"//pkg/bits\",\n\"//runsc/dockerutil\",\n+ \"//runsc/specutils\",\n\"//runsc/testutil\",\n],\n)\n"
},
{
"change_type": "MODIFY",
"old_path": "test/e2e/exec_test.go",
"new_path": "test/e2e/exec_test.go",
"diff": "@@ -30,14 +30,17 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/bits\"\n\"gvisor.dev/gvisor/runsc/dockerutil\"\n+ \"gvisor.dev/gvisor/runsc/specutils\"\n)\n+// Test that exec uses the exact same capability set as the container.\nfunc TestExecCapabilities(t *testing.T) {\nif err := dockerutil.Pull(\"alpine\"); err != nil {\nt.Fatalf(\"docker pull failed: %v\", err)\n}\n- d := dockerutil.MakeDocker(\"exec-test\")\n+ d := dockerutil.MakeDocker(\"exec-capabilities-test\")\n// Start the container.\nif err := d.Run(\"alpine\", \"sh\", \"-c\", \"cat /proc/self/status; sleep 100\"); err != nil {\n@@ -52,27 +55,59 @@ func TestExecCapabilities(t *testing.T) {\nif len(matches) != 2 {\nt.Fatalf(\"There should be a match for the whole line and the capability bitmask\")\n}\n- capString := matches[1]\n- t.Log(\"Root capabilities:\", capString)\n+ want := fmt.Sprintf(\"CapEff:\\t%s\\n\", matches[1])\n+ t.Log(\"Root capabilities:\", want)\n- // CAP_NET_RAW was in the capability set for the container, but was\n- // removed. However, `exec` does not remove it. Verify that it's not\n- // set in the container, then re-add it for comparison.\n- caps, err := strconv.ParseUint(capString, 16, 64)\n+ // Now check that exec'd process capabilities match the root.\n+ got, err := d.Exec(\"grep\", \"CapEff:\", \"/proc/self/status\")\nif err != nil {\n- t.Fatalf(\"failed to convert capabilities %q: %v\", capString, err)\n+ t.Fatalf(\"docker exec failed: %v\", err)\n+ }\n+ t.Logf(\"CapEff: %v\", got)\n+ if got != want {\n+ t.Errorf(\"wrong capabilities, got: %q, want: %q\", got, want)\n}\n- if caps&(1<<uint64(linux.CAP_NET_RAW)) != 0 {\n- t.Fatalf(\"CAP_NET_RAW should be filtered, but is set in the container: %x\", caps)\n}\n- caps |= 1 << uint64(linux.CAP_NET_RAW)\n- want := fmt.Sprintf(\"CapEff:\\t%016x\\n\", caps)\n- // Now check that exec'd process capabilities match the root.\n- got, err := d.Exec(\"grep\", \"CapEff:\", \"/proc/self/status\")\n+// Test that 'exec --privileged' adds all capabilities, except for CAP_NET_RAW\n+// which is removed from the container when --net-raw=false.\n+func TestExecPrivileged(t *testing.T) {\n+ if err := dockerutil.Pull(\"alpine\"); err != nil {\n+ t.Fatalf(\"docker pull failed: %v\", err)\n+ }\n+ d := dockerutil.MakeDocker(\"exec-privileged-test\")\n+\n+ // Start the container with all capabilities dropped.\n+ if err := d.Run(\"--cap-drop=all\", \"alpine\", \"sh\", \"-c\", \"cat /proc/self/status; sleep 100\"); err != nil {\n+ t.Fatalf(\"docker run failed: %v\", err)\n+ }\n+ defer d.CleanUp()\n+\n+ // Check that all capabilities where dropped from container.\n+ matches, err := d.WaitForOutputSubmatch(\"CapEff:\\t([0-9a-f]+)\\n\", 5*time.Second)\n+ if err != nil {\n+ t.Fatalf(\"WaitForOutputSubmatch() timeout: %v\", err)\n+ }\n+ if len(matches) != 2 {\n+ t.Fatalf(\"There should be a match for the whole line and the capability bitmask\")\n+ }\n+ containerCaps, err := strconv.ParseUint(matches[1], 16, 64)\n+ if err != nil {\n+ t.Fatalf(\"failed to convert capabilities %q: %v\", matches[1], err)\n+ }\n+ t.Logf(\"Container capabilities: %#x\", containerCaps)\n+ if containerCaps != 0 {\n+ t.Fatalf(\"Container should have no capabilities: %x\", containerCaps)\n+ }\n+\n+ // Check that 'exec --privileged' adds all capabilities, except\n+ // for CAP_NET_RAW.\n+ got, err := d.ExecWithFlags([]string{\"--privileged\"}, \"grep\", \"CapEff:\", \"/proc/self/status\")\nif err != nil {\nt.Fatalf(\"docker exec failed: %v\", err)\n}\n+ t.Logf(\"Exec CapEff: %v\", got)\n+ want := fmt.Sprintf(\"CapEff:\\t%016x\\n\", specutils.AllCapabilitiesUint64()&^bits.MaskOf64(int(linux.CAP_NET_RAW)))\nif got != want {\nt.Errorf(\"wrong capabilities, got: %q, want: %q\", got, want)\n}\n@@ -184,7 +219,7 @@ func TestExecEnvHasHome(t *testing.T) {\nif err := dockerutil.Pull(\"alpine\"); err != nil {\nt.Fatalf(\"docker pull failed: %v\", err)\n}\n- d := dockerutil.MakeDocker(\"exec-env-test\")\n+ d := dockerutil.MakeDocker(\"exec-env-home-test\")\n// We will check that HOME is set for root user, and also for a new\n// non-root user we will create.\n"
}
] | Go | Apache License 2.0 | google/gvisor | Prevent CAP_NET_RAW from appearing in exec
'docker exec' was getting CAP_NET_RAW even when --net-raw=false
because it was not filtered out from when copying container's
capabilities.
PiperOrigin-RevId: 272260451 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.