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,885
20.12.2019 16:43:34
28,800
21a14e9532365fc5eb51a5796ab66cf7f007ede3
Add vfs.Dentry.Children().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/dentry.go", "new_path": "pkg/sentry/vfs/dentry.go", "diff": "@@ -85,12 +85,12 @@ type Dentry struct {\n// mounts is accessed using atomic memory operations.\nmounts uint32\n- // mu synchronizes disowning and mounting over this Dentry.\n- mu sync.Mutex\n-\n// children are child Dentries.\nchildren map[string]*Dentry\n+ // mu synchronizes disowning and mounting over this Dentry.\n+ mu sync.Mutex\n+\n// impl is the DentryImpl associated with this Dentry. impl is immutable.\n// This should be the last field in Dentry.\nimpl DentryImpl\n@@ -199,6 +199,18 @@ func (d *Dentry) HasChildren() bool {\nreturn len(d.children) != 0\n}\n+// Children returns a map containing all of d's children.\n+func (d *Dentry) Children() map[string]*Dentry {\n+ if !d.HasChildren() {\n+ return nil\n+ }\n+ m := make(map[string]*Dentry)\n+ for name, child := range d.children {\n+ m[name] = child\n+ }\n+ return m\n+}\n+\n// InsertChild makes child a child of d with the given name.\n//\n// InsertChild is a mutator of d and child.\n" } ]
Go
Apache License 2.0
google/gvisor
Add vfs.Dentry.Children(). PiperOrigin-RevId: 286660774
259,885
20.12.2019 17:40:18
28,800
818eb22b11d6e0c056af6d4605e8cd246e622231
Add vfs.ResolvingPath.HandleJump().
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/resolving_path.go", "new_path": "pkg/sentry/vfs/resolving_path.go", "diff": "@@ -85,11 +85,11 @@ func init() {\n// so error \"constants\" are really mutable vars, necessitating somewhat\n// expensive interface object comparisons.\n-type resolveMountRootError struct{}\n+type resolveMountRootOrJumpError struct{}\n// Error implements error.Error.\n-func (resolveMountRootError) Error() string {\n- return \"resolving mount root\"\n+func (resolveMountRootOrJumpError) Error() string {\n+ return \"resolving mount root or jump\"\n}\ntype resolveMountPointError struct{}\n@@ -274,7 +274,7 @@ func (rp *ResolvingPath) ResolveParent(d *Dentry) (*Dentry, error) {\n// ... of non-root mount.\nrp.nextMount = vd.mount\nrp.nextStart = vd.dentry\n- return nil, resolveMountRootError{}\n+ return nil, resolveMountRootOrJumpError{}\n}\n// ... of root mount.\nparent = d\n@@ -385,11 +385,32 @@ func (rp *ResolvingPath) relpathPrepend(path fspath.Path) {\n}\n}\n+// HandleJump is called when the current path component is a \"magic\" link to\n+// the given VirtualDentry, like /proc/[pid]/fd/[fd]. If the calling Filesystem\n+// method should continue path traversal, HandleMagicSymlink updates the path\n+// component stream to reflect the magic link target and returns nil. Otherwise\n+// it returns a non-nil error.\n+//\n+// Preconditions: !rp.Done().\n+func (rp *ResolvingPath) HandleJump(target VirtualDentry) error {\n+ if rp.symlinks >= linux.MaxSymlinkTraversals {\n+ return syserror.ELOOP\n+ }\n+ rp.symlinks++\n+ // Consume the path component that represented the magic link.\n+ rp.Advance()\n+ // Unconditionally return a resolveMountRootOrJumpError, even if the Mount\n+ // isn't changing, to force restarting at the new Dentry.\n+ target.IncRef()\n+ rp.nextMount = target.mount\n+ rp.nextStart = target.dentry\n+ return resolveMountRootOrJumpError{}\n+}\n+\nfunc (rp *ResolvingPath) handleError(err error) bool {\nswitch err.(type) {\n- case resolveMountRootError:\n- // Switch to the new Mount. We hold references on the Mount and Dentry\n- // (from VFS.getMountpointAt()).\n+ case resolveMountRootOrJumpError:\n+ // Switch to the new Mount. We hold references on the Mount and Dentry.\nrp.decRefStartAndMount()\nrp.mount = rp.nextMount\nrp.start = rp.nextStart\n@@ -407,9 +428,8 @@ func (rp *ResolvingPath) handleError(err error) bool {\nreturn true\ncase resolveMountPointError:\n- // Switch to the new Mount. We hold a reference on the Mount (from\n- // VFS.getMountAt()), but borrow the reference on the mount root from\n- // the Mount.\n+ // Switch to the new Mount. We hold a reference on the Mount, but\n+ // borrow the reference on the mount root from the Mount.\nrp.decRefStartAndMount()\nrp.mount = rp.nextMount\nrp.start = rp.nextMount.root\n" } ]
Go
Apache License 2.0
google/gvisor
Add vfs.ResolvingPath.HandleJump(). PiperOrigin-RevId: 286666533
259,975
23.12.2019 11:48:03
28,800
e548ce18051398fb3fe379326080411f59fda379
Add python3-pip as dependency for Kokoro VM images. bm-tools requires python3 and pip3 in order to run tests. Add pip3 so that dependencies correctly install for Kokoro runs with bazel.
[ { "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 qemu-kvm python-pip zip\n+apt-get update && apt-get install -y rsync coreutils python-psutil qemu-kvm python-pip python3-pip zip\n# junitparser is used to merge junit xml files.\npip install junitparser\n" } ]
Go
Apache License 2.0
google/gvisor
Add python3-pip as dependency for Kokoro VM images. bm-tools requires python3 and pip3 in order to run tests. Add pip3 so that dependencies correctly install for Kokoro runs with bazel. PiperOrigin-RevId: 286923840
259,992
23.12.2019 17:31:20
28,800
574e988f2bc6060078a17f37a377441703c52a22
Fix deadlock in kernfs.Filesystem.revalidateChildLocked It was calling Dentry.InsertChild with the dentry's mutex already locked. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/kernfs/filesystem.go", "diff": "@@ -122,7 +122,7 @@ func (fs *Filesystem) revalidateChildLocked(ctx context.Context, vfsObj *vfs.Vir\nreturn nil, err\n}\n// Reference on childVFSD dropped by a corresponding Valid.\n- parent.InsertChild(name, childVFSD)\n+ parent.insertChildLocked(name, childVFSD)\n}\nreturn childVFSD.Impl().(*Dentry), nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs.go", "diff": "@@ -239,14 +239,22 @@ func (d *Dentry) destroy() {\n//\n// Precondition: d must represent a directory inode.\nfunc (d *Dentry) InsertChild(name string, child *vfs.Dentry) {\n+ d.dirMu.Lock()\n+ d.insertChildLocked(name, child)\n+ d.dirMu.Unlock()\n+}\n+\n+// insertChildLocked is equivalent to InsertChild, with additional\n+// preconditions.\n+//\n+// Precondition: d.dirMu must be locked.\n+func (d *Dentry) insertChildLocked(name string, child *vfs.Dentry) {\nif !d.isDir() {\npanic(fmt.Sprintf(\"InsertChild called on non-directory Dentry: %+v.\", d))\n}\nvfsDentry := d.VFSDentry()\nvfsDentry.IncRef() // DecRef in child's Dentry.destroy.\n- d.dirMu.Lock()\nvfsDentry.InsertChild(child, name)\n- d.dirMu.Unlock()\n}\n// The Inode interface maps filesystem-level operations that operate on paths to\n" } ]
Go
Apache License 2.0
google/gvisor
Fix deadlock in kernfs.Filesystem.revalidateChildLocked It was calling Dentry.InsertChild with the dentry's mutex already locked. Updates #1035 PiperOrigin-RevId: 286962742
259,885
27.12.2019 00:12:14
28,800
796f53c0befc21570b185811e26b74e71950dfc3
Add VFS2 support for /proc/filesystems. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/benchmark/benchmark_test.go", "new_path": "pkg/sentry/fsimpl/ext/benchmark/benchmark_test.go", "diff": "@@ -50,7 +50,9 @@ func setUp(b *testing.B, imagePath string) (context.Context, *vfs.VirtualFilesys\n// Create VFS.\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"extfs\", ext.FilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"extfs\", ext.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, imagePath, \"extfs\", &vfs.GetFilesystemOptions{InternalData: int(f.Fd())})\nif err != nil {\nf.Close()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/ext_test.go", "new_path": "pkg/sentry/fsimpl/ext/ext_test.go", "diff": "@@ -66,7 +66,9 @@ func setUp(t *testing.T, imagePath string) (context.Context, *vfs.VirtualFilesys\n// Create VFS.\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"extfs\", FilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"extfs\", FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, localImagePath, \"extfs\", &vfs.GetFilesystemOptions{InternalData: int(f.Fd())})\nif err != nil {\nf.Close()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "diff": "@@ -59,7 +59,9 @@ func newTestSystem(t *testing.T, rootFn RootDentryFn) *TestSystem {\nctx := contexttest.Context(t)\ncreds := auth.CredentialsFromContext(ctx)\nv := vfs.New()\n- v.MustRegisterFilesystemType(\"testfs\", &fsType{rootFn: rootFn})\n+ v.MustRegisterFilesystemType(\"testfs\", &fsType{rootFn: rootFn}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmns, err := v.NewMountNamespace(ctx, creds, \"\", \"testfs\", &vfs.GetFilesystemOptions{})\nif err != nil {\nt.Fatalf(\"Failed to create testfs root mount: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/memfs/benchmark_test.go", "new_path": "pkg/sentry/fsimpl/memfs/benchmark_test.go", "diff": "@@ -176,7 +176,9 @@ func BenchmarkVFS2MemfsStat(b *testing.B) {\n// Create VFS.\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"memfs\", memfs.FilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"memfs\", memfs.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"memfs\", &vfs.GetFilesystemOptions{})\nif err != nil {\nb.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n@@ -365,7 +367,9 @@ func BenchmarkVFS2MemfsMountStat(b *testing.B) {\n// Create VFS.\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"memfs\", memfs.FilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"memfs\", memfs.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"memfs\", &vfs.GetFilesystemOptions{})\nif err != nil {\nb.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/memfs/pipe_test.go", "new_path": "pkg/sentry/fsimpl/memfs/pipe_test.go", "diff": "@@ -152,7 +152,9 @@ func setup(t *testing.T) (context.Context, *auth.Credentials, *vfs.VirtualFilesy\n// Create VFS.\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"memfs\", FilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"memfs\", FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"memfs\", &vfs.GetFilesystemOptions{})\nif err != nil {\nt.Fatalf(\"failed to create tmpfs root mount: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -56,25 +56,25 @@ func checkDots(dirs []vfs.Dirent) ([]vfs.Dirent, error) {\nfunc checkTasksStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\nwants := map[string]vfs.Dirent{\n- \"loadavg\": vfs.Dirent{Type: linux.DT_REG},\n- \"meminfo\": vfs.Dirent{Type: linux.DT_REG},\n- \"mounts\": vfs.Dirent{Type: linux.DT_LNK},\n- \"self\": vfs.Dirent{Type: linux.DT_LNK},\n- \"stat\": vfs.Dirent{Type: linux.DT_REG},\n- \"thread-self\": vfs.Dirent{Type: linux.DT_LNK},\n- \"version\": vfs.Dirent{Type: linux.DT_REG},\n+ \"loadavg\": {Type: linux.DT_REG},\n+ \"meminfo\": {Type: linux.DT_REG},\n+ \"mounts\": {Type: linux.DT_LNK},\n+ \"self\": {Type: linux.DT_LNK},\n+ \"stat\": {Type: linux.DT_REG},\n+ \"thread-self\": {Type: linux.DT_LNK},\n+ \"version\": {Type: linux.DT_REG},\n}\nreturn checkFiles(gots, wants)\n}\nfunc checkTaskStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\nwants := map[string]vfs.Dirent{\n- \"io\": vfs.Dirent{Type: linux.DT_REG},\n- \"maps\": vfs.Dirent{Type: linux.DT_REG},\n- \"smaps\": vfs.Dirent{Type: linux.DT_REG},\n- \"stat\": vfs.Dirent{Type: linux.DT_REG},\n- \"statm\": vfs.Dirent{Type: linux.DT_REG},\n- \"status\": vfs.Dirent{Type: linux.DT_REG},\n+ \"io\": {Type: linux.DT_REG},\n+ \"maps\": {Type: linux.DT_REG},\n+ \"smaps\": {Type: linux.DT_REG},\n+ \"stat\": {Type: linux.DT_REG},\n+ \"statm\": {Type: linux.DT_REG},\n+ \"status\": {Type: linux.DT_REG},\n}\nreturn checkFiles(gots, wants)\n}\n@@ -114,7 +114,9 @@ func setup() (context.Context, *vfs.VirtualFilesystem, vfs.VirtualDentry, error)\ncreds := auth.CredentialsFromContext(ctx)\nvfsObj := vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"procfs\", &procFSType{})\n+ vfsObj.MustRegisterFilesystemType(\"procfs\", &procFSType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"procfs\", &vfs.GetFilesystemOptions{})\nif err != nil {\nreturn nil, nil, vfs.VirtualDentry{}, fmt.Errorf(\"NewMountNamespace(): %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "new_path": "pkg/sentry/vfs/file_description_impl_util_test.go", "diff": "@@ -89,7 +89,7 @@ func TestGenCountFD(t *testing.T) {\ncreds := auth.CredentialsFromContext(ctx)\nvfsObj := New() // vfs.New()\n- vfsObj.MustRegisterFilesystemType(\"testfs\", FDTestFilesystemType{})\n+ vfsObj.MustRegisterFilesystemType(\"testfs\", FDTestFilesystemType{}, &RegisterFilesystemTypeOptions{})\nmntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"testfs\", &GetFilesystemOptions{})\nif err != nil {\nt.Fatalf(\"failed to create testfs root mount: %v\", err)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/filesystem_type.go", "new_path": "pkg/sentry/vfs/filesystem_type.go", "diff": "package vfs\nimport (\n+ \"bytes\"\n\"fmt\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n@@ -43,28 +44,70 @@ type GetFilesystemOptions struct {\nInternalData interface{}\n}\n+type registeredFilesystemType struct {\n+ fsType FilesystemType\n+ opts RegisterFilesystemTypeOptions\n+}\n+\n+// RegisterFilesystemTypeOptions contains options to\n+// VirtualFilesystem.RegisterFilesystem().\n+type RegisterFilesystemTypeOptions struct {\n+ // If AllowUserMount is true, allow calls to VirtualFilesystem.MountAt()\n+ // for which MountOptions.InternalMount == false to use this filesystem\n+ // type.\n+ AllowUserMount bool\n+\n+ // If AllowUserList is true, make this filesystem type visible in\n+ // /proc/filesystems.\n+ AllowUserList bool\n+\n+ // If RequiresDevice is true, indicate that mounting this filesystem\n+ // requires a block device as the mount source in /proc/filesystems.\n+ RequiresDevice bool\n+}\n+\n// RegisterFilesystemType registers the given FilesystemType in vfs with the\n// given name.\n-func (vfs *VirtualFilesystem) RegisterFilesystemType(name string, fsType FilesystemType) error {\n+func (vfs *VirtualFilesystem) RegisterFilesystemType(name string, fsType FilesystemType, opts *RegisterFilesystemTypeOptions) error {\nvfs.fsTypesMu.Lock()\ndefer vfs.fsTypesMu.Unlock()\nif existing, ok := vfs.fsTypes[name]; ok {\n- return fmt.Errorf(\"name %q is already registered to filesystem type %T\", name, existing)\n+ return fmt.Errorf(\"name %q is already registered to filesystem type %T\", name, existing.fsType)\n+ }\n+ vfs.fsTypes[name] = &registeredFilesystemType{\n+ fsType: fsType,\n+ opts: *opts,\n}\n- vfs.fsTypes[name] = fsType\nreturn nil\n}\n// MustRegisterFilesystemType is equivalent to RegisterFilesystemType but\n// panics on failure.\n-func (vfs *VirtualFilesystem) MustRegisterFilesystemType(name string, fsType FilesystemType) {\n- if err := vfs.RegisterFilesystemType(name, fsType); err != nil {\n+func (vfs *VirtualFilesystem) MustRegisterFilesystemType(name string, fsType FilesystemType, opts *RegisterFilesystemTypeOptions) {\n+ if err := vfs.RegisterFilesystemType(name, fsType, opts); err != nil {\npanic(fmt.Sprintf(\"failed to register filesystem type %T: %v\", fsType, err))\n}\n}\n-func (vfs *VirtualFilesystem) getFilesystemType(name string) FilesystemType {\n+func (vfs *VirtualFilesystem) getFilesystemType(name string) *registeredFilesystemType {\nvfs.fsTypesMu.RLock()\ndefer vfs.fsTypesMu.RUnlock()\nreturn vfs.fsTypes[name]\n}\n+\n+// GenerateProcFilesystems emits the contents of /proc/filesystems for vfs to\n+// buf.\n+func (vfs *VirtualFilesystem) GenerateProcFilesystems(buf *bytes.Buffer) {\n+ vfs.fsTypesMu.RLock()\n+ defer vfs.fsTypesMu.RUnlock()\n+ for name, rft := range vfs.fsTypes {\n+ if !rft.opts.AllowUserList {\n+ continue\n+ }\n+ var nodev string\n+ if !rft.opts.RequiresDevice {\n+ nodev = \"nodev\"\n+ }\n+ fmt.Fprintf(buf, \"%s\\t%s\\n\", nodev, name)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/mount.go", "new_path": "pkg/sentry/vfs/mount.go", "diff": "@@ -112,11 +112,11 @@ type MountNamespace struct {\n// configured by the given arguments. A reference is taken on the returned\n// MountNamespace.\nfunc (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth.Credentials, source, fsTypeName string, opts *GetFilesystemOptions) (*MountNamespace, error) {\n- fsType := vfs.getFilesystemType(fsTypeName)\n- if fsType == nil {\n+ rft := vfs.getFilesystemType(fsTypeName)\n+ if rft == nil {\nreturn nil, syserror.ENODEV\n}\n- fs, root, err := fsType.GetFilesystem(ctx, vfs, creds, source, *opts)\n+ fs, root, err := rft.fsType.GetFilesystem(ctx, vfs, creds, source, *opts)\nif err != nil {\nreturn nil, err\n}\n@@ -136,11 +136,14 @@ func (vfs *VirtualFilesystem) NewMountNamespace(ctx context.Context, creds *auth\n// MountAt creates and mounts a Filesystem configured by the given arguments.\nfunc (vfs *VirtualFilesystem) MountAt(ctx context.Context, creds *auth.Credentials, source string, target *PathOperation, fsTypeName string, opts *MountOptions) error {\n- fsType := vfs.getFilesystemType(fsTypeName)\n- if fsType == nil {\n+ rft := vfs.getFilesystemType(fsTypeName)\n+ if rft == nil {\nreturn syserror.ENODEV\n}\n- fs, root, err := fsType.GetFilesystem(ctx, vfs, creds, source, opts.GetFilesystemOptions)\n+ if !opts.InternalMount && !rft.opts.AllowUserMount {\n+ return syserror.ENODEV\n+ }\n+ fs, root, err := rft.fsType.GetFilesystem(ctx, vfs, creds, source, opts.GetFilesystemOptions)\nif err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/options.go", "new_path": "pkg/sentry/vfs/options.go", "diff": "@@ -50,6 +50,10 @@ type MknodOptions struct {\ntype MountOptions struct {\n// GetFilesystemOptions contains options to FilesystemType.GetFilesystem().\nGetFilesystemOptions GetFilesystemOptions\n+\n+ // If InternalMount is true, allow the use of filesystem types for which\n+ // RegisterFilesystemTypeOptions.AllowUserMount == false.\n+ InternalMount bool\n}\n// OpenOptions contains options to VirtualFilesystem.OpenAt() and\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -75,23 +75,23 @@ type VirtualFilesystem struct {\n// mountpoints is analogous to Linux's mountpoint_hashtable.\nmountpoints map[*Dentry]map[*Mount]struct{}\n+ // fsTypes contains all registered FilesystemTypes. fsTypes is protected by\n+ // fsTypesMu.\n+ fsTypesMu sync.RWMutex\n+ fsTypes map[string]*registeredFilesystemType\n+\n// filesystems contains all Filesystems. filesystems is protected by\n// filesystemsMu.\nfilesystemsMu sync.Mutex\nfilesystems map[*Filesystem]struct{}\n-\n- // fsTypes contains all FilesystemTypes that are usable in the\n- // VirtualFilesystem. fsTypes is protected by fsTypesMu.\n- fsTypesMu sync.RWMutex\n- fsTypes map[string]FilesystemType\n}\n// New returns a new VirtualFilesystem with no mounts or FilesystemTypes.\nfunc New() *VirtualFilesystem {\nvfs := &VirtualFilesystem{\nmountpoints: make(map[*Dentry]map[*Mount]struct{}),\n+ fsTypes: make(map[string]*registeredFilesystemType),\nfilesystems: make(map[*Filesystem]struct{}),\n- fsTypes: make(map[string]FilesystemType),\n}\nvfs.mounts.Init()\nreturn vfs\n" } ]
Go
Apache License 2.0
google/gvisor
Add VFS2 support for /proc/filesystems. Updates #1195 PiperOrigin-RevId: 287269106
259,885
30.12.2019 11:35:06
28,800
1f384ac42b9ee8b52000dc2bff79d975853519ed
Add VFS2 support for device special files. Add FileDescriptionOptions.UseDentryMetadata, which reduces the amount of boilerplate needed for device FDs and the like between filesystems. Switch back to having FileDescription.Init() take references on the Mount and Dentry; otherwise managing refcounts around failed calls to OpenDeviceSpecialFile() / Device.Open() is tricky.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/inode.go", "new_path": "pkg/sentry/fsimpl/ext/inode.go", "diff": "@@ -157,8 +157,6 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nswitch in.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- mnt.IncRef()\n- vfsd.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *directory:\n@@ -168,8 +166,6 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- mnt.IncRef()\n- vfsd.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *symlink:\n@@ -178,8 +174,6 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nreturn nil, syserror.ELOOP\n}\nvar fd symlinkFD\n- mnt.IncRef()\n- vfsd.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ndefault:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "new_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "diff": "@@ -81,8 +81,6 @@ type DynamicBytesFD struct {\n// Init initializes a DynamicBytesFD.\nfunc (fd *DynamicBytesFD) Init(m *vfs.Mount, d *vfs.Dentry, data vfs.DynamicBytesSource, flags uint32) {\n- m.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\n- d.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\nfd.inode = d.Impl().(*Dentry).inode\nfd.SetDataSource(data)\nfd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go", "diff": "@@ -44,8 +44,6 @@ type GenericDirectoryFD struct {\n// Init initializes a GenericDirectoryFD.\nfunc (fd *GenericDirectoryFD) Init(m *vfs.Mount, d *vfs.Dentry, children *OrderedChildren, flags uint32) {\n- m.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\n- d.IncRef() // DecRef in vfs.FileDescription.vd.DecRef on final ref.\nfd.children = children\nfd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/memfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/memfs/filesystem.go", "diff": "@@ -348,8 +348,6 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\n}\n// mnt.EndWrite() is called by regularFileFD.Release().\n}\n- mnt.IncRef()\n- d.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{})\nif flags&linux.O_TRUNC != 0 {\nimpl.mu.Lock()\n@@ -364,8 +362,6 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- mnt.IncRef()\n- d.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\ncase *symlink:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/memfs/named_pipe.go", "new_path": "pkg/sentry/fsimpl/memfs/named_pipe.go", "diff": "@@ -55,8 +55,6 @@ func newNamedPipeFD(ctx context.Context, np *namedPipe, rp *vfs.ResolvingPath, v\nreturn nil, err\n}\nmnt := rp.Mount()\n- mnt.IncRef()\n- vfsd.IncRef()\nfd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/BUILD", "new_path": "pkg/sentry/vfs/BUILD", "diff": "@@ -9,6 +9,7 @@ go_library(\n\"context.go\",\n\"debug.go\",\n\"dentry.go\",\n+ \"device.go\",\n\"file_description.go\",\n\"file_description_impl_util.go\",\n\"filesystem.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/vfs/device.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 vfs\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// DeviceKind indicates whether a device is a block or character device.\n+type DeviceKind uint32\n+\n+const (\n+ // BlockDevice indicates a block device.\n+ BlockDevice DeviceKind = iota\n+\n+ // CharDevice indicates a character device.\n+ CharDevice\n+)\n+\n+// String implements fmt.Stringer.String.\n+func (kind DeviceKind) String() string {\n+ switch kind {\n+ case BlockDevice:\n+ return \"block\"\n+ case CharDevice:\n+ return \"character\"\n+ default:\n+ return fmt.Sprintf(\"invalid device kind %d\", kind)\n+ }\n+}\n+\n+type devTuple struct {\n+ kind DeviceKind\n+ major uint32\n+ minor uint32\n+}\n+\n+// A Device backs device special files.\n+type Device interface {\n+ // Open returns a FileDescription representing this device.\n+ Open(ctx context.Context, mnt *Mount, d *Dentry, opts OpenOptions) (*FileDescription, error)\n+}\n+\n+type registeredDevice struct {\n+ dev Device\n+ opts RegisterDeviceOptions\n+}\n+\n+// RegisterDeviceOptions contains options to\n+// VirtualFilesystem.RegisterDevice().\n+type RegisterDeviceOptions struct {\n+ // GroupName is the name shown for this device registration in\n+ // /proc/devices. If GroupName is empty, this registration will not be\n+ // shown in /proc/devices.\n+ GroupName string\n+}\n+\n+// RegisterDevice registers the given Device in vfs with the given major and\n+// minor device numbers.\n+func (vfs *VirtualFilesystem) RegisterDevice(kind DeviceKind, major, minor uint32, dev Device, opts *RegisterDeviceOptions) error {\n+ tup := devTuple{kind, major, minor}\n+ vfs.devicesMu.Lock()\n+ defer vfs.devicesMu.Unlock()\n+ if existing, ok := vfs.devices[tup]; ok {\n+ return fmt.Errorf(\"%s device number (%d, %d) is already registered to device type %T\", kind, major, minor, existing.dev)\n+ }\n+ vfs.devices[tup] = &registeredDevice{\n+ dev: dev,\n+ opts: *opts,\n+ }\n+ return nil\n+}\n+\n+// OpenDeviceSpecialFile returns a FileDescription representing the given\n+// device.\n+func (vfs *VirtualFilesystem) OpenDeviceSpecialFile(ctx context.Context, mnt *Mount, d *Dentry, kind DeviceKind, major, minor uint32, opts *OpenOptions) (*FileDescription, error) {\n+ tup := devTuple{kind, major, minor}\n+ vfs.devicesMu.RLock()\n+ defer vfs.devicesMu.RUnlock()\n+ rd, ok := vfs.devices[tup]\n+ if !ok {\n+ return nil, syserror.ENXIO\n+ }\n+ return rd.dev.Open(ctx, mnt, d, *opts)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -61,11 +61,25 @@ type FileDescriptionOptions struct {\n// If AllowDirectIO is true, allow O_DIRECT to be set on the file. This is\n// usually only the case if O_DIRECT would actually have an effect.\nAllowDirectIO bool\n+\n+ // If UseDentryMetadata is true, calls to FileDescription methods that\n+ // interact with file and filesystem metadata (Stat, SetStat, StatFS,\n+ // Listxattr, Getxattr, Setxattr, Removexattr) are implemented by calling\n+ // the corresponding FilesystemImpl methods instead of the corresponding\n+ // FileDescriptionImpl methods.\n+ //\n+ // UseDentryMetadata is intended for file descriptions that are implemented\n+ // outside of individual filesystems, such as pipes, sockets, and device\n+ // special files. FileDescriptions for which UseDentryMetadata is true may\n+ // embed DentryMetadataFileDescriptionImpl to obtain appropriate\n+ // implementations of FileDescriptionImpl methods that should not be\n+ // called.\n+ UseDentryMetadata bool\n}\n-// Init must be called before first use of fd. It takes ownership of references\n-// on mnt and d held by the caller. statusFlags is the initial file description\n-// status flags, which is usually the full set of flags passed to open(2).\n+// Init must be called before first use of fd. It takes references on mnt and\n+// d. statusFlags is the initial file description status flags, which is\n+// usually the full set of flags passed to open(2).\nfunc (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) {\nfd.refs = 1\nfd.statusFlags = statusFlags | linux.O_LARGEFILE\n@@ -73,6 +87,7 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mn\nmount: mnt,\ndentry: d,\n}\n+ fd.vd.IncRef()\nfd.opts = *opts\nfd.impl = impl\n}\n@@ -140,7 +155,7 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\n// sense. However, the check as actually implemented seems to be \"O_APPEND\n// cannot be changed if the file is marked as append-only\".\nif (flags^oldFlags)&linux.O_APPEND != 0 {\n- stat, err := fd.impl.Stat(ctx, StatOptions{\n+ stat, err := fd.Stat(ctx, StatOptions{\n// There is no mask bit for stx_attributes.\nMask: 0,\n// Linux just reads inode::i_flags directly.\n@@ -154,7 +169,7 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\n}\n}\nif (flags&linux.O_NOATIME != 0) && (oldFlags&linux.O_NOATIME == 0) {\n- stat, err := fd.impl.Stat(ctx, StatOptions{\n+ stat, err := fd.Stat(ctx, StatOptions{\nMask: linux.STATX_UID,\n// Linux's inode_owner_or_capable() just reads inode::i_uid\n// directly.\n@@ -348,17 +363,47 @@ func (fd *FileDescription) OnClose(ctx context.Context) error {\n// Stat returns metadata for the file represented by fd.\nfunc (fd *FileDescription) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ stat, err := fd.vd.mount.fs.impl.StatAt(ctx, rp, opts)\n+ vfsObj.putResolvingPath(rp)\n+ return stat, err\n+ }\nreturn fd.impl.Stat(ctx, opts)\n}\n// SetStat updates metadata for the file represented by fd.\nfunc (fd *FileDescription) SetStat(ctx context.Context, opts SetStatOptions) error {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ err := fd.vd.mount.fs.impl.SetStatAt(ctx, rp, opts)\n+ vfsObj.putResolvingPath(rp)\n+ return err\n+ }\nreturn fd.impl.SetStat(ctx, opts)\n}\n// StatFS returns metadata for the filesystem containing the file represented\n// by fd.\nfunc (fd *FileDescription) StatFS(ctx context.Context) (linux.Statfs, error) {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ statfs, err := fd.vd.mount.fs.impl.StatFSAt(ctx, rp)\n+ vfsObj.putResolvingPath(rp)\n+ return statfs, err\n+ }\nreturn fd.impl.StatFS(ctx)\n}\n@@ -417,6 +462,16 @@ func (fd *FileDescription) Ioctl(ctx context.Context, uio usermem.IO, args arch.\n// Listxattr returns all extended attribute names for the file represented by\n// fd.\nfunc (fd *FileDescription) Listxattr(ctx context.Context) ([]string, error) {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ names, err := fd.vd.mount.fs.impl.ListxattrAt(ctx, rp)\n+ vfsObj.putResolvingPath(rp)\n+ return names, err\n+ }\nnames, err := fd.impl.Listxattr(ctx)\nif err == syserror.ENOTSUP {\n// Linux doesn't actually return ENOTSUP in this case; instead,\n@@ -431,18 +486,48 @@ func (fd *FileDescription) Listxattr(ctx context.Context) ([]string, error) {\n// Getxattr returns the value associated with the given extended attribute for\n// the file represented by fd.\nfunc (fd *FileDescription) Getxattr(ctx context.Context, name string) (string, error) {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ val, err := fd.vd.mount.fs.impl.GetxattrAt(ctx, rp, name)\n+ vfsObj.putResolvingPath(rp)\n+ return val, err\n+ }\nreturn fd.impl.Getxattr(ctx, name)\n}\n// Setxattr changes the value associated with the given extended attribute for\n// the file represented by fd.\nfunc (fd *FileDescription) Setxattr(ctx context.Context, opts SetxattrOptions) error {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ err := fd.vd.mount.fs.impl.SetxattrAt(ctx, rp, opts)\n+ vfsObj.putResolvingPath(rp)\n+ return err\n+ }\nreturn fd.impl.Setxattr(ctx, opts)\n}\n// Removexattr removes the given extended attribute from the file represented\n// by fd.\nfunc (fd *FileDescription) Removexattr(ctx context.Context, name string) error {\n+ if fd.opts.UseDentryMetadata {\n+ vfsObj := fd.vd.mount.vfs\n+ rp := vfsObj.getResolvingPath(auth.CredentialsFromContext(ctx), &PathOperation{\n+ Root: fd.vd,\n+ Start: fd.vd,\n+ })\n+ err := fd.vd.mount.fs.impl.RemovexattrAt(ctx, rp, name)\n+ vfsObj.putResolvingPath(rp)\n+ return err\n+ }\nreturn fd.impl.Removexattr(ctx, name)\n}\n@@ -464,7 +549,7 @@ func (fd *FileDescription) MappedName(ctx context.Context) string {\n// DeviceID implements memmap.MappingIdentity.DeviceID.\nfunc (fd *FileDescription) DeviceID() uint64 {\n- stat, err := fd.impl.Stat(context.Background(), StatOptions{\n+ stat, err := fd.Stat(context.Background(), StatOptions{\n// There is no STATX_DEV; we assume that Stat will return it if it's\n// available regardless of mask.\nMask: 0,\n@@ -480,7 +565,7 @@ func (fd *FileDescription) DeviceID() uint64 {\n// InodeID implements memmap.MappingIdentity.InodeID.\nfunc (fd *FileDescription) InodeID() uint64 {\n- stat, err := fd.impl.Stat(context.Background(), StatOptions{\n+ stat, err := fd.Stat(context.Background(), StatOptions{\nMask: linux.STATX_INO,\n// fs/proc/task_mmu.c:show_map_vma() just reads inode::i_ino directly.\nSync: linux.AT_STATX_DONT_SYNC,\n@@ -493,5 +578,5 @@ func (fd *FileDescription) InodeID() uint64 {\n// Msync implements memmap.MappingIdentity.Msync.\nfunc (fd *FileDescription) Msync(ctx context.Context, mr memmap.MappableRange) error {\n- return fd.impl.Sync(ctx)\n+ return fd.Sync(ctx)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description_impl_util.go", "new_path": "pkg/sentry/vfs/file_description_impl_util.go", "diff": "@@ -177,6 +177,21 @@ func (DirectoryFileDescriptionDefaultImpl) Write(ctx context.Context, src userme\nreturn 0, syserror.EISDIR\n}\n+// DentryMetadataFileDescriptionImpl may be embedded by implementations of\n+// FileDescriptionImpl for which FileDescriptionOptions.UseDentryMetadata is\n+// true to obtain implementations of Stat and SetStat that panic.\n+type DentryMetadataFileDescriptionImpl struct{}\n+\n+// Stat implements FileDescriptionImpl.Stat.\n+func (DentryMetadataFileDescriptionImpl) Stat(ctx context.Context, opts StatOptions) (linux.Statx, error) {\n+ panic(\"illegal call to DentryMetadataFileDescriptionImpl.Stat\")\n+}\n+\n+// SetStat implements FileDescriptionImpl.SetStat.\n+func (DentryMetadataFileDescriptionImpl) SetStat(ctx context.Context, opts SetStatOptions) error {\n+ panic(\"illegal call to DentryMetadataFileDescriptionImpl.SetStat\")\n+}\n+\n// DynamicBytesFileDescriptionImpl may be embedded by implementations of\n// FileDescriptionImpl that represent read-only regular files whose contents\n// are backed by a bytes.Buffer that is regenerated when necessary, consistent\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/filesystem.go", "new_path": "pkg/sentry/vfs/filesystem.go", "diff": "@@ -418,17 +418,38 @@ type FilesystemImpl interface {\nUnlinkAt(ctx context.Context, rp *ResolvingPath) error\n// ListxattrAt returns all extended attribute names for the file at rp.\n+ //\n+ // Errors:\n+ //\n+ // - If extended attributes are not supported by the filesystem,\n+ // ListxattrAt returns nil. (See FileDescription.Listxattr for an\n+ // explanation.)\nListxattrAt(ctx context.Context, rp *ResolvingPath) ([]string, error)\n// GetxattrAt returns the value associated with the given extended\n// attribute for the file at rp.\n+ //\n+ // Errors:\n+ //\n+ // - If extended attributes are not supported by the filesystem, GetxattrAt\n+ // returns ENOTSUP.\nGetxattrAt(ctx context.Context, rp *ResolvingPath, name string) (string, error)\n// SetxattrAt changes the value associated with the given extended\n// attribute for the file at rp.\n+ //\n+ // Errors:\n+ //\n+ // - If extended attributes are not supported by the filesystem, SetxattrAt\n+ // returns ENOTSUP.\nSetxattrAt(ctx context.Context, rp *ResolvingPath, opts SetxattrOptions) error\n// RemovexattrAt removes the given extended attribute from the file at rp.\n+ //\n+ // Errors:\n+ //\n+ // - If extended attributes are not supported by the filesystem,\n+ // RemovexattrAt returns ENOTSUP.\nRemovexattrAt(ctx context.Context, rp *ResolvingPath, name string) error\n// PrependPath prepends a path from vd to vd.Mount().Root() to b.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -75,6 +75,11 @@ type VirtualFilesystem struct {\n// mountpoints is analogous to Linux's mountpoint_hashtable.\nmountpoints map[*Dentry]map[*Mount]struct{}\n+ // devices contains all registered Devices. devices is protected by\n+ // devicesMu.\n+ devicesMu sync.RWMutex\n+ devices map[devTuple]*registeredDevice\n+\n// fsTypes contains all registered FilesystemTypes. fsTypes is protected by\n// fsTypesMu.\nfsTypesMu sync.RWMutex\n@@ -90,6 +95,7 @@ type VirtualFilesystem struct {\nfunc New() *VirtualFilesystem {\nvfs := &VirtualFilesystem{\nmountpoints: make(map[*Dentry]map[*Mount]struct{}),\n+ devices: make(map[devTuple]*registeredDevice),\nfsTypes: make(map[string]*registeredFilesystemType),\nfilesystems: make(map[*Filesystem]struct{}),\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add VFS2 support for device special files. - Add FileDescriptionOptions.UseDentryMetadata, which reduces the amount of boilerplate needed for device FDs and the like between filesystems. - Switch back to having FileDescription.Init() take references on the Mount and Dentry; otherwise managing refcounts around failed calls to OpenDeviceSpecialFile() / Device.Open() is tricky. PiperOrigin-RevId: 287575574
259,865
31.12.2019 16:49:30
-3,600
200cf245c4ed43d8e2a37484cdbc36f5fbfa1ac9
netstack: minor fix typo in "if err" handler
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/sample/tun_tcp_connect/main.go", "new_path": "pkg/tcpip/sample/tun_tcp_connect/main.go", "diff": "@@ -164,7 +164,7 @@ func main() {\n// Create TCP endpoint.\nvar wq waiter.Queue\nep, e := s.NewEndpoint(tcp.ProtocolNumber, ipv4.ProtocolNumber, &wq)\n- if err != nil {\n+ if e != nil {\nlog.Fatal(e)\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": "@@ -168,7 +168,7 @@ func main() {\n// Create TCP endpoint, bind it, then start listening.\nvar wq waiter.Queue\nep, e := s.NewEndpoint(tcp.ProtocolNumber, proto, &wq)\n- if err != nil {\n+ if e != nil {\nlog.Fatal(e)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
netstack: minor fix typo in "if err" handler
259,975
03.01.2020 17:46:04
28,800
bf53d325ddcd533d202efcab40047535078a02f3
Remove FIXME comments to close old bug.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/procfs.go", "new_path": "pkg/sentry/mm/procfs.go", "diff": "@@ -66,8 +66,6 @@ func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer\nvar start usermem.Addr\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n- // FIXME(b/30793614): If we use a usermem.Addr for the handle, we get\n- // \"panic: autosave error: type usermem.Addr is not registered\".\nmm.appendVMAMapsEntryLocked(ctx, vseg, buf)\n}\n@@ -81,7 +79,6 @@ func (mm *MemoryManager) ReadMapsDataInto(ctx context.Context, buf *bytes.Buffer\n//\n// Artifically adjust the seqfile handle so we only output vsyscall entry once.\nif start != vsyscallEnd {\n- // FIXME(b/30793614): Can't get a pointer to constant vsyscallEnd.\nbuf.WriteString(vsyscallMapsEntry)\n}\n}\n@@ -97,8 +94,6 @@ func (mm *MemoryManager) ReadMapsSeqFileData(ctx context.Context, handle seqfile\nstart = *handle.(*usermem.Addr)\n}\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n- // FIXME(b/30793614): If we use a usermem.Addr for the handle, we get\n- // \"panic: autosave error: type usermem.Addr is not registered\".\nvmaAddr := vseg.End()\ndata = append(data, seqfile.SeqData{\nBuf: mm.vmaMapsEntryLocked(ctx, vseg),\n@@ -116,7 +111,6 @@ func (mm *MemoryManager) ReadMapsSeqFileData(ctx context.Context, handle seqfile\n//\n// Artifically adjust the seqfile handle so we only output vsyscall entry once.\nif start != vsyscallEnd {\n- // FIXME(b/30793614): Can't get a pointer to constant vsyscallEnd.\nvmaAddr := vsyscallEnd\ndata = append(data, seqfile.SeqData{\nBuf: []byte(vsyscallMapsEntry),\n@@ -187,15 +181,12 @@ func (mm *MemoryManager) ReadSmapsDataInto(ctx context.Context, buf *bytes.Buffe\nvar start usermem.Addr\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n- // FIXME(b/30793614): If we use a usermem.Addr for the handle, we get\n- // \"panic: autosave error: type usermem.Addr is not registered\".\nmm.vmaSmapsEntryIntoLocked(ctx, vseg, buf)\n}\n// We always emulate vsyscall, so advertise it here. See\n// ReadMapsSeqFileData for additional commentary.\nif start != vsyscallEnd {\n- // FIXME(b/30793614): Can't get a pointer to constant vsyscallEnd.\nbuf.WriteString(vsyscallSmapsEntry)\n}\n}\n@@ -211,8 +202,6 @@ func (mm *MemoryManager) ReadSmapsSeqFileData(ctx context.Context, handle seqfil\nstart = *handle.(*usermem.Addr)\n}\nfor vseg := mm.vmas.LowerBoundSegment(start); vseg.Ok(); vseg = vseg.NextSegment() {\n- // FIXME(b/30793614): If we use a usermem.Addr for the handle, we get\n- // \"panic: autosave error: type usermem.Addr is not registered\".\nvmaAddr := vseg.End()\ndata = append(data, seqfile.SeqData{\nBuf: mm.vmaSmapsEntryLocked(ctx, vseg),\n@@ -223,7 +212,6 @@ func (mm *MemoryManager) ReadSmapsSeqFileData(ctx context.Context, handle seqfil\n// We always emulate vsyscall, so advertise it here. See\n// ReadMapsSeqFileData for additional commentary.\nif start != vsyscallEnd {\n- // FIXME(b/30793614): Can't get a pointer to constant vsyscallEnd.\nvmaAddr := vsyscallEnd\ndata = append(data, seqfile.SeqData{\nBuf: []byte(vsyscallSmapsEntry),\n" } ]
Go
Apache License 2.0
google/gvisor
Remove FIXME comments to close old bug. PiperOrigin-RevId: 288075400
259,974
31.12.2019 08:44:06
0
de0d127ae61df783745880871a199ff86a720035
Make some of the fcntl flags arch specific.. Some of the flags in the file system related system call are architecture specific(O_NOFOLLOW/O_DIRECT..). Ref to the fcntl.h file in the Linux src codes.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/file.go", "new_path": "pkg/abi/linux/file.go", "diff": "@@ -36,10 +36,6 @@ const (\nO_NONBLOCK = 000004000\nO_DSYNC = 000010000\nO_ASYNC = 000020000\n- O_DIRECT = 000040000\n- O_LARGEFILE = 000100000\n- O_DIRECTORY = 000200000\n- O_NOFOLLOW = 000400000\nO_NOATIME = 001000000\nO_CLOEXEC = 002000000\nO_SYNC = 004000000 // __O_SYNC in Linux\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/file_amd64.go", "new_path": "pkg/abi/linux/file_amd64.go", "diff": "package linux\n+// Constants for open(2).\n+const (\n+ O_DIRECT = 000040000\n+ O_LARGEFILE = 000100000\n+ O_DIRECTORY = 000200000\n+ O_NOFOLLOW = 000400000\n+)\n+\n// Stat represents struct stat.\ntype Stat struct {\nDev uint64\n" }, { "change_type": "MODIFY", "old_path": "pkg/abi/linux/file_arm64.go", "new_path": "pkg/abi/linux/file_arm64.go", "diff": "package linux\n+// Constants for open(2).\n+const (\n+ O_DIRECTORY = 000040000\n+ O_NOFOLLOW = 000100000\n+ O_DIRECT = 000200000\n+ O_LARGEFILE = 000400000\n+)\n+\n// Stat represents struct stat.\ntype Stat struct {\nDev uint64\n" } ]
Go
Apache License 2.0
google/gvisor
Make some of the fcntl flags arch specific.. Some of the flags in the file system related system call are architecture specific(O_NOFOLLOW/O_DIRECT..). Ref to the fcntl.h file in the Linux src codes. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I354d988073bfd0c9ff5371d4e0be9da2b8fd019f
260,004
07.01.2020 10:07:59
28,800
2031cc4701d5bfd21b34d7b0f7dc86920a553385
Disable auto-generation of IPv6 link-local addresses for loopback NICs Test: Test that an IPv6 link-local address is not auto-generated for loopback NICs, even when it is enabled for non-loopback NICS.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -174,7 +174,8 @@ func (n *NIC) enable() *tcpip.Error {\nreturn err\n}\n- if !n.stack.autoGenIPv6LinkLocal {\n+ // Do not auto-generate an IPv6 link-local address for loopback devices.\n+ if !n.stack.autoGenIPv6LinkLocal || n.loopback {\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -444,8 +444,8 @@ type Stack struct {\nndpConfigs NDPConfigurations\n// autoGenIPv6LinkLocal determines whether or not the stack will attempt\n- // to auto-generate an IPv6 link-local address for newly enabled NICs.\n- // See the AutoGenIPv6LinkLocal field of Options for more details.\n+ // to auto-generate an IPv6 link-local address for newly enabled non-loopback\n+ // NICs. See the AutoGenIPv6LinkLocal field of Options for more details.\nautoGenIPv6LinkLocal bool\n// ndpDisp is the NDP event dispatcher that is used to send the netstack\n@@ -496,13 +496,15 @@ type Options struct {\n// before assigning an address to a NIC.\nNDPConfigs NDPConfigurations\n- // AutoGenIPv6LinkLocal determins whether or not the stack will attempt\n- // to auto-generate an IPv6 link-local address for newly enabled NICs.\n+ // AutoGenIPv6LinkLocal determines whether or not the stack will attempt to\n+ // auto-generate an IPv6 link-local address for newly enabled non-loopback\n+ // NICs.\n+ //\n// Note, setting this to true does not mean that a link-local address\n- // will be assigned right away, or at all. If Duplicate Address\n- // Detection is enabled, an address will only be assigned if it\n- // successfully resolves. If it fails, no further attempt will be made\n- // to auto-generate an IPv6 link-local address.\n+ // will be assigned right away, or at all. If Duplicate Address Detection\n+ // is enabled, an address will only be assigned if it successfully resolves.\n+ // If it fails, no further attempt will be made to auto-generate an IPv6\n+ // link-local address.\n//\n// The generated link-local address will follow RFC 4291 Appendix A\n// guidelines.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2121,6 +2121,55 @@ func TestNICAutoGenAddrWithOpaque(t *testing.T) {\n}\n}\n+// TestNoLinkLocalAutoGenForLoopbackNIC tests that IPv6 link-local addresses are\n+// not auto-generated for loopback NICs.\n+func TestNoLinkLocalAutoGenForLoopbackNIC(t *testing.T) {\n+ const nicID = 1\n+ const nicName = \"nicName\"\n+\n+ tests := []struct {\n+ name string\n+ opaqueIIDOpts stack.OpaqueInterfaceIdentifierOptions\n+ }{\n+ {\n+ name: \"IID From MAC\",\n+ opaqueIIDOpts: stack.OpaqueInterfaceIdentifierOptions{},\n+ },\n+ {\n+ name: \"Opaque IID\",\n+ opaqueIIDOpts: stack.OpaqueInterfaceIdentifierOptions{\n+ NICNameFromID: func(_ tcpip.NICID, nicName string) string {\n+ return nicName\n+ },\n+ },\n+ },\n+ }\n+\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ opts := stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n+ AutoGenIPv6LinkLocal: true,\n+ OpaqueIIDOpts: test.opaqueIIDOpts,\n+ }\n+\n+ e := channel.New(0, 1280, linkAddr1)\n+ s := stack.New(opts)\n+ if err := s.CreateNamedLoopbackNIC(nicID, nicName, e); err != nil {\n+ t.Fatalf(\"CreateNamedLoopbackNIC(%d, %q, _) = %s\", nicID, nicName, err)\n+ }\n+\n+ addr, err := s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"stack.GetMainNICAddress(%d, _) err = %s\", nicID, err)\n+ }\n+ if want := (tcpip.AddressWithPrefix{}); addr != want {\n+ t.Errorf(\"got stack.GetMainNICAddress(%d, _) = %s, want = %s\", nicID, addr, want)\n+ }\n+ })\n+ }\n+}\n+\n// TestNICAutoGenAddrDoesDAD tests that the successful auto-generation of IPv6\n// link-local addresses will only be assigned after the DAD process resolves.\nfunc TestNICAutoGenAddrDoesDAD(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Disable auto-generation of IPv6 link-local addresses for loopback NICs Test: Test that an IPv6 link-local address is not auto-generated for loopback NICs, even when it is enabled for non-loopback NICS. PiperOrigin-RevId: 288519591
259,858
07.01.2020 17:25:18
28,800
e77ad574233b779519a253c6f58197c339e9100a
Fix partial_bad_buffer write tests. The write tests are fitted to Linux-specific behavior, but it is not well-specified. Tweak the tests to allow for both acceptable outcomes.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/partial_bad_buffer.cc", "new_path": "test/syscalls/linux/partial_bad_buffer.cc", "diff": "#include <netinet/tcp.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n+#include <sys/stat.h>\n#include <sys/syscall.h>\n+#include <sys/types.h>\n#include <sys/uio.h>\n#include <unistd.h>\n@@ -62,9 +64,9 @@ class PartialBadBufferTest : public ::testing::Test {\n// Write some initial data.\nsize_t size = sizeof(kMessage) - 1;\nEXPECT_THAT(WriteFd(fd_, &kMessage, size), SyscallSucceedsWithValue(size));\n-\nASSERT_THAT(lseek(fd_, 0, SEEK_SET), SyscallSucceeds());\n+ // Map a useable buffer.\naddr_ = mmap(0, 2 * kPageSize, PROT_READ | PROT_WRITE,\nMAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\nASSERT_NE(addr_, MAP_FAILED);\n@@ -79,6 +81,15 @@ class PartialBadBufferTest : public ::testing::Test {\nbad_buffer_ = buf + kPageSize - 1;\n}\n+ off_t Size() {\n+ struct stat st;\n+ int rc = fstat(fd_, &st);\n+ if (rc < 0) {\n+ return static_cast<off_t>(rc);\n+ }\n+ return st.st_size;\n+ }\n+\nvoid TearDown() override {\nEXPECT_THAT(munmap(addr_, 2 * kPageSize), SyscallSucceeds()) << addr_;\nEXPECT_THAT(close(fd_), SyscallSucceeds());\n@@ -165,97 +176,99 @@ TEST_F(PartialBadBufferTest, PreadvSmall) {\n}\nTEST_F(PartialBadBufferTest, WriteBig) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(write)(fd_, bad_buffer_, kPageSize),\n- SyscallFailsWithErrno(EFAULT));\n+ ASSERT_THAT(lseek(fd_, orig_size, SEEK_SET), SyscallSucceeds());\n+ EXPECT_THAT(\n+ (n = RetryEINTR(write)(fd_, bad_buffer_, kPageSize)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, WriteSmall) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(write)(fd_, bad_buffer_, 10),\n- SyscallFailsWithErrno(EFAULT));\n+ ASSERT_THAT(lseek(fd_, orig_size, SEEK_SET), SyscallSucceeds());\n+ EXPECT_THAT(\n+ (n = RetryEINTR(write)(fd_, bad_buffer_, 10)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, PwriteBig) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(pwrite)(fd_, bad_buffer_, kPageSize, 0),\n- SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(\n+ (n = RetryEINTR(pwrite)(fd_, bad_buffer_, kPageSize, orig_size)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, PwriteSmall) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(pwrite)(fd_, bad_buffer_, 10, 0),\n- SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(\n+ (n = RetryEINTR(pwrite)(fd_, bad_buffer_, 10, orig_size)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, WritevBig) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n-\nstruct iovec vec;\nvec.iov_base = bad_buffer_;\nvec.iov_len = kPageSize;\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(writev)(fd_, &vec, 1), SyscallFailsWithErrno(EFAULT));\n+ ASSERT_THAT(lseek(fd_, orig_size, SEEK_SET), SyscallSucceeds());\n+ EXPECT_THAT(\n+ (n = RetryEINTR(writev)(fd_, &vec, 1)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, WritevSmall) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n-\nstruct iovec vec;\nvec.iov_base = bad_buffer_;\nvec.iov_len = 10;\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(writev)(fd_, &vec, 1), SyscallFailsWithErrno(EFAULT));\n+ ASSERT_THAT(lseek(fd_, orig_size, SEEK_SET), SyscallSucceeds());\n+ EXPECT_THAT(\n+ (n = RetryEINTR(writev)(fd_, &vec, 1)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, PwritevBig) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n-\nstruct iovec vec;\nvec.iov_base = bad_buffer_;\nvec.iov_len = kPageSize;\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(pwritev)(fd_, &vec, 1, 0),\n- SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(\n+ (n = RetryEINTR(pwritev)(fd_, &vec, 1, orig_size)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\nTEST_F(PartialBadBufferTest, PwritevSmall) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n-\nstruct iovec vec;\nvec.iov_base = bad_buffer_;\nvec.iov_len = 10;\n+ off_t orig_size = Size();\n+ int n;\n- EXPECT_THAT(RetryEINTR(pwritev)(fd_, &vec, 1, 0),\n- SyscallFailsWithErrno(EFAULT));\n+ EXPECT_THAT(\n+ (n = RetryEINTR(pwritev)(fd_, &vec, 1, orig_size)),\n+ AnyOf(SyscallFailsWithErrno(EFAULT), SyscallSucceedsWithValue(1)));\n+ EXPECT_EQ(Size(), orig_size + (n >= 0 ? n : 0));\n}\n// getdents returns EFAULT when the you claim the buffer is large enough, but\n@@ -283,29 +296,6 @@ TEST_F(PartialBadBufferTest, GetdentsOneEntry) {\nSyscallSucceedsWithValue(Gt(0)));\n}\n-// Verify that when write returns EFAULT the kernel hasn't silently written\n-// the initial valid bytes.\n-TEST_F(PartialBadBufferTest, WriteEfaultIsntPartial) {\n- // FIXME(b/24788078): The sentry write syscalls will return immediately\n- // if Access returns an error, but Access may not return an error\n- // and the sentry will instead perform a partial write.\n- SKIP_IF(IsRunningOnGvisor());\n-\n- bad_buffer_[0] = 'A';\n- EXPECT_THAT(RetryEINTR(write)(fd_, bad_buffer_, 10),\n- SyscallFailsWithErrno(EFAULT));\n-\n- size_t size = 255;\n- char buf[255];\n- memset(buf, 0, size);\n-\n- EXPECT_THAT(RetryEINTR(pread)(fd_, buf, size, 0),\n- SyscallSucceedsWithValue(sizeof(kMessage) - 1));\n-\n- // 'A' has not been written.\n- EXPECT_STREQ(buf, kMessage);\n-}\n-\nPosixErrorOr<sockaddr_storage> InetLoopbackAddr(int family) {\nstruct sockaddr_storage addr;\nmemset(&addr, 0, sizeof(addr));\n" } ]
Go
Apache License 2.0
google/gvisor
Fix partial_bad_buffer write tests. The write tests are fitted to Linux-specific behavior, but it is not well-specified. Tweak the tests to allow for both acceptable outcomes. PiperOrigin-RevId: 288606386
259,853
07.01.2020 23:52:59
28,800
a53ac7307abfeb7172e67f48d0a7aaa4b5c3f31e
fs/splice: don't report a partialResult error if there is no data loss
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/file.go", "new_path": "pkg/sentry/fs/file.go", "diff": "@@ -555,6 +555,10 @@ type lockedWriter struct {\n//\n// This applies only to Write, not WriteAt.\nOffset int64\n+\n+ // Err contains the first error encountered while copying. This is\n+ // useful to determine whether Writer or Reader failed during io.Copy.\n+ Err error\n}\n// Write implements io.Writer.Write.\n@@ -590,5 +594,8 @@ func (w *lockedWriter) WriteAt(buf []byte, offset int64) (int, error) {\nbreak\n}\n}\n+ if w.Err == nil {\n+ w.Err = err\n+ }\nreturn written, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/splice.go", "new_path": "pkg/sentry/fs/splice.go", "diff": "@@ -167,6 +167,11 @@ func Splice(ctx context.Context, dst *File, src *File, opts SpliceOpts) (int64,\nif !srcPipe && !opts.SrcOffset {\natomic.StoreInt64(&src.offset, src.offset+n)\n}\n+\n+ // Don't report any errors if we have some progress without data loss.\n+ if w.Err == nil {\n+ err = nil\n+ }\n}\n// Drop locks.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -1591,6 +1591,34 @@ TEST(Inotify, EpollNoDeadlock) {\n}\n}\n+TEST(Inotify, SpliceEvent) {\n+ int pipes[2];\n+ ASSERT_THAT(pipe2(pipes, O_NONBLOCK), SyscallSucceeds());\n+\n+ const TempPath root = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(InotifyInit1(IN_NONBLOCK));\n+ const TempPath file1 = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n+ root.path(), \"some content\", TempPath::kDefaultFileMode));\n+\n+ const FileDescriptor file1_fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));\n+ const int watcher = ASSERT_NO_ERRNO_AND_VALUE(\n+ InotifyAddWatch(fd.get(), file1.path(), IN_ALL_EVENTS));\n+\n+ char buf;\n+ EXPECT_THAT(read(file1_fd.get(), &buf, 1), SyscallSucceeds());\n+\n+ EXPECT_THAT(splice(fd.get(), nullptr, pipes[1], nullptr,\n+ sizeof(struct inotify_event) + 1, SPLICE_F_NONBLOCK),\n+ SyscallSucceedsWithValue(sizeof(struct inotify_event)));\n+\n+ const FileDescriptor read_fd(pipes[0]);\n+ const std::vector<Event> events =\n+ ASSERT_NO_ERRNO_AND_VALUE(DrainEvents(read_fd.get()));\n+ ASSERT_THAT(events, Are({Event(IN_ACCESS, watcher)}));\n+}\n+\n} // namespace\n} // namespace testing\n} // namespace gvisor\n" } ]
Go
Apache License 2.0
google/gvisor
fs/splice: don't report a partialResult error if there is no data loss PiperOrigin-RevId: 288642552
259,942
08.01.2020 09:28:53
28,800
0cc1e74b57e539e66c1a421c047a08635c0008e8
Add NIC.isLoopback() ...enabling us to remove the "CreateNamedLoopbackNIC" variant of CreateNIC and all the plumbing to connect it through to where the value is read in FindRoute.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -31,7 +31,6 @@ type NIC struct {\nid tcpip.NICID\nname string\nlinkEP LinkEndpoint\n- loopback bool\nmu sync.RWMutex\nspoofing bool\n@@ -85,7 +84,7 @@ const (\n)\n// newNIC returns a new NIC using the default NDP configurations from stack.\n-func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, loopback bool) *NIC {\n+func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint) *NIC {\n// TODO(b/141011931): Validate a LinkEndpoint (ep) is valid. For\n// example, make sure that the link address it provides is a valid\n// unicast ethernet address.\n@@ -99,7 +98,6 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, loopback\nid: id,\nname: name,\nlinkEP: ep,\n- loopback: loopback,\nprimary: make(map[tcpip.NetworkProtocolNumber][]*referencedNetworkEndpoint),\nendpoints: make(map[NetworkEndpointID]*referencedNetworkEndpoint),\nmcastJoins: make(map[NetworkEndpointID]int32),\n@@ -175,7 +173,7 @@ func (n *NIC) enable() *tcpip.Error {\n}\n// Do not auto-generate an IPv6 link-local address for loopback devices.\n- if !n.stack.autoGenIPv6LinkLocal || n.loopback {\n+ if !n.stack.autoGenIPv6LinkLocal || n.isLoopback() {\nreturn nil\n}\n@@ -240,6 +238,10 @@ func (n *NIC) isPromiscuousMode() bool {\nreturn rv\n}\n+func (n *NIC) isLoopback() bool {\n+ return n.linkEP.Capabilities()&CapabilityLoopback != 0\n+}\n+\n// setSpoofing enables or disables address spoofing.\nfunc (n *NIC) setSpoofing(enable bool) {\nn.mu.Lock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -798,7 +798,7 @@ func (s *Stack) NewPacketEndpoint(cooked bool, netProto tcpip.NetworkProtocolNum\n// createNIC creates a NIC with the provided id and link-layer endpoint, and\n// optionally enable it.\n-func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled, loopback bool) *tcpip.Error {\n+func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled bool) *tcpip.Error {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -807,7 +807,7 @@ func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled,\nreturn tcpip.ErrDuplicateNICID\n}\n- n := newNIC(s, id, name, ep, loopback)\n+ n := newNIC(s, id, name, ep)\ns.nics[id] = n\nif enabled {\n@@ -819,32 +819,26 @@ func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled,\n// CreateNIC creates a NIC with the provided id and link-layer endpoint.\nfunc (s *Stack) CreateNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, \"\", ep, true, false)\n+ return s.createNIC(id, \"\", ep, true)\n}\n// CreateNamedNIC creates a NIC with the provided id and link-layer endpoint,\n// and a human-readable name.\nfunc (s *Stack) CreateNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, name, ep, true, false)\n-}\n-\n-// CreateNamedLoopbackNIC creates a NIC with the provided id and link-layer\n-// endpoint, and a human-readable name.\n-func (s *Stack) CreateNamedLoopbackNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, name, ep, true, true)\n+ return s.createNIC(id, name, ep, true)\n}\n// CreateDisabledNIC creates a NIC with the provided id and link-layer endpoint,\n// but leave it disable. Stack.EnableNIC must be called before the link-layer\n// endpoint starts delivering packets to it.\nfunc (s *Stack) CreateDisabledNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, \"\", ep, false, false)\n+ return s.createNIC(id, \"\", ep, false)\n}\n// CreateDisabledNamedNIC is a combination of CreateNamedNIC and\n// CreateDisabledNIC.\nfunc (s *Stack) CreateDisabledNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, name, ep, false, false)\n+ return s.createNIC(id, name, ep, false)\n}\n// EnableNIC enables the given NIC so that the link-layer endpoint can start\n@@ -911,7 +905,7 @@ func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\nUp: true, // Netstack interfaces are always up.\nRunning: nic.linkEP.IsAttached(),\nPromiscuous: nic.isPromiscuousMode(),\n- Loopback: nic.linkEP.Capabilities()&CapabilityLoopback != 0,\n+ Loopback: nic.isLoopback(),\n}\nnics[id] = NICInfo{\nName: nic.name,\n@@ -1072,7 +1066,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nif id != 0 && !needRoute {\nif nic, ok := s.nics[id]; ok {\nif ref := s.getRefEP(nic, localAddr, netProto); ref != nil {\n- return makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref, s.handleLocal && !nic.loopback, multicastLoop && !nic.loopback), nil\n+ return makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref, s.handleLocal && !nic.isLoopback(), multicastLoop && !nic.isLoopback()), nil\n}\n}\n} else {\n@@ -1088,7 +1082,7 @@ func (s *Stack) FindRoute(id tcpip.NICID, localAddr, remoteAddr tcpip.Address, n\nremoteAddr = ref.ep.ID().LocalAddress\n}\n- r := makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref, s.handleLocal && !nic.loopback, multicastLoop && !nic.loopback)\n+ r := makeRoute(netProto, ref.ep.ID().LocalAddress, remoteAddr, nic.linkEP.LinkAddress(), ref, s.handleLocal && !nic.isLoopback(), multicastLoop && !nic.isLoopback())\nif needRoute {\nr.NextHop = route.Gateway\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -32,6 +32,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n\"gvisor.dev/gvisor/pkg/tcpip/link/channel\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/link/loopback\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/ipv6\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -2153,10 +2154,10 @@ func TestNoLinkLocalAutoGenForLoopbackNIC(t *testing.T) {\nOpaqueIIDOpts: test.opaqueIIDOpts,\n}\n- e := channel.New(0, 1280, linkAddr1)\n+ e := loopback.New()\ns := stack.New(opts)\n- if err := s.CreateNamedLoopbackNIC(nicID, nicName, e); err != nil {\n- t.Fatalf(\"CreateNamedLoopbackNIC(%d, %q, _) = %s\", nicID, nicName, err)\n+ if err := s.CreateNamedNIC(nicID, nicName, e); err != nil {\n+ t.Fatalf(\"CreateNamedNIC(%d, %q, _) = %s\", nicID, nicName, err)\n}\naddr, err := s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -126,7 +126,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\nlinkEP := loopback.New()\nlog.Infof(\"Enabling loopback interface %q with id %d on addresses %+v\", link.Name, nicID, link.Addresses)\n- if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses, true /* loopback */); err != nil {\n+ if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses); err != nil {\nreturn err\n}\n@@ -173,7 +173,7 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n}\nlog.Infof(\"Enabling interface %q with id %d on addresses %+v (%v) w/ %d channels\", link.Name, nicID, link.Addresses, mac, link.NumChannels)\n- if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses, false /* loopback */); err != nil {\n+ if err := n.createNICWithAddrs(nicID, link.Name, linkEP, link.Addresses); err != nil {\nreturn err\n}\n@@ -218,16 +218,10 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n// createNICWithAddrs creates a NIC in the network stack and adds the given\n// addresses.\n-func (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []net.IP, loopback bool) error {\n- if loopback {\n- if err := n.Stack.CreateNamedLoopbackNIC(id, name, sniffer.New(ep)); err != nil {\n- return fmt.Errorf(\"CreateNamedLoopbackNIC(%v, %v, %v) failed: %v\", id, name, ep, err)\n- }\n- } else {\n+func (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []net.IP) error {\nif err := n.Stack.CreateNamedNIC(id, name, sniffer.New(ep)); err != nil {\nreturn fmt.Errorf(\"CreateNamedNIC(%v, %v, %v) failed: %v\", id, name, ep, err)\n}\n- }\n// Always start with an arp address for the NIC.\nif err := n.Stack.AddAddress(id, arp.ProtocolNumber, arp.ProtocolAddress); err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Add NIC.isLoopback() ...enabling us to remove the "CreateNamedLoopbackNIC" variant of CreateNIC and all the plumbing to connect it through to where the value is read in FindRoute. PiperOrigin-RevId: 288713093
259,992
08.01.2020 10:30:50
28,800
db376e13924be59182ed4df95762328febf26298
Make /proc/[pid] offset start at TGID_OFFSET Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -27,7 +27,11 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n-const defaultPermission = 0444\n+const (\n+ defaultPermission = 0444\n+ selfName = \"self\"\n+ threadSelfName = \"thread-self\"\n+)\n// InoGenerator generates unique inode numbers for a given filesystem.\ntype InoGenerator interface {\n@@ -45,6 +49,11 @@ type tasksInode struct {\ninoGen InoGenerator\npidns *kernel.PIDNamespace\n+\n+ // '/proc/self' and '/proc/thread-self' have custom directory offsets in\n+ // Linux. So handle them outside of OrderedChildren.\n+ selfSymlink *vfs.Dentry\n+ threadSelfSymlink *vfs.Dentry\n}\nvar _ kernfs.Inode = (*tasksInode)(nil)\n@@ -57,9 +66,7 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\n\"loadavg\": newDentry(root, inoGen.NextIno(), defaultPermission, &loadavgData{}),\n\"meminfo\": newDentry(root, inoGen.NextIno(), defaultPermission, &meminfoData{k: k}),\n\"mounts\": kernfs.NewStaticSymlink(root, inoGen.NextIno(), defaultPermission, \"self/mounts\"),\n- \"self\": newSelfSymlink(root, inoGen.NextIno(), defaultPermission, pidns),\n\"stat\": newDentry(root, inoGen.NextIno(), defaultPermission, &statData{k: k}),\n- \"thread-self\": newThreadSelfSymlink(root, inoGen.NextIno(), defaultPermission, pidns),\n//\"uptime\": newUptime(ctx, msrc),\n//\"version\": newVersionData(root, inoGen.NextIno(), k),\n\"version\": newDentry(root, inoGen.NextIno(), defaultPermission, &versionData{k: k}),\n@@ -68,6 +75,8 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\ninode := &tasksInode{\npidns: pidns,\ninoGen: inoGen,\n+ selfSymlink: newSelfSymlink(root, inoGen.NextIno(), 0444, pidns).VFSDentry(),\n+ threadSelfSymlink: newThreadSelfSymlink(root, inoGen.NextIno(), 0444, pidns).VFSDentry(),\n}\ninode.InodeAttrs.Init(root, inoGen.NextIno(), linux.ModeDirectory|0555)\n@@ -86,6 +95,13 @@ func (i *tasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, erro\n// Try to lookup a corresponding task.\ntid, err := strconv.ParseUint(name, 10, 64)\nif err != nil {\n+ // If it failed to parse, check if it's one of the special handled files.\n+ switch name {\n+ case selfName:\n+ return i.selfSymlink, nil\n+ case threadSelfName:\n+ return i.threadSelfSymlink, nil\n+ }\nreturn nil, syserror.ENOENT\n}\n@@ -104,41 +120,81 @@ func (i *tasksInode) Valid(ctx context.Context) bool {\n}\n// IterDirents implements kernfs.inodeDynamicLookup.\n-//\n-// TODO(gvisor.dev/issue/1195): Use tgid N offset = TGID_OFFSET + N.\n-func (i *tasksInode) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback, offset, relOffset int64) (int64, error) {\n- var tids []int\n+func (i *tasksInode) IterDirents(ctx context.Context, cb vfs.IterDirentsCallback, offset, _ int64) (int64, error) {\n+ // fs/proc/internal.h: #define FIRST_PROCESS_ENTRY 256\n+ const FIRST_PROCESS_ENTRY = 256\n+\n+ // Use maxTaskID to shortcut searches that will result in 0 entries.\n+ const maxTaskID = kernel.TasksLimit + 1\n+ if offset >= maxTaskID {\n+ return offset, nil\n+ }\n+\n+ // According to Linux (fs/proc/base.c:proc_pid_readdir()), process directories\n+ // start at offset FIRST_PROCESS_ENTRY with '/proc/self', followed by\n+ // '/proc/thread-self' and then '/proc/[pid]'.\n+ if offset < FIRST_PROCESS_ENTRY {\n+ offset = FIRST_PROCESS_ENTRY\n+ }\n- // Collect all tasks. Per linux we only include it in directory listings if\n- // it's the leader. But for whatever crazy reason, you can still walk to the\n- // given node.\n+ if offset == FIRST_PROCESS_ENTRY {\n+ dirent := vfs.Dirent{\n+ Name: selfName,\n+ Type: linux.DT_LNK,\n+ Ino: i.inoGen.NextIno(),\n+ NextOff: offset + 1,\n+ }\n+ if !cb.Handle(dirent) {\n+ return offset, nil\n+ }\n+ offset++\n+ }\n+ if offset == FIRST_PROCESS_ENTRY+1 {\n+ dirent := vfs.Dirent{\n+ Name: threadSelfName,\n+ Type: linux.DT_LNK,\n+ Ino: i.inoGen.NextIno(),\n+ NextOff: offset + 1,\n+ }\n+ if !cb.Handle(dirent) {\n+ return offset, nil\n+ }\n+ offset++\n+ }\n+\n+ // Collect all tasks that TGIDs are greater than the offset specified. Per\n+ // Linux we only include in directory listings if it's the leader. But for\n+ // whatever crazy reason, you can still walk to the given node.\n+ var tids []int\n+ startTid := offset - FIRST_PROCESS_ENTRY - 2\nfor _, tg := range i.pidns.ThreadGroups() {\n+ tid := i.pidns.IDOfThreadGroup(tg)\n+ if int64(tid) < startTid {\n+ continue\n+ }\nif leader := tg.Leader(); leader != nil {\n- tids = append(tids, int(i.pidns.IDOfThreadGroup(tg)))\n+ tids = append(tids, int(tid))\n}\n}\nif len(tids) == 0 {\nreturn offset, nil\n}\n- if relOffset >= int64(len(tids)) {\n- return offset, nil\n- }\nsort.Ints(tids)\n- for _, tid := range tids[relOffset:] {\n+ for _, tid := range tids {\ndirent := vfs.Dirent{\nName: strconv.FormatUint(uint64(tid), 10),\nType: linux.DT_DIR,\nIno: i.inoGen.NextIno(),\n- NextOff: offset + 1,\n+ NextOff: FIRST_PROCESS_ENTRY + 2 + int64(tid) + 1,\n}\nif !cb.Handle(dirent) {\nreturn offset, nil\n}\noffset++\n}\n- return offset, nil\n+ return maxTaskID, nil\n}\n// Open implements kernfs.Inode.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -16,6 +16,7 @@ package proc\nimport (\n\"fmt\"\n+ \"math\"\n\"path\"\n\"strconv\"\n\"testing\"\n@@ -30,6 +31,18 @@ import (\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n+var (\n+ // Next offset 256 by convention. Adds 1 for the next offset.\n+ selfLink = vfs.Dirent{Type: linux.DT_LNK, NextOff: 256 + 0 + 1}\n+ threadSelfLink = vfs.Dirent{Type: linux.DT_LNK, NextOff: 256 + 1 + 1}\n+\n+ // /proc/[pid] next offset starts at 256+2 (files above), then adds the\n+ // PID, and adds 1 for the next offset.\n+ proc1 = vfs.Dirent{Type: linux.DT_DIR, NextOff: 258 + 1 + 1}\n+ proc2 = vfs.Dirent{Type: linux.DT_DIR, NextOff: 258 + 2 + 1}\n+ proc3 = vfs.Dirent{Type: linux.DT_DIR, NextOff: 258 + 3 + 1}\n+)\n+\ntype testIterDirentsCallback struct {\ndirents []vfs.Dirent\n}\n@@ -59,9 +72,9 @@ func checkTasksStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\n\"loadavg\": {Type: linux.DT_REG},\n\"meminfo\": {Type: linux.DT_REG},\n\"mounts\": {Type: linux.DT_LNK},\n- \"self\": {Type: linux.DT_LNK},\n+ \"self\": selfLink,\n\"stat\": {Type: linux.DT_REG},\n- \"thread-self\": {Type: linux.DT_LNK},\n+ \"thread-self\": threadSelfLink,\n\"version\": {Type: linux.DT_REG},\n}\nreturn checkFiles(gots, wants)\n@@ -93,6 +106,9 @@ func checkFiles(gots []vfs.Dirent, wants map[string]vfs.Dirent) ([]vfs.Dirent, e\nif want.Type != got.Type {\nreturn gots, fmt.Errorf(\"wrong file type, want: %v, got: %v: %+v\", want.Type, got.Type, got)\n}\n+ if want.NextOff != 0 && want.NextOff != got.NextOff {\n+ return gots, fmt.Errorf(\"wrong dirent offset, want: %v, got: %v: %+v\", want.NextOff, got.NextOff, got)\n+ }\ndelete(wants, got.Name)\ngots = append(gots[0:i], gots[i+1:]...)\n@@ -154,7 +170,7 @@ func TestTasksEmpty(t *testing.T) {\nt.Error(err.Error())\n}\nif len(cb.dirents) != 0 {\n- t.Error(\"found more files than expected: %+v\", cb.dirents)\n+ t.Errorf(\"found more files than expected: %+v\", cb.dirents)\n}\n}\n@@ -216,6 +232,11 @@ func TestTasks(t *testing.T) {\nif !found {\nt.Errorf(\"Additional task ID %d listed: %v\", pid, tasks)\n}\n+ // Next offset starts at 256+2 ('self' and 'thread-self'), then adds the\n+ // PID, and adds 1 for the next offset.\n+ if want := int64(256 + 2 + pid + 1); d.NextOff != want {\n+ t.Errorf(\"Wrong dirent offset want: %d got: %d: %+v\", want, d.NextOff, d)\n+ }\n}\n// Test lookup.\n@@ -246,6 +267,126 @@ func TestTasks(t *testing.T) {\n}\n}\n+func TestTasksOffset(t *testing.T) {\n+ ctx, vfsObj, root, err := setup()\n+ if err != nil {\n+ t.Fatalf(\"Setup failed: %v\", err)\n+ }\n+ defer root.DecRef()\n+\n+ k := kernel.KernelFromContext(ctx)\n+ for i := 0; i < 3; i++ {\n+ tc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n+ if _, err := createTask(ctx, fmt.Sprintf(\"name-%d\", i), tc); err != nil {\n+ t.Fatalf(\"CreateTask(): %v\", err)\n+ }\n+ }\n+\n+ for _, tc := range []struct {\n+ name string\n+ offset int64\n+ wants map[string]vfs.Dirent\n+ }{\n+ {\n+ name: \"small offset\",\n+ offset: 100,\n+ wants: map[string]vfs.Dirent{\n+ \"self\": selfLink,\n+ \"thread-self\": threadSelfLink,\n+ \"1\": proc1,\n+ \"2\": proc2,\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"offset at start\",\n+ offset: 256,\n+ wants: map[string]vfs.Dirent{\n+ \"self\": selfLink,\n+ \"thread-self\": threadSelfLink,\n+ \"1\": proc1,\n+ \"2\": proc2,\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"skip /proc/self\",\n+ offset: 257,\n+ wants: map[string]vfs.Dirent{\n+ \"thread-self\": threadSelfLink,\n+ \"1\": proc1,\n+ \"2\": proc2,\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"skip symlinks\",\n+ offset: 258,\n+ wants: map[string]vfs.Dirent{\n+ \"1\": proc1,\n+ \"2\": proc2,\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"skip first process\",\n+ offset: 260,\n+ wants: map[string]vfs.Dirent{\n+ \"2\": proc2,\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"last process\",\n+ offset: 261,\n+ wants: map[string]vfs.Dirent{\n+ \"3\": proc3,\n+ },\n+ },\n+ {\n+ name: \"after last\",\n+ offset: 262,\n+ wants: nil,\n+ },\n+ {\n+ name: \"TaskLimit+1\",\n+ offset: kernel.TasksLimit + 1,\n+ wants: nil,\n+ },\n+ {\n+ name: \"max\",\n+ offset: math.MaxInt64,\n+ wants: nil,\n+ },\n+ } {\n+ t.Run(tc.name, func(t *testing.T) {\n+ fd, err := vfsObj.OpenAt(\n+ ctx,\n+ auth.CredentialsFromContext(ctx),\n+ &vfs.PathOperation{Root: root, Start: root, Path: fspath.Parse(\"/\")},\n+ &vfs.OpenOptions{},\n+ )\n+ if err != nil {\n+ t.Fatalf(\"vfsfs.OpenAt(/) failed: %v\", err)\n+ }\n+ if _, err := fd.Impl().Seek(ctx, tc.offset, linux.SEEK_SET); err != nil {\n+ t.Fatalf(\"Seek(%d, SEEK_SET): %v\", tc.offset, err)\n+ }\n+\n+ cb := testIterDirentsCallback{}\n+ if err := fd.Impl().IterDirents(ctx, &cb); err != nil {\n+ t.Fatalf(\"IterDirents(): %v\", err)\n+ }\n+ if cb.dirents, err = checkFiles(cb.dirents, tc.wants); err != nil {\n+ t.Error(err.Error())\n+ }\n+ if len(cb.dirents) != 0 {\n+ t.Errorf(\"found more files than expected: %+v\", cb.dirents)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestTask(t *testing.T) {\nctx, vfsObj, root, err := setup()\nif err != nil {\n" } ]
Go
Apache License 2.0
google/gvisor
Make /proc/[pid] offset start at TGID_OFFSET Updates #1195 PiperOrigin-RevId: 288725745
259,891
08.01.2020 11:15:46
28,800
1e1921e2acdb7357972257219fdffb9edf17bf55
Minor fixes to comments and logging
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -157,9 +157,7 @@ func convertNetstackToBinary(name string, table iptables.Table) (linux.KernelIPT\nmeta.HookEntry[hook] = entries.Size\n}\n}\n- // Is this a chain underflow point? The underflow rule is the last rule\n- // in the chain, and is an unconditional rule (i.e. it matches any\n- // packet). This is enforced when saving iptables.\n+ // Is this a chain underflow point?\nfor underflow, underflowRuleIdx := range table.Underflows {\nif underflowRuleIdx == ruleIdx {\nmeta.Underflow[underflow] = entries.Size\n@@ -290,6 +288,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// Get the basic rules data (struct ipt_replace).\nif len(optVal) < linux.SizeOfIPTReplace {\n+ log.Infof(\"netfilter.SetEntries: optVal has insufficient size for replace %d\", len(optVal))\nreturn syserr.ErrInvalidArgument\n}\nvar replace linux.IPTReplace\n@@ -313,6 +312,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nfor entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\n// Get the struct ipt_entry.\nif len(optVal) < linux.SizeOfIPTEntry {\n+ log.Infof(\"netfilter: optVal has insufficient size for entry %d\", len(optVal))\nreturn syserr.ErrInvalidArgument\n}\nvar entry linux.IPTEntry\n@@ -328,6 +328,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// filtering. We reject any nonzero IPTIP values for now.\nemptyIPTIP := linux.IPTIP{}\nif entry.IP != emptyIPTIP {\n+ log.Infof(\"netfilter: non-empty struct iptip found\")\nreturn syserr.ErrInvalidArgument\n}\n@@ -386,6 +387,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// along with the number of bytes it occupies in optVal.\nfunc parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nif len(optVal) < linux.SizeOfXTEntryTarget {\n+ log.Infof(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\nvar target linux.XTEntryTarget\n@@ -395,6 +397,7 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\ncase \"\":\n// Standard target.\nif len(optVal) < linux.SizeOfXTStandardTarget {\n+ log.Infof(\"netfilter.SetEntries: optVal has insufficient size for standard target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\nvar target linux.XTStandardTarget\n@@ -420,6 +423,7 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\ncase errorTargetName:\n// Error target.\nif len(optVal) < linux.SizeOfXTErrorTarget {\n+ log.Infof(\"netfilter.SetEntries: optVal has insufficient size for error target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\nvar target linux.XTErrorTarget\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -326,7 +326,7 @@ func AddressAndFamily(sfamily int, addr []byte, strict bool) (tcpip.FullAddress,\n}\nfamily := usermem.ByteOrder.Uint16(addr)\n- if family != uint16(sfamily) && (!strict && family != linux.AF_UNSPEC) {\n+ if family != uint16(sfamily) && (strict || family != linux.AF_UNSPEC) {\nreturn tcpip.FullAddress{}, family, syserr.ErrAddressFamilyNotSupported\n}\n@@ -1357,7 +1357,8 @@ func (s *SocketOperations) SetSockOpt(t *kernel.Task, level int, name int, optVa\n}\nif s.skType == linux.SOCK_RAW && level == linux.IPPROTO_IP {\n- if name == linux.IPT_SO_SET_REPLACE {\n+ switch name {\n+ case linux.IPT_SO_SET_REPLACE:\nif len(optVal) < linux.SizeOfIPTReplace {\nreturn syserr.ErrInvalidArgument\n}\n@@ -1371,7 +1372,8 @@ func (s *SocketOperations) SetSockOpt(t *kernel.Task, level int, name int, optVa\nreturn err\n}\nreturn nil\n- } else if name == linux.IPT_SO_SET_ADD_COUNTERS {\n+\n+ case linux.IPT_SO_SET_ADD_COUNTERS:\n// TODO(gvisor.dev/issue/170): Counter support.\nreturn nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_socket.go", "new_path": "pkg/sentry/syscalls/linux/sys_socket.go", "diff": "@@ -41,7 +41,7 @@ const maxListenBacklog = 1024\nconst maxAddrLen = 200\n// maxOptLen is the maximum sockopt parameter length we're willing to accept.\n-const maxOptLen = 1024\n+const maxOptLen = 1024 * 8\n// maxControlLen is the maximum length of the msghdr.msg_control buffer we're\n// willing to accept. Note that this limit is smaller than Linux, which allows\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "@@ -34,7 +34,7 @@ func (UnconditionalDropTarget) Action(packet buffer.VectorisedView) (Verdict, st\nreturn Drop, \"\"\n}\n-// PanicTarget just panics.\n+// PanicTarget just panics. It represents a target that should be unreachable.\ntype PanicTarget struct{}\n// Actions implements Target.Action.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -107,20 +107,19 @@ type IPTables struct {\nPriorities map[Hook][]string\n}\n-// A Table defines a set of chains and hooks into the network stack. The\n-// currently supported tables are:\n-// * nat\n-// * mangle\n+// A Table defines a set of chains and hooks into the network stack. It is\n+// really just a list of rules with some metadata for entrypoints and such.\ntype Table struct {\n- // A table is just a list of rules with some entrypoints.\n+ // Rules holds the rules that make up the table.\nRules []Rule\n+ // BuiltinChains maps builtin chains to their entrypoints.\nBuiltinChains map[Hook]int\n+ // Underflows maps builtin chains to their underflow point (i.e. the\n+ // rule to execute if the chain returns without a verdict).\nUnderflows map[Hook]int\n- // DefaultTargets map[Hook]int\n-\n// UserChains holds user-defined chains for the keyed by name. Users\n// can give their chains arbitrary names.\nUserChains map[string]int\n@@ -149,21 +148,6 @@ func (table *Table) SetMetadata(metadata interface{}) {\ntable.metadata = metadata\n}\n-//// A Chain defines a list of rules for packet processing. When a packet\n-//// traverses a chain, it is checked against each rule until either a rule\n-//// returns a verdict or the chain ends.\n-////\n-//// By convention, builtin chains end with a rule that matches everything and\n-//// returns either Accept or Drop. User-defined chains end with Return. These\n-//// aren't strictly necessary here, but the iptables tool writes tables this way.\n-//type Chain struct {\n-// // Name is the chain name.\n-// Name string\n-\n-// // Rules is the list of rules to traverse.\n-// Rules []Rule\n-//}\n-\n// A Rule is a packet processing rule. It consists of two pieces. First it\n// contains zero or more matchers, each of which is a specification of which\n// packets this rule applies to. If there are no matchers in the rule, it\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -43,8 +43,7 @@ func (FilterInputDropUDP) Name() string {\n// ContainerAction implements TestCase.ContainerAction.\nfunc (FilterInputDropUDP) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-j\", \"DROP\"); err != nil {\n- // if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"ACCEPT\"); err != nil {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"ACCEPT\"); err != nil {\nreturn err\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -167,14 +167,14 @@ func TestFilterInputDropUDP(t *testing.T) {\n}\n}\n-// func TestFilterInputDropUDPPort(t *testing.T) {\n-// if err := singleTest(FilterInputDropUDPPort{}); err != nil {\n-// t.Fatal(err)\n-// }\n-// }\n-\n-// func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n-// if err := singleTest(FilterInputDropDifferentUDPPort{}); err != nil {\n-// t.Fatal(err)\n-// }\n-// }\n+func TestFilterInputDropUDPPort(t *testing.T) {\n+ if err := singleTest(FilterInputDropUDPPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n+ if err := singleTest(FilterInputDropDifferentUDPPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Minor fixes to comments and logging
259,891
08.01.2020 12:43:46
28,800
7cebd77806d164a3baec52eaeb05662e8c404967
First commit -- re-adding DROP
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -410,10 +410,7 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\ncase iptables.Accept:\nreturn iptables.UnconditionalAcceptTarget{}, linux.SizeOfXTStandardTarget, nil\ncase iptables.Drop:\n- // TODO(gvisor.dev/issue/170): Return an\n- // iptables.UnconditionalDropTarget to support DROP.\n- log.Infof(\"netfilter DROP is not supported yet.\")\n- return nil, 0, syserr.ErrInvalidArgument\n+ return iptables.UnconditionalDropTarget{}, linux.SizeOfXTStandardTarget, nil\ndefault:\npanic(fmt.Sprintf(\"Unknown verdict: %v\", verdict))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
First commit -- re-adding DROP
259,891
08.01.2020 12:48:17
28,800
447f64c561e6b5893c1bbae7d641187b7aca64ac
Added test for unconditional DROP on the filter INPUT chain
[ { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -31,6 +31,7 @@ func init() {\nRegisterTestCase(FilterInputDropUDP{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropDifferentUDPPort{})\n+ RegisterTestCase(FilterInputDropAll{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -122,3 +123,34 @@ func (FilterInputDropDifferentUDPPort) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropDifferentUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// FilterInputDropAll tests that we can drop all traffic to the INPUT chain.\n+type FilterInputDropAll struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDropAll) Name() string {\n+ return \"FilterInputDropAll\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDropAll) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for All packets on dropPort.\n+ if err := listenUDP(dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"packets should have been dropped, but got a packet\")\n+ } else if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {\n+ return fmt.Errorf(\"error reading: %v\", err)\n+ }\n+\n+ // At this point we know that reading timed out and never received a\n+ // packet.\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDropAll) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, dropPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -177,3 +177,9 @@ func TestFilterInputDropDifferentUDPPort(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\n+func TestFilterInputDropAll(t *testing.T) {\n+ if err := singleTest(FilterInputDropAll{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Added test for unconditional DROP on the filter INPUT chain
259,891
08.01.2020 14:48:47
28,800
b2a881784c8e525c1fea71c6f23663413d107f05
Built dead-simple traversal, but now getting depedency cycle error :'(
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -368,6 +368,10 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\n}\n+ // TODO(gvisor.dev/issue/170): Check the following conditions:\n+ // - There are no loops.\n+ // - There are no chains without an unconditional final rule.\n+\nipt := stack.IPTables()\ntable.SetMetadata(metadata{\nHookEntry: replace.HookEntry,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/BUILD", "new_path": "pkg/tcpip/iptables/BUILD", "diff": "@@ -11,5 +11,7 @@ go_library(\n],\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/iptables\",\nvisibility = [\"//visibility:public\"],\n- deps = [\"//pkg/tcpip/buffer\"],\n+ deps = [\n+ \"//pkg/tcpip\",\n+ ],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "// tool.\npackage iptables\n+import \"github.com/google/netstack/tcpip\"\n+\nconst (\nTablenameNat = \"nat\"\nTablenameMangle = \"mangle\"\n@@ -121,3 +123,60 @@ func EmptyFilterTable() Table {\nUserChains: map[string]int{},\n}\n}\n+\n+// Check runs pkt through the rules for hook. It returns true when the packet\n+// should continue traversing the network stack and false when it should be\n+// dropped.\n+func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n+ // TODO(gvisor.dev/issue/170): A lot of this is uncomplicated because\n+ // we're missing features. Jumps, the call stack, etc. aren't checked\n+ // for yet because we're yet to support them.\n+ log.Infof(\"kevin: iptables.IPTables: checking hook %v\", hook)\n+\n+ // Go through each table containing the hook.\n+ for _, tablename := range it.Priorities[hook] {\n+ verdict := it.checkTable(tablename)\n+ switch verdict {\n+ // TODO: We either got a final verdict or simply continue on.\n+ }\n+ }\n+}\n+\n+func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) bool {\n+ log.Infof(\"kevin: iptables.IPTables: checking table %q\", tablename)\n+ table := it.Tables[tablename]\n+ ruleIdx := table.BuiltinChains[hook]\n+\n+ // Start from ruleIdx and go down until a rule gives us a verdict.\n+ for ruleIdx := table.BuiltinChains[hook]; ruleIdx < len(table.Rules); ruleIdx++ {\n+ verdict := checkRule(hook, pkt, table, ruleIdx)\n+ switch verdict {\n+ case Accept, Drop:\n+ return verdict\n+ case Continue:\n+ continue\n+ case Stolen, Queue, Repeat, None, Jump, Return:\n+ }\n+ }\n+\n+ panic(\"Traversed past the entire list of iptables rules.\")\n+}\n+\n+func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) Verdict {\n+ rule := table.Rules[ruleIdx]\n+ // Go through each rule matcher. If they all match, run\n+ // the rule target.\n+ for _, matcher := range rule.Matchers {\n+ matches, hotdrop := matcher.Match(hook, pkt, \"\")\n+ if hotdrop {\n+ return Drop\n+ }\n+ if !matches {\n+ return Continue\n+ }\n+ }\n+\n+ // All the matchers matched, so run the target.\n+ verdict, _ := rule.Target.Action(pkt)\n+ return verdict\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -350,6 +350,12 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt tcpip.PacketBuffer) {\n}\npkt.NetworkHeader = headerView[:h.HeaderLength()]\n+ // iptables filtering.\n+ if ok := iptables.Check(iptables.Input, pkt); !ok {\n+ // iptables is telling us to drop the packet.\n+ return\n+ }\n+\nhlen := int(h.HeaderLength())\ntlen := int(h.TotalLength())\npkt.Data.TrimFront(hlen)\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -138,7 +138,7 @@ func (FilterInputDropAll) ContainerAction(ip net.IP) error {\nreturn err\n}\n- // Listen for All packets on dropPort.\n+ // Listen for all packets on dropPort.\nif err := listenUDP(dropPort, sendloopDuration); err == nil {\nreturn fmt.Errorf(\"packets should have been dropped, but got a packet\")\n} else if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() {\n" } ]
Go
Apache License 2.0
google/gvisor
Built dead-simple traversal, but now getting depedency cycle error :'(
259,942
08.01.2020 14:49:12
28,800
e21c5840569155d39e8e11ac18cee99bc6d67469
Combine various Create*NIC methods into CreateNICWithOptions.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "@@ -2500,9 +2500,9 @@ func TestAutoGenAddrWithOpaqueIID(t *testing.T) {\nSecretKey: secretKey,\n},\n})\n-\n- if err := s.CreateNamedNIC(nicID, nicName, e); err != nil {\n- t.Fatalf(\"CreateNamedNIC(%d, %q, _) = %s\", nicID, nicName, err)\n+ opts := stack.NICOptions{Name: nicName}\n+ if err := s.CreateNICWithOptions(nicID, e, opts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(%d, _, %+v, _) = %s\", nicID, opts, err)\n}\nexpectAutoGenAddrEvent := func(addr tcpip.AddressWithPrefix, eventType ndpAutoGenAddrEventType) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -796,9 +796,21 @@ func (s *Stack) NewPacketEndpoint(cooked bool, netProto tcpip.NetworkProtocolNum\nreturn s.rawFactory.NewPacketEndpoint(s, cooked, netProto, waiterQueue)\n}\n-// createNIC creates a NIC with the provided id and link-layer endpoint, and\n-// optionally enable it.\n-func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled bool) *tcpip.Error {\n+// NICOptions specifies the configuration of a NIC as it is being created.\n+// The zero value creates an enabled, unnamed NIC.\n+type NICOptions struct {\n+ // Name specifies the name of the NIC.\n+ Name string\n+\n+ // Disabled specifies whether to avoid calling Attach on the passed\n+ // LinkEndpoint.\n+ Disabled bool\n+}\n+\n+// CreateNICWithOptions creates a NIC with the provided id, LinkEndpoint, and\n+// NICOptions. See the documentation on type NICOptions for details on how\n+// NICs can be configured.\n+func (s *Stack) CreateNICWithOptions(id tcpip.NICID, ep LinkEndpoint, opts NICOptions) *tcpip.Error {\ns.mu.Lock()\ndefer s.mu.Unlock()\n@@ -807,38 +819,20 @@ func (s *Stack) createNIC(id tcpip.NICID, name string, ep LinkEndpoint, enabled\nreturn tcpip.ErrDuplicateNICID\n}\n- n := newNIC(s, id, name, ep)\n+ n := newNIC(s, id, opts.Name, ep)\ns.nics[id] = n\n- if enabled {\n+ if !opts.Disabled {\nreturn n.enable()\n}\nreturn nil\n}\n-// CreateNIC creates a NIC with the provided id and link-layer endpoint.\n+// CreateNIC creates a NIC with the provided id and LinkEndpoint and calls\n+// `LinkEndpoint.Attach` to start delivering packets to it.\nfunc (s *Stack) CreateNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, \"\", ep, true)\n-}\n-\n-// CreateNamedNIC creates a NIC with the provided id and link-layer endpoint,\n-// and a human-readable name.\n-func (s *Stack) CreateNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, name, ep, true)\n-}\n-\n-// CreateDisabledNIC creates a NIC with the provided id and link-layer endpoint,\n-// but leave it disable. Stack.EnableNIC must be called before the link-layer\n-// endpoint starts delivering packets to it.\n-func (s *Stack) CreateDisabledNIC(id tcpip.NICID, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, \"\", ep, false)\n-}\n-\n-// CreateDisabledNamedNIC is a combination of CreateNamedNIC and\n-// CreateDisabledNIC.\n-func (s *Stack) CreateDisabledNamedNIC(id tcpip.NICID, name string, ep LinkEndpoint) *tcpip.Error {\n- return s.createNIC(id, name, ep, false)\n+ return s.CreateNICWithOptions(id, ep, NICOptions{})\n}\n// EnableNIC enables the given NIC so that the link-layer endpoint can start\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2097,8 +2097,9 @@ func TestNICAutoGenAddrWithOpaque(t *testing.T) {\ne := channel.New(10, 1280, test.linkAddr)\ns := stack.New(opts)\n- if err := s.CreateNamedNIC(nicID, test.nicName, e); err != nil {\n- t.Fatalf(\"CreateNamedNIC(%d, %q, _) = %s\", nicID, test.nicName, err)\n+ nicOpts := stack.NICOptions{Name: test.nicName}\n+ if err := s.CreateNICWithOptions(nicID, e, nicOpts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(%d, _, %+v) = %s\", nicID, opts, err)\n}\naddr, err := s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n@@ -2156,8 +2157,9 @@ func TestNoLinkLocalAutoGenForLoopbackNIC(t *testing.T) {\ne := loopback.New()\ns := stack.New(opts)\n- if err := s.CreateNamedNIC(nicID, nicName, e); err != nil {\n- t.Fatalf(\"CreateNamedNIC(%d, %q, _) = %s\", nicID, nicName, err)\n+ nicOpts := stack.NICOptions{Name: nicName}\n+ if err := s.CreateNICWithOptions(nicID, e, nicOpts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(%d, _, %+v) = %s\", nicID, nicOpts, err)\n}\naddr, err := s.GetMainNICAddress(nicID, header.IPv6ProtocolNumber)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer_test.go", "new_path": "pkg/tcpip/stack/transport_demuxer_test.go", "diff": "@@ -80,8 +80,9 @@ func newDualTestContextMultiNic(t *testing.T, mtu uint32, linkEpNames []string)\nfor i, linkEpName := range linkEpNames {\nchannelEP := channel.New(256, mtu, \"\")\nnicID := tcpip.NICID(i + 1)\n- if err := s.CreateNamedNIC(nicID, linkEpName, channelEP); err != nil {\n- t.Fatalf(\"CreateNIC failed: %v\", err)\n+ opts := stack.NICOptions{Name: linkEpName}\n+ if err := s.CreateNICWithOptions(nicID, channelEP, opts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\nlinkEPs[linkEpName] = channelEP\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -3794,8 +3794,9 @@ func TestBindToDeviceOption(t *testing.T) {\n}\ndefer ep.Close()\n- if err := s.CreateNamedNIC(321, \"my_device\", loopback.New()); err != nil {\n- t.Errorf(\"CreateNamedNIC failed: %v\", err)\n+ opts := stack.NICOptions{Name: \"my_device\"}\n+ if err := s.CreateNICWithOptions(321, loopback.New(), opts); err != nil {\n+ t.Errorf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\n// Make an nameless NIC.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "new_path": "pkg/tcpip/transport/tcp/testing/context/context.go", "diff": "@@ -158,15 +158,17 @@ func New(t *testing.T, mtu uint32) *Context {\nif testing.Verbose() {\nwep = sniffer.New(ep)\n}\n- if err := s.CreateNamedNIC(1, \"nic1\", wep); err != nil {\n- t.Fatalf(\"CreateNIC failed: %v\", err)\n+ opts := stack.NICOptions{Name: \"nic1\"}\n+ if err := s.CreateNICWithOptions(1, wep, opts); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\nwep2 := stack.LinkEndpoint(channel.New(1000, mtu, \"\"))\nif testing.Verbose() {\nwep2 = sniffer.New(channel.New(1000, mtu, \"\"))\n}\n- if err := s.CreateNamedNIC(2, \"nic2\", wep2); err != nil {\n- t.Fatalf(\"CreateNIC failed: %v\", err)\n+ opts2 := stack.NICOptions{Name: \"nic2\"}\n+ if err := s.CreateNICWithOptions(2, wep2, opts2); err != nil {\n+ t.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts2, err)\n}\nif err := s.AddAddress(1, ipv4.ProtocolNumber, StackAddr); err != nil {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -508,8 +508,9 @@ func TestBindToDeviceOption(t *testing.T) {\n}\ndefer ep.Close()\n- if err := s.CreateNamedNIC(321, \"my_device\", loopback.New()); err != nil {\n- t.Errorf(\"CreateNamedNIC failed: %v\", err)\n+ opts := stack.NICOptions{Name: \"my_device\"}\n+ if err := s.CreateNICWithOptions(321, loopback.New(), opts); err != nil {\n+ t.Errorf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\n// Make an nameless NIC.\n" }, { "change_type": "MODIFY", "old_path": "runsc/boot/network.go", "new_path": "runsc/boot/network.go", "diff": "@@ -219,8 +219,9 @@ func (n *Network) CreateLinksAndRoutes(args *CreateLinksAndRoutesArgs, _ *struct\n// createNICWithAddrs creates a NIC in the network stack and adds the given\n// addresses.\nfunc (n *Network) createNICWithAddrs(id tcpip.NICID, name string, ep stack.LinkEndpoint, addrs []net.IP) error {\n- if err := n.Stack.CreateNamedNIC(id, name, sniffer.New(ep)); err != nil {\n- return fmt.Errorf(\"CreateNamedNIC(%v, %v, %v) failed: %v\", id, name, ep, err)\n+ opts := stack.NICOptions{Name: name}\n+ if err := n.Stack.CreateNICWithOptions(id, sniffer.New(ep), opts); err != nil {\n+ return fmt.Errorf(\"CreateNICWithOptions(%d, _, %+v) failed: %v\", id, opts, err)\n}\n// Always start with an arp address for the NIC.\n" } ]
Go
Apache License 2.0
google/gvisor
Combine various Create*NIC methods into CreateNICWithOptions. PiperOrigin-RevId: 288779416
259,891
08.01.2020 15:57:25
28,800
0999ae8b34d83a4b2ea8342d0459c8131c35d6e1
Getting a panic when running tests. For some reason the filter table is ending up with the wrong chains and is indexing -1 into rules.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -25,7 +25,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n- \"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -45,7 +44,7 @@ type metadata struct {\n}\n// GetInfo returns information about iptables.\n-func GetInfo(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr) (linux.IPTGetinfo, *syserr.Error) {\n+func GetInfo(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr) (linux.IPTGetinfo, *syserr.Error) {\n// Read in the struct and table name.\nvar info linux.IPTGetinfo\nif _, err := t.CopyIn(outPtr, &info); err != nil {\n@@ -53,7 +52,7 @@ func GetInfo(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr) (linux.IPTG\n}\n// Find the appropriate table.\n- table, err := findTable(ep, info.Name.String())\n+ table, err := findTable(stack, info.Name.String())\nif err != nil {\nreturn linux.IPTGetinfo{}, err\n}\n@@ -76,7 +75,7 @@ func GetInfo(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr) (linux.IPTG\n}\n// GetEntries returns netstack's iptables rules encoded for the iptables tool.\n-func GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen int) (linux.KernelIPTGetEntries, *syserr.Error) {\n+func GetEntries(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr, outLen int) (linux.KernelIPTGetEntries, *syserr.Error) {\n// Read in the struct and table name.\nvar userEntries linux.IPTGetEntries\nif _, err := t.CopyIn(outPtr, &userEntries); err != nil {\n@@ -84,7 +83,7 @@ func GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen i\n}\n// Find the appropriate table.\n- table, err := findTable(ep, userEntries.Name.String())\n+ table, err := findTable(stack, userEntries.Name.String())\nif err != nil {\nreturn linux.KernelIPTGetEntries{}, err\n}\n@@ -103,12 +102,8 @@ func GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen i\nreturn entries, nil\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+func findTable(stack *stack.Stack, tableName string) (iptables.Table, *syserr.Error) {\n+ table, ok := stack.IPTables().Tables[tableName]\nif !ok {\nreturn iptables.Table{}, syserr.ErrInvalidArgument\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -826,7 +826,11 @@ func (s *SocketOperations) GetSockOpt(t *kernel.Task, level, name int, outPtr us\nreturn nil, syserr.ErrInvalidArgument\n}\n- info, err := netfilter.GetInfo(t, s.Endpoint, outPtr)\n+ stack := inet.StackFromContext(t)\n+ if stack == nil {\n+ return nil, syserr.ErrNoDevice\n+ }\n+ info, err := netfilter.GetInfo(t, stack.(*Stack).Stack, outPtr)\nif err != nil {\nreturn nil, err\n}\n@@ -837,7 +841,11 @@ func (s *SocketOperations) GetSockOpt(t *kernel.Task, level, name int, outPtr us\nreturn nil, syserr.ErrInvalidArgument\n}\n- entries, err := netfilter.GetEntries(t, s.Endpoint, outPtr, outLen)\n+ stack := inet.StackFromContext(t)\n+ if stack == nil {\n+ return nil, syserr.ErrNoDevice\n+ }\n+ entries, err := netfilter.GetEntries(t, stack.(*Stack).Stack, outPtr, outLen)\nif err != nil {\nreturn nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -15,7 +15,6 @@ go_library(\nvisibility = [\"//visibility:public\"],\ndeps = [\n\"//pkg/tcpip/buffer\",\n- \"//pkg/tcpip/iptables\",\n\"//pkg/waiter\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/BUILD", "new_path": "pkg/tcpip/iptables/BUILD", "diff": "@@ -12,6 +12,7 @@ go_library(\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/iptables\",\nvisibility = [\"//visibility:public\"],\ndeps = [\n+ \"//pkg/log\",\n\"//pkg/tcpip\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "// tool.\npackage iptables\n-import \"github.com/google/netstack/tcpip\"\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+)\nconst (\nTablenameNat = \"nat\"\n@@ -135,31 +140,47 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n// Go through each table containing the hook.\nfor _, tablename := range it.Priorities[hook] {\n- verdict := it.checkTable(tablename)\n+ verdict := it.checkTable(hook, pkt, tablename)\nswitch verdict {\n- // TODO: We either got a final verdict or simply continue on.\n+ // If the table returns Accept, move on to the next table.\n+ case Accept:\n+ continue\n+ // The Drop verdict is final.\n+ case Drop:\n+ log.Infof(\"kevin: Packet dropped\")\n+ return false\n+ case Stolen, Queue, Repeat, None, Jump, Return, Continue:\n+ panic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\n}\n}\n+\n+ // Every table returned Accept.\n+ log.Infof(\"kevin: Packet accepted\")\n+ return true\n}\n-func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) bool {\n+func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) Verdict {\nlog.Infof(\"kevin: iptables.IPTables: checking table %q\", tablename)\ntable := it.Tables[tablename]\n- ruleIdx := table.BuiltinChains[hook]\n+ log.Infof(\"kevin: iptables.IPTables: table %+v\", table)\n// Start from ruleIdx and go down until a rule gives us a verdict.\nfor ruleIdx := table.BuiltinChains[hook]; ruleIdx < len(table.Rules); ruleIdx++ {\n- verdict := checkRule(hook, pkt, table, ruleIdx)\n+ verdict := it.checkRule(hook, pkt, table, ruleIdx)\nswitch verdict {\n+ // For either of these cases, this table is done with the\n+ // packet.\ncase Accept, Drop:\nreturn verdict\n+ // Continue traversing the rules of the table.\ncase Continue:\ncontinue\ncase Stolen, Queue, Repeat, None, Jump, Return:\n+ panic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\n}\n}\n- panic(\"Traversed past the entire list of iptables rules.\")\n+ panic(fmt.Sprintf(\"Traversed past the entire list of iptables rules in table %q.\", tablename))\n}\nfunc (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) Verdict {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "package iptables\n-import \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+import \"gvisor.dev/gvisor/pkg/tcpip\"\n// UnconditionalAcceptTarget accepts all packets.\ntype UnconditionalAcceptTarget struct{}\n// Action implements Target.Action.\n-func (UnconditionalAcceptTarget) Action(packet buffer.VectorisedView) (Verdict, string) {\n+func (UnconditionalAcceptTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\nreturn Accept, \"\"\n}\n@@ -30,7 +30,7 @@ func (UnconditionalAcceptTarget) Action(packet buffer.VectorisedView) (Verdict,\ntype UnconditionalDropTarget struct{}\n// Action implements Target.Action.\n-func (UnconditionalDropTarget) Action(packet buffer.VectorisedView) (Verdict, string) {\n+func (UnconditionalDropTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\nreturn Drop, \"\"\n}\n@@ -38,6 +38,6 @@ func (UnconditionalDropTarget) Action(packet buffer.VectorisedView) (Verdict, st\ntype PanicTarget struct{}\n// Actions implements Target.Action.\n-func (PanicTarget) Action(packet buffer.VectorisedView) (Verdict, string) {\n+func (PanicTarget) Action(packet tcpip.PacketBuffer) (Verdict, string) {\npanic(\"PanicTarget triggered.\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "package iptables\n-import (\n- \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n-)\n+import \"gvisor.dev/gvisor/pkg/tcpip\"\n// A Hook specifies one of the hooks built into the network stack.\n//\n@@ -165,7 +163,7 @@ type Matcher interface {\n// Match returns whether the packet matches and whether the packet\n// should be \"hotdropped\", i.e. dropped immediately. This is usually\n// used for suspicious packets.\n- Match(hook Hook, packet buffer.VectorisedView, interfaceName string) (matches bool, hotdrop bool)\n+ Match(hook Hook, packet tcpip.PacketBuffer, interfaceName string) (matches bool, hotdrop bool)\n}\n// A Target is the interface for taking an action for a packet.\n@@ -173,5 +171,5 @@ type Target interface {\n// Action takes an action on the packet and returns a verdict on how\n// traversal should (or should not) continue. If the return value is\n// Jump, it also returns the name of the chain to jump to.\n- Action(packet buffer.VectorisedView) (Verdict, string)\n+ Action(packet tcpip.PacketBuffer) (Verdict, string)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/arp/arp.go", "new_path": "pkg/tcpip/network/arp/arp.go", "diff": "@@ -137,7 +137,7 @@ func (*protocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) {\nreturn tcpip.Address(h.ProtocolAddressSender()), ProtocolAddress\n}\n-func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, sender stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {\n+func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, sender stack.LinkEndpoint, st *stack.Stack) (stack.NetworkEndpoint, *tcpip.Error) {\nif addrWithPrefix.Address != ProtocolAddress {\nreturn nil, tcpip.ErrBadLocalAddress\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/BUILD", "new_path": "pkg/tcpip/network/ipv4/BUILD", "diff": "@@ -15,6 +15,7 @@ go_library(\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n\"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/iptables\",\n\"//pkg/tcpip/network/fragmentation\",\n\"//pkg/tcpip/network/hash\",\n\"//pkg/tcpip/stack\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -26,6 +26,7 @@ import (\n\"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n\"gvisor.dev/gvisor/pkg/tcpip/header\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/fragmentation\"\n\"gvisor.dev/gvisor/pkg/tcpip/network/hash\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n@@ -54,10 +55,11 @@ type endpoint struct {\ndispatcher stack.TransportDispatcher\nfragmentation *fragmentation.Fragmentation\nprotocol *protocol\n+ stack *stack.Stack\n}\n// NewEndpoint creates a new ipv4 endpoint.\n-func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {\n+func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint, st *stack.Stack) (stack.NetworkEndpoint, *tcpip.Error) {\ne := &endpoint{\nnicID: nicID,\nid: stack.NetworkEndpointID{LocalAddress: addrWithPrefix.Address},\n@@ -66,6 +68,7 @@ func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWi\ndispatcher: dispatcher,\nfragmentation: fragmentation.NewFragmentation(fragmentation.HighFragThreshold, fragmentation.LowFragThreshold, fragmentation.DefaultReassembleTimeout),\nprotocol: p,\n+ stack: st,\n}\nreturn e, nil\n@@ -351,7 +354,8 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt tcpip.PacketBuffer) {\npkt.NetworkHeader = headerView[:h.HeaderLength()]\n// iptables filtering.\n- if ok := iptables.Check(iptables.Input, pkt); !ok {\n+ ipt := e.stack.IPTables()\n+ if ok := ipt.Check(iptables.Input, pkt); !ok {\n// iptables is telling us to drop the packet.\nreturn\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ipv6.go", "new_path": "pkg/tcpip/network/ipv6/ipv6.go", "diff": "@@ -221,7 +221,7 @@ func (*protocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) {\n}\n// NewEndpoint creates a new ipv6 endpoint.\n-func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {\n+func (p *protocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint, st *stack.Stack) (stack.NetworkEndpoint, *tcpip.Error) {\nreturn &endpoint{\nnicID: nicID,\nid: stack.NetworkEndpointID{LocalAddress: addrWithPrefix.Address},\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -467,7 +467,7 @@ func (n *NIC) addAddressLocked(protocolAddress tcpip.ProtocolAddress, peb Primar\n}\n// Create the new network endpoint.\n- ep, err := netProto.NewEndpoint(n.id, protocolAddress.AddressWithPrefix, n.stack, n, n.linkEP)\n+ ep, err := netProto.NewEndpoint(n.id, protocolAddress.AddressWithPrefix, n.stack, n, n.linkEP, n.stack)\nif err != nil {\nreturn nil, err\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/registration.go", "new_path": "pkg/tcpip/stack/registration.go", "diff": "@@ -282,7 +282,7 @@ type NetworkProtocol interface {\nParseAddresses(v buffer.View) (src, dst tcpip.Address)\n// NewEndpoint creates a new endpoint of this protocol.\n- NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache LinkAddressCache, dispatcher TransportDispatcher, sender LinkEndpoint) (NetworkEndpoint, *tcpip.Error)\n+ NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache LinkAddressCache, dispatcher TransportDispatcher, sender LinkEndpoint, st *Stack) (NetworkEndpoint, *tcpip.Error)\n// SetOption allows enabling/disabling protocol specific features.\n// SetOption returns an error if the option is not supported or the\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -40,7 +40,6 @@ import (\n\"time\"\n\"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n- \"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/waiter\"\n)\n@@ -446,9 +445,6 @@ type Endpoint interface {\n// NOTE: This method is a no-op for sockets other than TCP.\nModerateRecvBuf(copied int)\n- // IPTables returns the iptables for this endpoint's stack.\n- IPTables() (iptables.IPTables, error)\n-\n// Info returns a copy to the transport endpoint info.\nInfo() EndpointInfo\n" } ]
Go
Apache License 2.0
google/gvisor
Getting a panic when running tests. For some reason the filter table is ending up with the wrong chains and is indexing -1 into rules.
259,992
08.01.2020 15:40:00
28,800
1c2420146777de5b5727f69331b50be1b57a3351
Github bug reviver For everyone's joy, this is a tool that reopens issues that have been closed, but are still referenced by TODOs in the code. The idea is to run it in Kokoro nightly. Kokoro changes are coming up next.
[ { "change_type": "MODIFY", "old_path": "WORKSPACE", "new_path": "WORKSPACE", "diff": "@@ -290,6 +290,27 @@ go_repository(\nversion = \"v1.3.1\",\n)\n+go_repository(\n+ name = \"com_github_google_go-github\",\n+ importpath = \"github.com/google/go-github\",\n+ sum = \"h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=\",\n+ version = \"v17.0.0\",\n+)\n+\n+go_repository(\n+ name = \"org_golang_x_oauth2\",\n+ importpath = \"golang.org/x/oauth2\",\n+ sum = \"h1:pE8b58s1HRDMi8RDc79m0HISf9D4TzseP40cEA6IGfs=\",\n+ version = \"v0.0.0-20191202225959-858c2ad4c8b6\",\n+)\n+\n+go_repository(\n+ name = \"com_github_google_go-querystring\",\n+ importpath = \"github.com/google/go-querystring\",\n+ sum = \"h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=\",\n+ version = \"v1.0.0\",\n+)\n+\n# System Call test dependencies.\nhttp_archive(\nname = \"com_google_absl\",\n" }, { "change_type": "MODIFY", "old_path": "go.mod", "new_path": "go.mod", "diff": "@@ -9,6 +9,7 @@ require (\ngithub.com/golang/protobuf v1.3.1\ngithub.com/google/btree v1.0.0\ngithub.com/google/go-cmp v0.2.0\n+ github.com/google/go-github/v28 v28.1.1\ngithub.com/google/subcommands v0.0.0-20190508160503-636abe8753b8\ngithub.com/google/uuid v0.0.0-20171129191014-dec09d789f3d\ngithub.com/kr/pty v1.1.1\n@@ -17,5 +18,6 @@ require (\ngithub.com/vishvananda/netlink v1.0.1-0.20190318003149-adb577d4a45e\ngithub.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936\ngolang.org/x/net v0.0.0-20190311183353-d8887717615a\n+ golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a\n)\n" }, { "change_type": "MODIFY", "old_path": "go.sum", "new_path": "go.sum", "diff": "@@ -4,6 +4,7 @@ github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFU\ngithub.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=\ngithub.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=\ngithub.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=\n+github.com/google/go-github/v28 v28.1.1/go.mod h1:bsqJWQX05omyWVmc00nEUql9mhQyv38lDZ8kPZcQVoM=\ngithub.com/google/subcommands v0.0.0-20190508160503-636abe8753b8/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=\ngithub.com/google/uuid v0.0.0-20171129191014-dec09d789f3d/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\n@@ -13,6 +14,7 @@ github.com/vishvananda/netlink v1.0.1-0.20190318003149-adb577d4a45e/go.mod h1:+S\ngithub.com/vishvananda/netns v0.0.0-20171111001504-be1fbeda1936/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\n+golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/BUILD", "diff": "+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_binary\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_binary(\n+ name = \"issue_reviver\",\n+ srcs = [\"main.go\"],\n+ deps = [\n+ \"//tools/issue_reviver/github\",\n+ \"//tools/issue_reviver/reviver\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/github/BUILD", "diff": "+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"github\",\n+ srcs = [\"github.go\"],\n+ importpath = \"gvisor.dev/gvisor/tools/issue_reviver/github\",\n+ visibility = [\n+ \"//tools/issue_reviver:__subpackages__\",\n+ ],\n+ deps = [\n+ \"//tools/issue_reviver/reviver\",\n+ \"@com_github_google_go-github//github:go_default_library\",\n+ \"@org_golang_x_oauth2//:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/github/github.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 github implements reviver.Bugger interface on top of Github issues.\n+package github\n+\n+import (\n+ \"context\"\n+ \"fmt\"\n+ \"strconv\"\n+ \"strings\"\n+ \"time\"\n+\n+ \"github.com/google/go-github/github\"\n+ \"golang.org/x/oauth2\"\n+ \"gvisor.dev/gvisor/tools/issue_reviver/reviver\"\n+)\n+\n+// Bugger implements reviver.Bugger interface for github issues.\n+type Bugger struct {\n+ owner string\n+ repo string\n+ dryRun bool\n+\n+ client *github.Client\n+ issues map[int]*github.Issue\n+}\n+\n+// NewBugger creates a new Bugger.\n+func NewBugger(token, owner, repo string, dryRun bool) (*Bugger, error) {\n+ b := &Bugger{\n+ owner: owner,\n+ repo: repo,\n+ dryRun: dryRun,\n+ issues: map[int]*github.Issue{},\n+ }\n+ if err := b.load(token); err != nil {\n+ return nil, err\n+ }\n+ return b, nil\n+}\n+\n+func (b *Bugger) load(token string) error {\n+ ctx := context.Background()\n+ if len(token) == 0 {\n+ fmt.Print(\"No OAUTH token provided, using unauthenticated account.\\n\")\n+ b.client = github.NewClient(nil)\n+ } else {\n+ ts := oauth2.StaticTokenSource(\n+ &oauth2.Token{AccessToken: token},\n+ )\n+ tc := oauth2.NewClient(ctx, ts)\n+ b.client = github.NewClient(tc)\n+ }\n+\n+ err := processAllPages(func(listOpts github.ListOptions) (*github.Response, error) {\n+ opts := &github.IssueListByRepoOptions{State: \"open\", ListOptions: listOpts}\n+ tmps, resp, err := b.client.Issues.ListByRepo(ctx, b.owner, b.repo, opts)\n+ if err != nil {\n+ return resp, err\n+ }\n+ for _, issue := range tmps {\n+ b.issues[issue.GetNumber()] = issue\n+ }\n+ return resp, nil\n+ })\n+ if err != nil {\n+ return err\n+ }\n+\n+ fmt.Printf(\"Loaded %d issues from github.com/%s/%s\\n\", len(b.issues), b.owner, b.repo)\n+ return nil\n+}\n+\n+// Activate implements reviver.Bugger.\n+func (b *Bugger) Activate(todo *reviver.Todo) (bool, error) {\n+ const prefix = \"gvisor.dev/issue/\"\n+\n+ // First check if I can handle the TODO.\n+ idStr := strings.TrimPrefix(todo.Issue, prefix)\n+ if len(todo.Issue) == len(idStr) {\n+ return false, nil\n+ }\n+\n+ id, err := strconv.Atoi(idStr)\n+ if err != nil {\n+ return true, err\n+ }\n+\n+ // Check against active issues cache.\n+ if _, ok := b.issues[id]; ok {\n+ fmt.Printf(\"%q is active: OK\\n\", todo.Issue)\n+ return true, nil\n+ }\n+\n+ fmt.Printf(\"%q is not active: reopening issue %d\\n\", todo.Issue, id)\n+\n+ // Format comment with TODO locations and search link.\n+ comment := strings.Builder{}\n+ fmt.Fprintln(&comment, \"There are TODOs still referencing this issue:\")\n+ for _, l := range todo.Locations {\n+ fmt.Fprintf(&comment,\n+ \"1. [%s:%d](https://github.com/%s/%s/blob/HEAD/%s#%d): %s\\n\",\n+ l.File, l.Line, b.owner, b.repo, l.File, l.Line, l.Comment)\n+ }\n+ fmt.Fprintf(&comment,\n+ \"\\n\\nSearch [TODO](https://github.com/%s/%s/search?q=%%22%s%d%%22)\", b.owner, b.repo, prefix, id)\n+\n+ if b.dryRun {\n+ fmt.Printf(\"[dry-run: skipping change to issue %d]\\n%s\\n=======================\\n\", id, comment.String())\n+ return true, nil\n+ }\n+\n+ ctx := context.Background()\n+ req := &github.IssueRequest{State: github.String(\"open\")}\n+ _, _, err = b.client.Issues.Edit(ctx, b.owner, b.repo, id, req)\n+ if err != nil {\n+ return true, fmt.Errorf(\"failed to reactivate issue %d: %v\", id, err)\n+ }\n+\n+ cmt := &github.IssueComment{\n+ Body: github.String(comment.String()),\n+ Reactions: &github.Reactions{Confused: github.Int(1)},\n+ }\n+ if _, _, err := b.client.Issues.CreateComment(ctx, b.owner, b.repo, id, cmt); err != nil {\n+ return true, fmt.Errorf(\"failed to add comment to issue %d: %v\", id, err)\n+ }\n+\n+ return true, nil\n+}\n+\n+func processAllPages(fn func(github.ListOptions) (*github.Response, error)) error {\n+ opts := github.ListOptions{PerPage: 1000}\n+ for {\n+ resp, err := fn(opts)\n+ if err != nil {\n+ if rateErr, ok := err.(*github.RateLimitError); ok {\n+ duration := rateErr.Rate.Reset.Sub(time.Now())\n+ if duration > 5*time.Minute {\n+ return fmt.Errorf(\"Rate limited for too long: %v\", duration)\n+ }\n+ fmt.Printf(\"Rate limited, sleeping for: %v\\n\", duration)\n+ time.Sleep(duration)\n+ continue\n+ }\n+ return err\n+ }\n+ if resp.NextPage == 0 {\n+ return nil\n+ }\n+ opts.Page = resp.NextPage\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/main.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 main is the entry point for issue_reviver.\n+package main\n+\n+import (\n+ \"flag\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+\n+ \"gvisor.dev/gvisor/tools/issue_reviver/github\"\n+ \"gvisor.dev/gvisor/tools/issue_reviver/reviver\"\n+)\n+\n+var (\n+ owner string\n+ repo string\n+ tokenFile string\n+ path string\n+ dryRun bool\n+)\n+\n+// Keep the options simple for now. Supports only a single path and repo.\n+func init() {\n+ flag.StringVar(&owner, \"owner\", \"google\", \"Github project org/owner to look for issues\")\n+ flag.StringVar(&repo, \"repo\", \"gvisor\", \"Github repo to look for issues\")\n+ flag.StringVar(&tokenFile, \"oauth-token-file\", \"\", \"Path to file containing the OAUTH token to be used as credential to github\")\n+ flag.StringVar(&path, \"path\", \"\", \"Path to scan for TODOs\")\n+ flag.BoolVar(&dryRun, \"dry-run\", false, \"If set to true, no changes are made to issues\")\n+}\n+\n+func main() {\n+ flag.Parse()\n+\n+ // Check for mandatory parameters.\n+ if len(owner) == 0 {\n+ fmt.Println(\"missing --owner option.\")\n+ flag.Usage()\n+ os.Exit(1)\n+ }\n+ if len(repo) == 0 {\n+ fmt.Println(\"missing --repo option.\")\n+ flag.Usage()\n+ os.Exit(1)\n+ }\n+ if len(path) == 0 {\n+ fmt.Println(\"missing --path option.\")\n+ flag.Usage()\n+ os.Exit(1)\n+ }\n+\n+ // Token is passed as a file so it doesn't show up in command line arguments.\n+ var token string\n+ if len(tokenFile) != 0 {\n+ bytes, err := ioutil.ReadFile(tokenFile)\n+ if err != nil {\n+ fmt.Println(err.Error())\n+ os.Exit(1)\n+ }\n+ token = string(bytes)\n+ }\n+\n+ bugger, err := github.NewBugger(token, owner, repo, dryRun)\n+ if err != nil {\n+ fmt.Fprintln(os.Stderr, \"Error getting github issues:\", err)\n+ os.Exit(1)\n+ }\n+ rev := reviver.New([]string{path}, []reviver.Bugger{bugger})\n+ if errs := rev.Run(); len(errs) > 0 {\n+ fmt.Fprintf(os.Stderr, \"Encountered %d errors:\\n\", len(errs))\n+ for _, err := range errs {\n+ fmt.Fprintf(os.Stderr, \"\\t%v\\n\", err)\n+ }\n+ os.Exit(1)\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/reviver/BUILD", "diff": "+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_library\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"reviver\",\n+ srcs = [\"reviver.go\"],\n+ importpath = \"gvisor.dev/gvisor/tools/issue_reviver/reviver\",\n+ visibility = [\n+ \"//tools/issue_reviver:__subpackages__\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"reviver_test\",\n+ size = \"small\",\n+ srcs = [\"reviver_test.go\"],\n+ embed = [\":reviver\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/reviver/reviver.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 reviver scans the code looking for TODOs and pass them to registered\n+// Buggers to ensure TODOs point to active issues.\n+package reviver\n+\n+import (\n+ \"bufio\"\n+ \"fmt\"\n+ \"io/ioutil\"\n+ \"os\"\n+ \"path/filepath\"\n+ \"regexp\"\n+ \"sync\"\n+)\n+\n+// This is how a TODO looks like.\n+var regexTodo = regexp.MustCompile(`(\\/\\/|#)\\s*(TODO|FIXME)\\(([a-zA-Z0-9.\\/]+)\\):\\s*(.+)`)\n+\n+// Bugger interface is called for every TODO found in the code. If it can handle\n+// the TODO, it must return true. If it returns false, the next Bugger is\n+// called. If no Bugger handles the TODO, it's dropped on the floor.\n+type Bugger interface {\n+ Activate(todo *Todo) (bool, error)\n+}\n+\n+// Location saves the location where the TODO was found.\n+type Location struct {\n+ Comment string\n+ File string\n+ Line uint\n+}\n+\n+// Todo represents a unique TODO. There can be several TODOs pointing to the\n+// same issue in the code. They are all grouped together.\n+type Todo struct {\n+ Issue string\n+ Locations []Location\n+}\n+\n+// Reviver scans the given paths for TODOs and calls Buggers to handle them.\n+type Reviver struct {\n+ paths []string\n+ buggers []Bugger\n+\n+ mu sync.Mutex\n+ todos map[string]*Todo\n+ errs []error\n+}\n+\n+// New create a new Reviver.\n+func New(paths []string, buggers []Bugger) *Reviver {\n+ return &Reviver{\n+ paths: paths,\n+ buggers: buggers,\n+ todos: map[string]*Todo{},\n+ }\n+}\n+\n+// Run runs. It returns all errors found during processing, it doesn't stop\n+// on errors.\n+func (r *Reviver) Run() []error {\n+ // Process each directory in parallel.\n+ wg := sync.WaitGroup{}\n+ for _, path := range r.paths {\n+ wg.Add(1)\n+ go func(path string) {\n+ defer wg.Done()\n+ r.processPath(path, &wg)\n+ }(path)\n+ }\n+\n+ wg.Wait()\n+\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+\n+ fmt.Printf(\"Processing %d TODOs (%d errors)...\\n\", len(r.todos), len(r.errs))\n+ dropped := 0\n+ for _, todo := range r.todos {\n+ ok, err := r.processTodo(todo)\n+ if err != nil {\n+ r.errs = append(r.errs, err)\n+ }\n+ if !ok {\n+ dropped++\n+ }\n+ }\n+ fmt.Printf(\"Processed %d TODOs, %d were skipped (%d errors)\\n\", len(r.todos)-dropped, dropped, len(r.errs))\n+\n+ return r.errs\n+}\n+\n+func (r *Reviver) processPath(path string, wg *sync.WaitGroup) {\n+ fmt.Printf(\"Processing dir %q\\n\", path)\n+ fis, err := ioutil.ReadDir(path)\n+ if err != nil {\n+ r.addErr(fmt.Errorf(\"error processing dir %q: %v\", path, err))\n+ return\n+ }\n+\n+ for _, fi := range fis {\n+ childPath := filepath.Join(path, fi.Name())\n+ switch {\n+ case fi.Mode().IsDir():\n+ wg.Add(1)\n+ go func() {\n+ defer wg.Done()\n+ r.processPath(childPath, wg)\n+ }()\n+\n+ case fi.Mode().IsRegular():\n+ file, err := os.Open(childPath)\n+ if err != nil {\n+ r.addErr(err)\n+ continue\n+ }\n+\n+ scanner := bufio.NewScanner(file)\n+ lineno := uint(0)\n+ for scanner.Scan() {\n+ lineno++\n+ line := scanner.Text()\n+ if todo := r.processLine(line, childPath, lineno); todo != nil {\n+ r.addTodo(todo)\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+func (r *Reviver) processLine(line, path string, lineno uint) *Todo {\n+ matches := regexTodo.FindStringSubmatch(line)\n+ if matches == nil {\n+ return nil\n+ }\n+ if len(matches) != 5 {\n+ panic(fmt.Sprintf(\"regex returned wrong matches for %q: %v\", line, matches))\n+ }\n+ return &Todo{\n+ Issue: matches[3],\n+ Locations: []Location{\n+ {\n+ File: path,\n+ Line: lineno,\n+ Comment: matches[4],\n+ },\n+ },\n+ }\n+}\n+\n+func (r *Reviver) addTodo(newTodo *Todo) {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+\n+ if todo := r.todos[newTodo.Issue]; todo == nil {\n+ r.todos[newTodo.Issue] = newTodo\n+ } else {\n+ todo.Locations = append(todo.Locations, newTodo.Locations...)\n+ }\n+}\n+\n+func (r *Reviver) addErr(err error) {\n+ r.mu.Lock()\n+ defer r.mu.Unlock()\n+ r.errs = append(r.errs, err)\n+}\n+\n+func (r *Reviver) processTodo(todo *Todo) (bool, error) {\n+ for _, bugger := range r.buggers {\n+ ok, err := bugger.Activate(todo)\n+ if err != nil {\n+ return false, err\n+ }\n+ if ok {\n+ return true, nil\n+ }\n+ }\n+ return false, nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "tools/issue_reviver/reviver/reviver_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 reviver\n+\n+import (\n+ \"testing\"\n+)\n+\n+func TestProcessLine(t *testing.T) {\n+ for _, tc := range []struct {\n+ line string\n+ want *Todo\n+ }{\n+ {\n+ line: \"// TODO(foobar.com/issue/123): comment, bla. blabla.\",\n+ want: &Todo{\n+ Issue: \"foobar.com/issue/123\",\n+ Locations: []Location{\n+ {Comment: \"comment, bla. blabla.\"},\n+ },\n+ },\n+ },\n+ {\n+ line: \"// FIXME(b/123): internal bug\",\n+ want: &Todo{\n+ Issue: \"b/123\",\n+ Locations: []Location{\n+ {Comment: \"internal bug\"},\n+ },\n+ },\n+ },\n+ {\n+ line: \"TODO(issue): not todo\",\n+ },\n+ {\n+ line: \"FIXME(issue): not todo\",\n+ },\n+ {\n+ line: \"// TODO (issue): not todo\",\n+ },\n+ {\n+ line: \"// TODO(issue) not todo\",\n+ },\n+ {\n+ line: \"// todo(issue): not todo\",\n+ },\n+ {\n+ line: \"// TODO(issue):\",\n+ },\n+ } {\n+ t.Logf(\"Testing: %s\", tc.line)\n+ r := Reviver{}\n+ got := r.processLine(tc.line, \"test\", 0)\n+ if got == nil {\n+ if tc.want != nil {\n+ t.Errorf(\"failed to process line, want: %+v\", tc.want)\n+ }\n+ } else {\n+ if tc.want == nil {\n+ t.Errorf(\"expected error, got: %+v\", got)\n+ continue\n+ }\n+ if got.Issue != tc.want.Issue {\n+ t.Errorf(\"wrong issue, got: %v, want: %v\", got.Issue, tc.want.Issue)\n+ }\n+ if len(got.Locations) != len(tc.want.Locations) {\n+ t.Errorf(\"wrong number of locations, got: %v, want: %v, locations: %+v\", len(got.Locations), len(tc.want.Locations), got.Locations)\n+ }\n+ for i, wantLoc := range tc.want.Locations {\n+ if got.Locations[i].Comment != wantLoc.Comment {\n+ t.Errorf(\"wrong comment, got: %v, want: %v\", got.Locations[i].Comment, wantLoc.Comment)\n+ }\n+ }\n+ }\n+ }\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Github bug reviver For everyone's joy, this is a tool that reopens issues that have been closed, but are still referenced by TODOs in the code. The idea is to run it in Kokoro nightly. Kokoro changes are coming up next. PiperOrigin-RevId: 288789560
260,003
08.01.2020 16:29:12
28,800
b3ae8a62cfdf13821d35467d4150ed983ac556f1
Fix slice bounds out of range panic in parsing socket control message. Panic found by syzakller.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/control/control.go", "new_path": "pkg/sentry/socket/control/control.go", "diff": "@@ -471,6 +471,9 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (socket.Con\ncase linux.SOL_IP:\nswitch h.Type {\ncase linux.IP_TOS:\n+ if length < linux.SizeOfControlMessageTOS {\n+ return socket.ControlMessages{}, syserror.EINVAL\n+ }\ncmsgs.IP.HasTOS = true\nbinary.Unmarshal(buf[i:i+linux.SizeOfControlMessageTOS], usermem.ByteOrder, &cmsgs.IP.TOS)\ni += AlignUp(length, width)\n@@ -481,6 +484,9 @@ func Parse(t *kernel.Task, socketOrEndpoint interface{}, buf []byte) (socket.Con\ncase linux.SOL_IPV6:\nswitch h.Type {\ncase linux.IPV6_TCLASS:\n+ if length < linux.SizeOfControlMessageTClass {\n+ return socket.ControlMessages{}, syserror.EINVAL\n+ }\ncmsgs.IP.HasTClass = true\nbinary.Unmarshal(buf[i:i+linux.SizeOfControlMessageTClass], usermem.ByteOrder, &cmsgs.IP.TClass)\ni += AlignUp(length, width)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_ip_unbound.cc", "new_path": "test/syscalls/linux/socket_ip_unbound.cc", "diff": "@@ -129,6 +129,7 @@ TEST_P(IPUnboundSocketTest, InvalidNegativeTtl) {\nstruct TOSOption {\nint level;\nint option;\n+ int cmsg_level;\n};\nconstexpr int INET_ECN_MASK = 3;\n@@ -139,10 +140,12 @@ static TOSOption GetTOSOption(int domain) {\ncase AF_INET:\nopt.level = IPPROTO_IP;\nopt.option = IP_TOS;\n+ opt.cmsg_level = SOL_IP;\nbreak;\ncase AF_INET6:\nopt.level = IPPROTO_IPV6;\nopt.option = IPV6_TCLASS;\n+ opt.cmsg_level = SOL_IPV6;\nbreak;\n}\nreturn opt;\n@@ -386,6 +389,36 @@ TEST_P(IPUnboundSocketTest, NullTOS) {\nSyscallFailsWithErrno(EFAULT));\n}\n+TEST_P(IPUnboundSocketTest, InsufficientBufferTOS) {\n+ SKIP_IF(GetParam().protocol == IPPROTO_TCP);\n+\n+ auto socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());\n+ TOSOption t = GetTOSOption(GetParam().domain);\n+\n+ in_addr addr4;\n+ in6_addr addr6;\n+ ASSERT_THAT(inet_pton(AF_INET, \"127.0.0.1\", &addr4), ::testing::Eq(1));\n+ ASSERT_THAT(inet_pton(AF_INET6, \"fe80::\", &addr6), ::testing::Eq(1));\n+\n+ cmsghdr cmsg = {};\n+ cmsg.cmsg_len = sizeof(cmsg);\n+ cmsg.cmsg_level = t.cmsg_level;\n+ cmsg.cmsg_type = t.option;\n+\n+ msghdr msg = {};\n+ msg.msg_control = &cmsg;\n+ msg.msg_controllen = sizeof(cmsg);\n+ if (GetParam().domain == AF_INET) {\n+ msg.msg_name = &addr4;\n+ msg.msg_namelen = sizeof(addr4);\n+ } else {\n+ msg.msg_name = &addr6;\n+ msg.msg_namelen = sizeof(addr6);\n+ }\n+\n+ EXPECT_THAT(sendmsg(socket->get(), &msg, 0), SyscallFailsWithErrno(EINVAL));\n+}\n+\nINSTANTIATE_TEST_SUITE_P(\nIPUnboundSockets, IPUnboundSocketTest,\n::testing::ValuesIn(VecCat<SocketKind>(VecCat<SocketKind>(\n" } ]
Go
Apache License 2.0
google/gvisor
Fix slice bounds out of range panic in parsing socket control message. Panic found by syzakller. PiperOrigin-RevId: 288799046
259,891
08.01.2020 16:35:01
28,800
f26a576984052a235b63ec79081a8c4a8c8ffc00
Addressed GH comments
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -298,6 +298,7 @@ type IPTReplace struct {\n// Entries [0]IPTEntry\n}\n+// KernelIPTEntry is identical to IPTReplace, but includes the Entries field.\ntype KernelIPTReplace struct {\nIPTReplace\nEntries [0]IPTEntry\n@@ -306,28 +307,32 @@ type KernelIPTReplace struct {\n// SizeOfIPTReplace is the size of an IPTReplace.\nconst SizeOfIPTReplace = 96\n+// ExtensionName holds the name of a netfilter extension.\ntype ExtensionName [XT_EXTENSION_MAXNAMELEN]byte\n// String implements fmt.Stringer.\nfunc (en ExtensionName) String() string {\n- return name(en[:])\n+ return goString(en[:])\n}\n+// ExtensionName holds the name of a netfilter table.\ntype TableName [XT_TABLE_MAXNAMELEN]byte\n// String implements fmt.Stringer.\nfunc (tn TableName) String() string {\n- return name(tn[:])\n+ return goString(tn[:])\n}\n+// ExtensionName holds the name of a netfilter error. These can also hold\n+// user-defined chains.\ntype ErrorName [XT_FUNCTION_MAXNAMELEN]byte\n// String implements fmt.Stringer.\n-func (fn ErrorName) String() string {\n- return name(fn[:])\n+func (en ErrorName) String() string {\n+ return goString(en[:])\n}\n-func name(cstring []byte) string {\n+func goString(cstring []byte) string {\nfor i, c := range cstring {\nif c == 0 {\nreturn string(cstring[:i])\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -53,7 +53,7 @@ func GetInfo(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr) (linux.IPTG\n}\n// Find the appropriate table.\n- table, err := findTable(ep, info.Name.String())\n+ table, err := findTable(ep, info.Name)\nif err != nil {\nreturn linux.IPTGetinfo{}, err\n}\n@@ -84,7 +84,7 @@ func GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen i\n}\n// Find the appropriate table.\n- table, err := findTable(ep, userEntries.Name.String())\n+ table, err := findTable(ep, userEntries.Name)\nif err != nil {\nreturn linux.KernelIPTGetEntries{}, err\n}\n@@ -96,19 +96,19 @@ func GetEntries(t *kernel.Task, ep tcpip.Endpoint, outPtr usermem.Addr, outLen i\nreturn linux.KernelIPTGetEntries{}, err\n}\nif binary.Size(entries) > uintptr(outLen) {\n- log.Infof(\"Insufficient GetEntries output size: %d\", uintptr(outLen))\n+ log.Warningf(\"Insufficient GetEntries output size: %d\", uintptr(outLen))\nreturn linux.KernelIPTGetEntries{}, syserr.ErrInvalidArgument\n}\nreturn entries, nil\n}\n-func findTable(ep tcpip.Endpoint, tableName string) (iptables.Table, *syserr.Error) {\n+func findTable(ep tcpip.Endpoint, tablename linux.TableName) (iptables.Table, *syserr.Error) {\nipt, err := ep.IPTables()\nif err != nil {\nreturn iptables.Table{}, syserr.FromError(err)\n}\n- table, ok := ipt.Tables[tableName]\n+ table, ok := ipt.Tables[tablename.String()]\nif !ok {\nreturn iptables.Table{}, syserr.ErrInvalidArgument\n}\n@@ -138,17 +138,17 @@ func FillDefaultIPTables(stack *stack.Stack) {\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+func convertNetstackToBinary(tablename string, table iptables.Table) (linux.KernelIPTGetEntries, metadata, *syserr.Error) {\n// Return values.\nvar entries linux.KernelIPTGetEntries\nvar meta metadata\n// The table name has to fit in the struct.\n- if linux.XT_TABLE_MAXNAMELEN < len(name) {\n- log.Infof(\"Table name too long.\")\n+ if linux.XT_TABLE_MAXNAMELEN < len(tablename) {\n+ log.Warningf(\"Table name %q too long.\", tablename)\nreturn linux.KernelIPTGetEntries{}, metadata{}, syserr.ErrInvalidArgument\n}\n- copy(entries.Name[:], name)\n+ copy(entries.Name[:], tablename)\nfor ruleIdx, rule := range table.Rules {\n// Is this a chain entry point?\n@@ -273,11 +273,12 @@ func translateToStandardVerdict(val int32) (iptables.Verdict, *syserr.Error) {\ncase -linux.NF_DROP - 1:\nreturn iptables.Drop, nil\ncase -linux.NF_QUEUE - 1:\n- log.Infof(\"Unsupported iptables verdict QUEUE.\")\n+ log.Warningf(\"Unsupported iptables verdict QUEUE.\")\ncase linux.NF_RETURN:\n- log.Infof(\"Unsupported iptables verdict RETURN.\")\n+ log.Warningf(\"Unsupported iptables verdict RETURN.\")\n+ default:\n+ log.Warningf(\"Unknown iptables verdict %d.\", val)\n}\n- log.Infof(\"Unknown iptables verdict %d.\", val)\nreturn iptables.Invalid, syserr.ErrInvalidArgument\n}\n@@ -288,7 +289,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// Get the basic rules data (struct ipt_replace).\nif len(optVal) < linux.SizeOfIPTReplace {\n- log.Infof(\"netfilter.SetEntries: optVal has insufficient size for replace %d\", len(optVal))\n+ log.Warningf(\"netfilter.SetEntries: optVal has insufficient size for replace %d\", len(optVal))\nreturn syserr.ErrInvalidArgument\n}\nvar replace linux.IPTReplace\n@@ -302,7 +303,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\ncase iptables.TablenameFilter:\ntable = iptables.EmptyFilterTable()\ndefault:\n- log.Infof(fmt.Sprintf(\"We don't yet support writing to the %q table (gvisor.dev/issue/170)\", replace.Name.String()))\n+ log.Warningf(\"We don't yet support writing to the %q table (gvisor.dev/issue/170)\", replace.Name.String())\nreturn syserr.ErrInvalidArgument\n}\n@@ -312,7 +313,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nfor entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\n// Get the struct ipt_entry.\nif len(optVal) < linux.SizeOfIPTEntry {\n- log.Infof(\"netfilter: optVal has insufficient size for entry %d\", len(optVal))\n+ log.Warningf(\"netfilter: optVal has insufficient size for entry %d\", len(optVal))\nreturn syserr.ErrInvalidArgument\n}\nvar entry linux.IPTEntry\n@@ -328,7 +329,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// filtering. We reject any nonzero IPTIP values for now.\nemptyIPTIP := linux.IPTIP{}\nif entry.IP != emptyIPTIP {\n- log.Infof(\"netfilter: non-empty struct iptip found\")\n+ log.Warningf(\"netfilter: non-empty struct iptip found\")\nreturn syserr.ErrInvalidArgument\n}\n@@ -358,11 +359,11 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\n}\nif ruleIdx := table.BuiltinChains[hk]; ruleIdx == iptables.HookUnset {\n- log.Infof(\"Hook %v is unset.\", hk)\n+ log.Warningf(\"Hook %v is unset.\", hk)\nreturn syserr.ErrInvalidArgument\n}\nif ruleIdx := table.Underflows[hk]; ruleIdx == iptables.HookUnset {\n- log.Infof(\"Underflow %v is unset.\", hk)\n+ log.Warningf(\"Underflow %v is unset.\", hk)\nreturn syserr.ErrInvalidArgument\n}\n}\n@@ -385,7 +386,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// along with the number of bytes it occupies in optVal.\nfunc parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nif len(optVal) < linux.SizeOfXTEntryTarget {\n- log.Infof(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\n+ log.Warningf(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\nvar target linux.XTEntryTarget\n@@ -395,14 +396,14 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\ncase \"\":\n// Standard target.\nif len(optVal) < linux.SizeOfXTStandardTarget {\n- log.Infof(\"netfilter.SetEntries: optVal has insufficient size for standard target %d\", len(optVal))\n+ log.Warningf(\"netfilter.SetEntries: optVal has insufficient size for standard target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\n- var target linux.XTStandardTarget\n+ var standardTarget linux.XTStandardTarget\nbuf = optVal[:linux.SizeOfXTStandardTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &target)\n+ binary.Unmarshal(buf, usermem.ByteOrder, &standardTarget)\n- verdict, err := translateToStandardVerdict(target.Verdict)\n+ verdict, err := translateToStandardVerdict(standardTarget.Verdict)\nif err != nil {\nreturn nil, 0, err\n}\n@@ -424,9 +425,9 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nlog.Infof(\"netfilter.SetEntries: optVal has insufficient size for error target %d\", len(optVal))\nreturn nil, 0, syserr.ErrInvalidArgument\n}\n- var target linux.XTErrorTarget\n+ var errorTarget linux.XTErrorTarget\nbuf = optVal[:linux.SizeOfXTErrorTarget]\n- binary.Unmarshal(buf, usermem.ByteOrder, &target)\n+ binary.Unmarshal(buf, usermem.ByteOrder, &errorTarget)\n// Error targets are used in 2 cases:\n// * An actual error case. These rules have an error\n@@ -435,11 +436,11 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\n// somehow fall through every rule.\n// * To mark the start of a user defined chain. These\n// rules have an error with the name of the chain.\n- switch target.Name.String() {\n+ switch errorTarget.Name.String() {\ncase errorTargetName:\nreturn iptables.PanicTarget{}, linux.SizeOfXTErrorTarget, nil\ndefault:\n- log.Infof(\"Unknown error target %q doesn't exist or isn't supported yet.\", target.Name.String())\n+ log.Infof(\"Unknown error target %q doesn't exist or isn't supported yet.\", errorTarget.Name.String())\nreturn nil, 0, syserr.ErrInvalidArgument\n}\n}\n@@ -449,22 +450,6 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nreturn nil, 0, syserr.ErrInvalidArgument\n}\n-func chainNameFromHook(hook int) string {\n- switch hook {\n- case linux.NF_INET_PRE_ROUTING:\n- return iptables.ChainNamePrerouting\n- case linux.NF_INET_LOCAL_IN:\n- return iptables.ChainNameInput\n- case linux.NF_INET_FORWARD:\n- return iptables.ChainNameForward\n- case linux.NF_INET_LOCAL_OUT:\n- return iptables.ChainNameOutput\n- case linux.NF_INET_POST_ROUTING:\n- return iptables.ChainNamePostrouting\n- }\n- panic(fmt.Sprintf(\"Unknown hook %d does not correspond to a builtin chain\"))\n-}\n-\nfunc hookFromLinux(hook int) iptables.Hook {\nswitch hook {\ncase linux.NF_INET_PRE_ROUTING:\n@@ -489,7 +474,7 @@ func printReplace(optVal []byte) {\nreplaceBuf := optVal[:linux.SizeOfIPTReplace]\noptVal = optVal[linux.SizeOfIPTReplace:]\nbinary.Unmarshal(replaceBuf, usermem.ByteOrder, &replace)\n- log.Infof(\"kevin: Replacing table %q: %+v\", replace.Name.String(), replace)\n+ log.Infof(\"Replacing table %q: %+v\", replace.Name.String(), replace)\n// Read in the list of entries at the end of replace.\nvar totalOffset uint16\n@@ -497,33 +482,33 @@ func printReplace(optVal []byte) {\nvar entry linux.IPTEntry\nentryBuf := optVal[:linux.SizeOfIPTEntry]\nbinary.Unmarshal(entryBuf, usermem.ByteOrder, &entry)\n- log.Infof(\"kevin: Entry %d (total offset %d): %+v\", entryIdx, totalOffset, entry)\n+ log.Infof(\"Entry %d (total offset %d): %+v\", entryIdx, totalOffset, entry)\ntotalOffset += entry.NextOffset\nif entry.TargetOffset == linux.SizeOfIPTEntry {\n- log.Infof(\"kevin: Entry has no matches.\")\n+ log.Infof(\"Entry has no matches.\")\n} else {\n- log.Infof(\"kevin: Entry has matches.\")\n+ log.Infof(\"Entry has matches.\")\n}\nvar target linux.XTEntryTarget\ntargetBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTEntryTarget]\nbinary.Unmarshal(targetBuf, usermem.ByteOrder, &target)\n- log.Infof(\"kevin: Target named %q: %+v\", target.Name.String(), target)\n+ log.Infof(\"Target named %q: %+v\", target.Name.String(), target)\nswitch target.Name.String() {\ncase \"\":\nvar standardTarget linux.XTStandardTarget\nstBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTStandardTarget]\nbinary.Unmarshal(stBuf, usermem.ByteOrder, &standardTarget)\n- log.Infof(\"kevin: Standard target with verdict %q (%d).\", linux.VerdictStrings[standardTarget.Verdict], standardTarget.Verdict)\n+ log.Infof(\"Standard target with verdict %q (%d).\", linux.VerdictStrings[standardTarget.Verdict], standardTarget.Verdict)\ncase errorTargetName:\nvar errorTarget linux.XTErrorTarget\netBuf := optVal[entry.TargetOffset : entry.TargetOffset+linux.SizeOfXTErrorTarget]\nbinary.Unmarshal(etBuf, usermem.ByteOrder, &errorTarget)\n- log.Infof(\"kevin: Error target with name %q.\", errorTarget.Name.String())\n+ log.Infof(\"Error target with name %q.\", errorTarget.Name.String())\ndefault:\n- log.Infof(\"kevin: Unknown target type.\")\n+ log.Infof(\"Unknown target type.\")\n}\noptVal = optVal[entry.NextOffset:]\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -1368,10 +1368,7 @@ func (s *SocketOperations) SetSockOpt(t *kernel.Task, level int, name int, optVa\nreturn syserr.ErrNoDevice\n}\n// Stack must be a netstack stack.\n- if err := netfilter.SetEntries(stack.(*Stack).Stack, optVal); err != nil {\n- return err\n- }\n- return nil\n+ return netfilter.SetEntries(stack.(*Stack).Stack, optVal)\ncase linux.IPT_SO_SET_ADD_COUNTERS:\n// TODO(gvisor.dev/issue/170): Counter support.\n" } ]
Go
Apache License 2.0
google/gvisor
Addressed GH comments
259,860
08.01.2020 16:32:50
28,800
565b64148314018e1234196182b55c4f01772e77
Define sizes for extent headers and entries separately to improve clarity.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/disklayout/extent.go", "new_path": "pkg/sentry/fsimpl/ext/disklayout/extent.go", "diff": "@@ -29,8 +29,12 @@ package disklayout\n// byte (i * sb.BlockSize()) to ((i+1) * sb.BlockSize()).\nconst (\n- // ExtentStructsSize is the size of all the three extent on-disk structs.\n- ExtentStructsSize = 12\n+ // ExtentHeaderSize is the size of the header of an extent tree node.\n+ ExtentHeaderSize = 12\n+\n+ // ExtentEntrySize is the size of an entry in an extent tree node.\n+ // This size is the same for both leaf and internal nodes.\n+ ExtentEntrySize = 12\n// ExtentMagic is the magic number which must be present in the header.\nExtentMagic = 0xf30a\n@@ -57,7 +61,7 @@ type ExtentNode struct {\nEntries []ExtentEntryPair\n}\n-// ExtentEntry reprsents an extent tree node entry. The entry can either be\n+// ExtentEntry represents an extent tree node entry. The entry can either be\n// an ExtentIdx or Extent itself. This exists to simplify navigation logic.\ntype ExtentEntry interface {\n// FileBlock returns the first file block number covered by this entry.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/disklayout/extent_test.go", "new_path": "pkg/sentry/fsimpl/ext/disklayout/extent_test.go", "diff": "@@ -21,7 +21,7 @@ import (\n// TestExtentSize tests that the extent structs are of the correct\n// size.\nfunc TestExtentSize(t *testing.T) {\n- assertSize(t, ExtentHeader{}, ExtentStructsSize)\n- assertSize(t, ExtentIdx{}, ExtentStructsSize)\n- assertSize(t, Extent{}, ExtentStructsSize)\n+ assertSize(t, ExtentHeader{}, ExtentHeaderSize)\n+ assertSize(t, ExtentIdx{}, ExtentEntrySize)\n+ assertSize(t, Extent{}, ExtentEntrySize)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/extent_file.go", "new_path": "pkg/sentry/fsimpl/ext/extent_file.go", "diff": "@@ -57,7 +57,7 @@ func newExtentFile(regFile regularFile) (*extentFile, error) {\nfunc (f *extentFile) buildExtTree() error {\nrootNodeData := f.regFile.inode.diskInode.Data()\n- binary.Unmarshal(rootNodeData[:disklayout.ExtentStructsSize], binary.LittleEndian, &f.root.Header)\n+ binary.Unmarshal(rootNodeData[:disklayout.ExtentHeaderSize], binary.LittleEndian, &f.root.Header)\n// Root node can not have more than 4 entries: 60 bytes = 1 header + 4 entries.\nif f.root.Header.NumEntries > 4 {\n@@ -67,7 +67,7 @@ func (f *extentFile) buildExtTree() error {\n}\nf.root.Entries = make([]disklayout.ExtentEntryPair, f.root.Header.NumEntries)\n- for i, off := uint16(0), disklayout.ExtentStructsSize; i < f.root.Header.NumEntries; i, off = i+1, off+disklayout.ExtentStructsSize {\n+ for i, off := uint16(0), disklayout.ExtentEntrySize; i < f.root.Header.NumEntries; i, off = i+1, off+disklayout.ExtentEntrySize {\nvar curEntry disklayout.ExtentEntry\nif f.root.Header.Height == 0 {\n// Leaf node.\n@@ -76,7 +76,7 @@ func (f *extentFile) buildExtTree() error {\n// Internal node.\ncurEntry = &disklayout.ExtentIdx{}\n}\n- binary.Unmarshal(rootNodeData[off:off+disklayout.ExtentStructsSize], binary.LittleEndian, curEntry)\n+ binary.Unmarshal(rootNodeData[off:off+disklayout.ExtentEntrySize], binary.LittleEndian, curEntry)\nf.root.Entries[i].Entry = curEntry\n}\n@@ -105,7 +105,7 @@ func (f *extentFile) buildExtTreeFromDisk(entry disklayout.ExtentEntry) (*diskla\n}\nentries := make([]disklayout.ExtentEntryPair, header.NumEntries)\n- for i, off := uint16(0), off+disklayout.ExtentStructsSize; i < header.NumEntries; i, off = i+1, off+disklayout.ExtentStructsSize {\n+ for i, off := uint16(0), off+disklayout.ExtentEntrySize; i < header.NumEntries; i, off = i+1, off+disklayout.ExtentEntrySize {\nvar curEntry disklayout.ExtentEntry\nif header.Height == 0 {\n// Leaf node.\n" } ]
Go
Apache License 2.0
google/gvisor
Define sizes for extent headers and entries separately to improve clarity. PiperOrigin-RevId: 288799694
259,884
08.01.2020 16:35:43
28,800
fbb2c008e26a7e9d860f6cbf796ea7c375858502
Return correct length with MSG_TRUNC for unix sockets. This change calls a new Truncate method on the EndpointReader in RecvMsg for both netlink and unix sockets. This allows readers such as sockets to peek at the length of data without actually reading it to a buffer. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/BUILD", "new_path": "pkg/sentry/socket/netlink/BUILD", "diff": "@@ -22,7 +22,6 @@ go_library(\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/kernel/time\",\n- \"//pkg/sentry/safemem\",\n\"//pkg/sentry/socket\",\n\"//pkg/sentry/socket/netlink/port\",\n\"//pkg/sentry/socket/unix\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netlink/socket.go", "new_path": "pkg/sentry/socket/netlink/socket.go", "diff": "@@ -29,7 +29,6 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\nktime \"gvisor.dev/gvisor/pkg/sentry/kernel/time\"\n- \"gvisor.dev/gvisor/pkg/sentry/safemem\"\n\"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/netlink/port\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix\"\n@@ -500,29 +499,29 @@ func (s *Socket) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags int, have\ntrunc := flags&linux.MSG_TRUNC != 0\nr := unix.EndpointReader{\n+ Ctx: t,\nEndpoint: s.ep,\nPeek: flags&linux.MSG_PEEK != 0,\n}\n+ doRead := func() (int64, error) {\n+ return dst.CopyOutFrom(t, &r)\n+ }\n+\n// If MSG_TRUNC is set with a zero byte destination then we still need\n// to read the message and discard it, or in the case where MSG_PEEK is\n// set, leave it be. In both cases the full message length must be\n- // returned. However, the memory manager for the destination will not read\n- // the endpoint if the destination is zero length.\n- //\n- // In order for the endpoint to be read when the destination size is zero,\n- // we must cause a read of the endpoint by using a separate fake zero\n- // length block sequence and calling the EndpointReader directly.\n+ // returned.\nif trunc && dst.Addrs.NumBytes() == 0 {\n- // Perform a read to a zero byte block sequence. We can ignore the\n- // original destination since it was zero bytes. The length returned by\n- // ReadToBlocks is ignored and we return the full message length to comply\n- // with MSG_TRUNC.\n- _, err := r.ReadToBlocks(safemem.BlockSeqOf(safemem.BlockFromSafeSlice(make([]byte, 0))))\n- return int(r.MsgSize), linux.MSG_TRUNC, from, fromLen, socket.ControlMessages{}, syserr.FromError(err)\n+ doRead = func() (int64, error) {\n+ err := r.Truncate()\n+ // Always return zero for bytes read since the destination size is\n+ // zero.\n+ return 0, err\n+ }\n}\n- if n, err := dst.CopyOutFrom(t, &r); err != syserror.ErrWouldBlock || flags&linux.MSG_DONTWAIT != 0 {\n+ if n, err := doRead(); err != syserror.ErrWouldBlock || flags&linux.MSG_DONTWAIT != 0 {\nvar mflags int\nif n < int64(r.MsgSize) {\nmflags |= linux.MSG_TRUNC\n@@ -540,7 +539,7 @@ func (s *Socket) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags int, have\ndefer s.EventUnregister(&e)\nfor {\n- if n, err := dst.CopyOutFrom(t, &r); err != syserror.ErrWouldBlock {\n+ if n, err := doRead(); err != syserror.ErrWouldBlock {\nvar mflags int\nif n < int64(r.MsgSize) {\nmflags |= linux.MSG_TRUNC\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/io.go", "new_path": "pkg/sentry/socket/unix/io.go", "diff": "@@ -83,6 +83,19 @@ type EndpointReader struct {\nControlTrunc bool\n}\n+// Truncate calls RecvMsg on the endpoint without writing to a destination.\n+func (r *EndpointReader) Truncate() error {\n+ // Ignore bytes read since it will always be zero.\n+ _, ms, c, ct, err := r.Endpoint.RecvMsg(r.Ctx, [][]byte{}, r.Creds, r.NumRights, r.Peek, r.From)\n+ r.Control = c\n+ r.ControlTrunc = ct\n+ r.MsgSize = ms\n+ if err != nil {\n+ return err.ToError()\n+ }\n+ return nil\n+}\n+\n// ReadToBlocks implements safemem.Reader.ReadToBlocks.\nfunc (r *EndpointReader) ReadToBlocks(dsts safemem.BlockSeq) (uint64, error) {\nreturn safemem.FromVecReaderFunc{func(bufs [][]byte) (int64, error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/unix/unix.go", "new_path": "pkg/sentry/socket/unix/unix.go", "diff": "@@ -544,8 +544,27 @@ func (s *SocketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\nif senderRequested {\nr.From = &tcpip.FullAddress{}\n}\n+\n+ doRead := func() (int64, error) {\n+ return dst.CopyOutFrom(t, &r)\n+ }\n+\n+ // If MSG_TRUNC is set with a zero byte destination then we still need\n+ // to read the message and discard it, or in the case where MSG_PEEK is\n+ // set, leave it be. In both cases the full message length must be\n+ // returned.\n+ if trunc && dst.Addrs.NumBytes() == 0 {\n+ doRead = func() (int64, error) {\n+ err := r.Truncate()\n+ // Always return zero for bytes read since the destination size is\n+ // zero.\n+ return 0, err\n+ }\n+\n+ }\n+\nvar total int64\n- if n, err := dst.CopyOutFrom(t, &r); err != syserror.ErrWouldBlock || dontWait {\n+ if n, err := doRead(); err != syserror.ErrWouldBlock || dontWait {\nvar from linux.SockAddr\nvar fromLen uint32\nif r.From != nil && len([]byte(r.From.Addr)) != 0 {\n@@ -580,7 +599,7 @@ func (s *SocketOperations) RecvMsg(t *kernel.Task, dst usermem.IOSequence, flags\ndefer s.EventUnregister(&e)\nfor {\n- if n, err := dst.CopyOutFrom(t, &r); err != syserror.ErrWouldBlock {\n+ if n, err := doRead(); err != syserror.ErrWouldBlock {\nvar from linux.SockAddr\nvar fromLen uint32\nif r.From != nil {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -2888,7 +2888,6 @@ cc_library(\n\":unix_domain_socket_test_util\",\n\"//test/util:test_util\",\n\"//test/util:thread_util\",\n- \"//test/util:timer_util\",\n\"@com_google_absl//absl/time\",\n\"@com_google_googletest//:gtest\",\n],\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_non_stream.cc", "new_path": "test/syscalls/linux/socket_non_stream.cc", "diff": "@@ -113,7 +113,7 @@ TEST_P(NonStreamSocketPairTest, RecvmsgMsghdrFlagMsgTrunc) {\nEXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(received_data)));\n// Check that msghdr flags were updated.\n- EXPECT_EQ(msg.msg_flags, MSG_TRUNC);\n+ EXPECT_EQ(msg.msg_flags & MSG_TRUNC, MSG_TRUNC);\n}\n// Stream sockets allow data sent with multiple sends to be peeked at in a\n@@ -193,7 +193,7 @@ TEST_P(NonStreamSocketPairTest, MsgTruncTruncationRecvmsgMsghdrFlagMsgTrunc) {\nEXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(received_data)));\n// Check that msghdr flags were updated.\n- EXPECT_EQ(msg.msg_flags, MSG_TRUNC);\n+ EXPECT_EQ(msg.msg_flags & MSG_TRUNC, MSG_TRUNC);\n}\nTEST_P(NonStreamSocketPairTest, MsgTruncSameSize) {\n@@ -224,5 +224,114 @@ TEST_P(NonStreamSocketPairTest, MsgTruncNotFull) {\nEXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));\n}\n+// This test tests reading from a socket with MSG_TRUNC and a zero length\n+// receive buffer. The user should be able to get the message length.\n+TEST_P(NonStreamSocketPairTest, RecvmsgMsgTruncZeroLen) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ // The receive buffer is of zero length.\n+ char received_data[0] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ // The syscall succeeds returning the full size of the message on the socket.\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_TRUNC),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ // Check that MSG_TRUNC is set on msghdr flags.\n+ EXPECT_EQ(msg.msg_flags & MSG_TRUNC, MSG_TRUNC);\n+}\n+\n+// This test tests reading from a socket with MSG_TRUNC | MSG_PEEK and a zero\n+// length receive buffer. The user should be able to get the message length\n+// without reading data off the socket.\n+TEST_P(NonStreamSocketPairTest, RecvmsgMsgTruncMsgPeekZeroLen) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ // The receive buffer is of zero length.\n+ char peek_data[0] = {};\n+\n+ struct iovec peek_iov;\n+ peek_iov.iov_base = peek_data;\n+ peek_iov.iov_len = sizeof(peek_data);\n+ struct msghdr peek_msg = {};\n+ peek_msg.msg_flags = -1;\n+ peek_msg.msg_iov = &peek_iov;\n+ peek_msg.msg_iovlen = 1;\n+\n+ // The syscall succeeds returning the full size of the message on the socket.\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &peek_msg,\n+ MSG_TRUNC | MSG_PEEK),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ // Check that MSG_TRUNC is set on msghdr flags because the receive buffer is\n+ // smaller than the message size.\n+ EXPECT_EQ(peek_msg.msg_flags & MSG_TRUNC, MSG_TRUNC);\n+\n+ char received_data[sizeof(sent_data)] = {};\n+\n+ struct iovec received_iov;\n+ received_iov.iov_base = received_data;\n+ received_iov.iov_len = sizeof(received_data);\n+ struct msghdr received_msg = {};\n+ received_msg.msg_flags = -1;\n+ received_msg.msg_iov = &received_iov;\n+ received_msg.msg_iovlen = 1;\n+\n+ // Next we can read the actual data.\n+ ASSERT_THAT(\n+ RetryEINTR(recvmsg)(sockets->second_fd(), &received_msg, MSG_TRUNC),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ EXPECT_EQ(0, memcmp(sent_data, received_data, sizeof(sent_data)));\n+\n+ // Check that MSG_TRUNC is not set on msghdr flags because we read the whole\n+ // message.\n+ EXPECT_EQ(received_msg.msg_flags & MSG_TRUNC, 0);\n+}\n+\n+// This test tests reading from a socket with MSG_TRUNC | MSG_PEEK and a zero\n+// length receive buffer and MSG_DONTWAIT. The user should be able to get an\n+// EAGAIN or EWOULDBLOCK error response.\n+TEST_P(NonStreamSocketPairTest, RecvmsgTruncPeekDontwaitZeroLen) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // NOTE: We don't send any data on the socket.\n+\n+ // The receive buffer is of zero length.\n+ char peek_data[0] = {};\n+\n+ struct iovec peek_iov;\n+ peek_iov.iov_base = peek_data;\n+ peek_iov.iov_len = sizeof(peek_data);\n+ struct msghdr peek_msg = {};\n+ peek_msg.msg_flags = -1;\n+ peek_msg.msg_iov = &peek_iov;\n+ peek_msg.msg_iovlen = 1;\n+\n+ // recvmsg fails with EAGAIN because no data is available on the socket.\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &peek_msg,\n+ MSG_TRUNC | MSG_PEEK | MSG_DONTWAIT),\n+ SyscallFailsWithErrno(EAGAIN));\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_non_stream_blocking.cc", "new_path": "test/syscalls/linux/socket_non_stream_blocking.cc", "diff": "#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/syscalls/linux/unix_domain_socket_test_util.h\"\n#include \"test/util/test_util.h\"\n+#include \"test/util/thread_util.h\"\nnamespace gvisor {\nnamespace testing {\n@@ -44,5 +45,41 @@ TEST_P(BlockingNonStreamSocketPairTest, RecvLessThanBufferWaitAll) {\nSyscallSucceedsWithValue(sizeof(sent_data)));\n}\n+// This test tests reading from a socket with MSG_TRUNC | MSG_PEEK and a zero\n+// length receive buffer and MSG_DONTWAIT. The recvmsg call should block on\n+// reading the data.\n+TEST_P(BlockingNonStreamSocketPairTest,\n+ RecvmsgTruncPeekDontwaitZeroLenBlocking) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ // NOTE: We don't initially send any data on the socket.\n+ const int data_size = 10;\n+ char sent_data[data_size];\n+ RandomizeBuffer(sent_data, data_size);\n+\n+ // The receive buffer is of zero length.\n+ char peek_data[0] = {};\n+\n+ struct iovec peek_iov;\n+ peek_iov.iov_base = peek_data;\n+ peek_iov.iov_len = sizeof(peek_data);\n+ struct msghdr peek_msg = {};\n+ peek_msg.msg_flags = -1;\n+ peek_msg.msg_iov = &peek_iov;\n+ peek_msg.msg_iovlen = 1;\n+\n+ ScopedThread t([&]() {\n+ // The syscall succeeds returning the full size of the message on the\n+ // socket. This should block until there is data on the socket.\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &peek_msg,\n+ MSG_TRUNC | MSG_PEEK),\n+ SyscallSucceedsWithValue(data_size));\n+ });\n+\n+ absl::SleepFor(absl::Seconds(1));\n+ ASSERT_THAT(RetryEINTR(send)(sockets->first_fd(), sent_data, data_size, 0),\n+ SyscallSucceedsWithValue(data_size));\n+}\n+\n} // namespace testing\n} // namespace gvisor\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_stream.cc", "new_path": "test/syscalls/linux/socket_stream.cc", "diff": "@@ -104,7 +104,60 @@ TEST_P(StreamSocketPairTest, RecvmsgMsghdrFlagsNoMsgTrunc) {\nEXPECT_EQ(0, memcmp(received_data, sent_data, sizeof(received_data)));\n// Check that msghdr flags were cleared (MSG_TRUNC was not set).\n- EXPECT_EQ(msg.msg_flags, 0);\n+ ASSERT_EQ(msg.msg_flags & MSG_TRUNC, 0);\n+}\n+\n+TEST_P(StreamSocketPairTest, RecvmsgTruncZeroLen) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ char received_data[0] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_TRUNC),\n+ SyscallSucceedsWithValue(0));\n+\n+ // Check that msghdr flags were cleared (MSG_TRUNC was not set).\n+ ASSERT_EQ(msg.msg_flags & MSG_TRUNC, 0);\n+}\n+\n+TEST_P(StreamSocketPairTest, RecvmsgTruncPeekZeroLen) {\n+ auto sockets = ASSERT_NO_ERRNO_AND_VALUE(NewSocketPair());\n+\n+ char sent_data[10];\n+ RandomizeBuffer(sent_data, sizeof(sent_data));\n+ ASSERT_THAT(\n+ RetryEINTR(send)(sockets->first_fd(), sent_data, sizeof(sent_data), 0),\n+ SyscallSucceedsWithValue(sizeof(sent_data)));\n+\n+ char received_data[0] = {};\n+\n+ struct iovec iov;\n+ iov.iov_base = received_data;\n+ iov.iov_len = sizeof(received_data);\n+ struct msghdr msg = {};\n+ msg.msg_flags = -1;\n+ msg.msg_iov = &iov;\n+ msg.msg_iovlen = 1;\n+\n+ ASSERT_THAT(\n+ RetryEINTR(recvmsg)(sockets->second_fd(), &msg, MSG_TRUNC | MSG_PEEK),\n+ SyscallSucceedsWithValue(0));\n+\n+ // Check that msghdr flags were cleared (MSG_TRUNC was not set).\n+ ASSERT_EQ(msg.msg_flags & MSG_TRUNC, 0);\n}\nTEST_P(StreamSocketPairTest, MsgTrunc) {\n" } ]
Go
Apache License 2.0
google/gvisor
Return correct length with MSG_TRUNC for unix sockets. This change calls a new Truncate method on the EndpointReader in RecvMsg for both netlink and unix sockets. This allows readers such as sockets to peek at the length of data without actually reading it to a buffer. Fixes #993 #1240 PiperOrigin-RevId: 288800167
259,891
08.01.2020 17:30:08
28,800
ae060a63d9ad1bfb65b84a2ccbaf2893c5a50b76
More GH comments.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -298,7 +298,7 @@ type IPTReplace struct {\n// Entries [0]IPTEntry\n}\n-// KernelIPTEntry is identical to IPTReplace, but includes the Entries field.\n+// KernelIPTReplace is identical to IPTReplace, but includes the Entries field.\ntype KernelIPTReplace struct {\nIPTReplace\nEntries [0]IPTEntry\n@@ -315,7 +315,7 @@ func (en ExtensionName) String() string {\nreturn goString(en[:])\n}\n-// ExtensionName holds the name of a netfilter table.\n+// TableName holds the name of a netfilter table.\ntype TableName [XT_TABLE_MAXNAMELEN]byte\n// String implements fmt.Stringer.\n@@ -323,7 +323,7 @@ func (tn TableName) String() string {\nreturn goString(tn[:])\n}\n-// ExtensionName holds the name of a netfilter error. These can also hold\n+// ErrorName holds the name of a netfilter error. These can also hold\n// user-defined chains.\ntype ErrorName [XT_FUNCTION_MAXNAMELEN]byte\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -210,8 +210,8 @@ func marshalTarget(target iptables.Target) []byte {\nreturn marshalStandardTarget(iptables.Accept)\ncase iptables.UnconditionalDropTarget:\nreturn marshalStandardTarget(iptables.Drop)\n- case iptables.PanicTarget:\n- return marshalPanicTarget()\n+ case iptables.ErrorTarget:\n+ return marshalErrorTarget()\ndefault:\npanic(fmt.Errorf(\"unknown target of type %T\", target))\n}\n@@ -230,7 +230,7 @@ func marshalStandardTarget(verdict iptables.Verdict) []byte {\nreturn binary.Marshal(ret, usermem.ByteOrder, target)\n}\n-func marshalPanicTarget() []byte {\n+func marshalErrorTarget() []byte {\n// This is an error target named error\ntarget := linux.XTErrorTarget{\nTarget: linux.XTEntryTarget{\n@@ -438,7 +438,7 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\n// rules have an error with the name of the chain.\nswitch errorTarget.Name.String() {\ncase errorTargetName:\n- return iptables.PanicTarget{}, linux.SizeOfXTErrorTarget, nil\n+ return iptables.ErrorTarget{}, linux.SizeOfXTErrorTarget, nil\ndefault:\nlog.Infof(\"Unknown error target %q doesn't exist or isn't supported yet.\", errorTarget.Name.String())\nreturn nil, 0, syserr.ErrInvalidArgument\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/BUILD", "new_path": "pkg/tcpip/iptables/BUILD", "diff": "@@ -11,5 +11,8 @@ go_library(\n],\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/iptables\",\nvisibility = [\"//visibility:public\"],\n- deps = [\"//pkg/tcpip/buffer\"],\n+ deps = [\n+ \"//pkg/log\",\n+ \"//pkg/tcpip/buffer\",\n+ ],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -45,7 +45,7 @@ func DefaultTables() IPTables {\nRule{Target: UnconditionalAcceptTarget{}},\nRule{Target: UnconditionalAcceptTarget{}},\nRule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: PanicTarget{}},\n+ Rule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\nPrerouting: 0,\n@@ -65,7 +65,7 @@ func DefaultTables() IPTables {\nRules: []Rule{\nRule{Target: UnconditionalAcceptTarget{}},\nRule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: PanicTarget{}},\n+ Rule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\nPrerouting: 0,\n@@ -82,7 +82,7 @@ func DefaultTables() IPTables {\nRule{Target: UnconditionalAcceptTarget{}},\nRule{Target: UnconditionalAcceptTarget{}},\nRule{Target: UnconditionalAcceptTarget{}},\n- Rule{Target: PanicTarget{}},\n+ Rule{Target: ErrorTarget{}},\n},\nBuiltinChains: map[Hook]int{\nInput: 0,\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/targets.go", "new_path": "pkg/tcpip/iptables/targets.go", "diff": "package iptables\n-import \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+import (\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+)\n// UnconditionalAcceptTarget accepts all packets.\ntype UnconditionalAcceptTarget struct{}\n@@ -34,10 +37,13 @@ func (UnconditionalDropTarget) Action(packet buffer.VectorisedView) (Verdict, st\nreturn Drop, \"\"\n}\n-// PanicTarget just panics. It represents a target that should be unreachable.\n-type PanicTarget struct{}\n+// ErrorTarget logs an error and drops the packet. It represents a target that\n+// should be unreachable.\n+type ErrorTarget struct{}\n// Actions implements Target.Action.\n-func (PanicTarget) Action(packet buffer.VectorisedView) (Verdict, string) {\n- panic(\"PanicTarget triggered.\")\n+func (ErrorTarget) Action(packet buffer.VectorisedView) (Verdict, string) {\n+ log.Warningf(\"ErrorTarget triggered.\")\n+ return Drop, \"\"\n+\n}\n" } ]
Go
Apache License 2.0
google/gvisor
More GH comments.
259,891
08.01.2020 21:39:13
28,800
781a68eeb65b4db09ae6591a4273e27a2bf60999
It works! It drops some packets.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -52,7 +52,7 @@ func GetInfo(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr) (linux.IPT\n}\n// Find the appropriate table.\n- table, err := findTable(ep, info.Name)\n+ table, err := findTable(stack, info.Name)\nif err != nil {\nreturn linux.IPTGetinfo{}, err\n}\n@@ -83,7 +83,7 @@ func GetEntries(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr, outLen\n}\n// Find the appropriate table.\n- table, err := findTable(ep, userEntries.Name)\n+ table, err := findTable(stack, userEntries.Name)\nif err != nil {\nreturn linux.KernelIPTGetEntries{}, err\n}\n@@ -102,11 +102,8 @@ func GetEntries(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr, outLen\nreturn entries, nil\n}\n-func findTable(ep tcpip.Endpoint, tablename linux.TableName) (iptables.Table, *syserr.Error) {\n- ipt, err := ep.IPTables()\n- if err != nil {\n- return iptables.Table{}, syserr.FromError(err)\n- }\n+func findTable(stack *stack.Stack, tablename linux.TableName) (iptables.Table, *syserr.Error) {\n+ ipt := stack.IPTables()\ntable, ok := ipt.Tables[tablename.String()]\nif !ok {\nreturn iptables.Table{}, syserr.ErrInvalidArgument\n@@ -347,7 +344,7 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// Go through the list of supported hooks for this table and, for each\n// one, set the rule it corresponds to.\nfor hook, _ := range replace.HookEntry {\n- if table.ValidHooks()&uint32(hook) != 0 {\n+ if table.ValidHooks()&(1<<hook) != 0 {\nhk := hookFromLinux(hook)\nfor ruleIdx, offset := range offsets {\nif offset == replace.HookEntry[hook] {\n" } ]
Go
Apache License 2.0
google/gvisor
It works! It drops some packets.
259,891
08.01.2020 22:10:35
28,800
aeb3a4017b9bc038ebe5630fe270d5ea8691d141
Working on filtering by protocol.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -151,6 +151,9 @@ func (table *Table) SetMetadata(metadata interface{}) {\n// packets this rule applies to. If there are no matchers in the rule, it\n// applies to any packet.\ntype Rule struct {\n+ // IPHeaderFilters holds basic IP filtering fields common to every rule.\n+ IPHeaderFilter IPHeaderFilter\n+\n// Matchers is the list of matchers for this rule.\nMatchers []Matcher\n@@ -158,6 +161,23 @@ type Rule struct {\nTarget Target\n}\n+// TODO: This is gross.\n+// TODO: Save this in SetEntries.\n+// TODO: Utilize this when traversing tables.\n+type IPHeaderFilter struct {\n+ Source [4]byte\n+ Destination [4]byte\n+ SourceMask [4]byte\n+ DestinationMask [4]byte\n+ OutputInterface string\n+ InputInterface string\n+ OutputInterfaceMask string\n+ InputInterfaceMask string\n+ Protocol uint16\n+ Flags uint8\n+ InverseFlags uint8\n+}\n+\n// A Matcher is the interface for matching packets.\ntype Matcher interface {\n// Match returns whether the packet matches and whether the packet\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -166,20 +166,20 @@ func TestFilterInputDropUDP(t *testing.T) {\n}\n}\n-func TestFilterInputDropUDPPort(t *testing.T) {\n- if err := singleTest(FilterInputDropUDPPort{}); err != nil {\n- t.Fatal(err)\n- }\n-}\n-\n-func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n- if err := singleTest(FilterInputDropDifferentUDPPort{}); err != nil {\n- t.Fatal(err)\n- }\n-}\n-\n-func TestFilterInputDropAll(t *testing.T) {\n- if err := singleTest(FilterInputDropAll{}); err != nil {\n- t.Fatal(err)\n- }\n-}\n+// func TestFilterInputDropUDPPort(t *testing.T) {\n+// if err := singleTest(FilterInputDropUDPPort{}); err != nil {\n+// t.Fatal(err)\n+// }\n+// }\n+\n+// func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n+// if err := singleTest(FilterInputDropDifferentUDPPort{}); err != nil {\n+// t.Fatal(err)\n+// }\n+// }\n+\n+// func TestFilterInputDropAll(t *testing.T) {\n+// if err := singleTest(FilterInputDropAll{}); err != nil {\n+// t.Fatal(err)\n+// }\n+// }\n" } ]
Go
Apache License 2.0
google/gvisor
Working on filtering by protocol.
259,857
09.01.2020 09:01:17
0
fdfa05ff2c99b4a2f7c0b22fc491a268f1f2e164
Avoid panic when c.PCIDs is nil When PCID is disabled, there would throw a panic when dropPageTables() access to c.PCID without check.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_amd64.go", "new_path": "pkg/sentry/platform/kvm/machine_amd64.go", "diff": "@@ -90,9 +90,11 @@ func (m *machine) dropPageTables(pt *pagetables.PageTables) {\n// Clear from all PCIDs.\nfor _, c := range m.vCPUs {\n+ if c.PCIDs != nil {\nc.PCIDs.Drop(pt)\n}\n}\n+}\n// initArchState initializes architecture-specific state.\nfunc (c *vCPU) initArchState() error {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/machine_arm64.go", "new_path": "pkg/sentry/platform/kvm/machine_arm64.go", "diff": "@@ -97,9 +97,11 @@ func (m *machine) dropPageTables(pt *pagetables.PageTables) {\n// Clear from all PCIDs.\nfor _, c := range m.vCPUs {\n+ if c.PCIDs != nil {\nc.PCIDs.Drop(pt)\n}\n}\n+}\n// nonCanonical generates a canonical address return.\n//\n" } ]
Go
Apache License 2.0
google/gvisor
Avoid panic when c.PCIDs is nil When PCID is disabled, there would throw a panic when dropPageTables() access to c.PCID without check. Signed-off-by: Lai Jiangshan <[email protected]>
259,881
08.01.2020 16:58:30
28,800
afbd4a130b3b49224b8c25a50d2bf1cfadd49ed3
Use question marks for questions
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/FAQ.md", "new_path": "content/docs/user_guide/FAQ.md", "diff": "@@ -23,11 +23,11 @@ gVisor supports Linux\nBinaries run in gVisor should be built for the\n[AMD64](https://en.wikipedia.org/wiki/X86-64) CPU architecture.\n-### Can I run Docker images using gVisor.\n+### Can I run Docker images using gVisor?\nYes. Please see the [Docker Quick Start][docker].\n-### Can I run Kubernetes pods using gVisor.\n+### Can I run Kubernetes pods using gVisor?\nYes. Please see the [Kubernetes Quick Start][k8s].\n" } ]
Go
Apache License 2.0
google/gvisor
Use question marks for questions
259,992
09.01.2020 10:16:02
28,800
290908fa8ae2363c3d2a7af7cef8d5dda622cde7
Configure issue reviver to run with Kokoro
[ { "change_type": "ADD", "old_path": null, "new_path": "kokoro/issue_reviver.cfg", "diff": "+build_file: \"repo/scripts/issue_reviver.sh\"\n+\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: \"73898_kokoro-github-access-token\"\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/issue_reviver.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+DIR=$(dirname $0)\n+source \"${DIR}\"/common.sh\n+\n+# Provide a credential file if available.\n+export OAUTH_TOKEN_FILE=\"\"\n+if [[ -v KOKORO_GITHUB_ACCESS_TOKEN ]]; then\n+ OAUTH_TOKEN_FILE=\"${KOKORO_KEYSTORE_DIR}/${KOKORO_GITHUB_ACCESS_TOKEN}\"\n+fi\n+\n+REPO_ROOT=$(cd \"$(dirname \"${DIR}\")\"; pwd)\n+run //tools/issue_reviver:issue_reviver --path \"${REPO_ROOT}\" --oauth-token-file=\"${OAUTH_TOKEN_FILE}\"\n" } ]
Go
Apache License 2.0
google/gvisor
Configure issue reviver to run with Kokoro PiperOrigin-RevId: 288921032
259,896
09.01.2020 10:03:22
28,800
6cc8e2d814f99439e01c308e16f6631d75578ec0
Add test to check iptables redirect port rule
[ { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -23,6 +23,7 @@ import (\nconst (\ndropPort = 2401\nacceptPort = 2402\n+ redirectPort = 42\nsendloopDuration = 2 * time.Second\nnetwork = \"udp4\"\n)\n@@ -31,6 +32,7 @@ func init() {\nRegisterTestCase(FilterInputDropUDP{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropDifferentUDPPort{})\n+ RegisterTestCase(FilterInputRedirectUDPPort{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -122,3 +124,29 @@ func (FilterInputDropDifferentUDPPort) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropDifferentUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// FilterInputRedirectUDPPort tests that packets are redirected to different port.\n+type FilterInputRedirectUDPPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputRedirectUDPPort) Name() string {\n+ return \"FilterInputRedirectUDPPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputRedirectUDPPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ return err\n+ }\n+\n+ if err := listenUDP(redirectPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", acceptPort, redirectPort, err)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputRedirectUDPPort) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -177,3 +177,10 @@ func TestFilterInputDropDifferentUDPPort(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\n+func TestFilterInputRedirectUDPPort(t *testing.T) {\n+ if err := singleTest(FilterInputRedirectUDPPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n" } ]
Go
Apache License 2.0
google/gvisor
Add test to check iptables redirect port rule
259,942
09.01.2020 10:34:30
28,800
e752ddbb72d89b19863a6b50d99814149a08d5fe
Allow clients to store an opaque NICContext with NICs ...retrievable later via stack.NICInfo(). Clients of this library can use it to add metadata that should be tracked alongside a NIC, to avoid having to keep a map[tcpip.NICID]metadata mirroring stack.Stack's nic map.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -31,6 +31,7 @@ type NIC struct {\nid tcpip.NICID\nname string\nlinkEP LinkEndpoint\n+ context NICContext\nmu sync.RWMutex\nspoofing bool\n@@ -84,7 +85,7 @@ const (\n)\n// newNIC returns a new NIC using the default NDP configurations from stack.\n-func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint) *NIC {\n+func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint, ctx NICContext) *NIC {\n// TODO(b/141011931): Validate a LinkEndpoint (ep) is valid. For\n// example, make sure that the link address it provides is a valid\n// unicast ethernet address.\n@@ -98,6 +99,7 @@ func newNIC(stack *Stack, id tcpip.NICID, name string, ep LinkEndpoint) *NIC {\nid: id,\nname: name,\nlinkEP: ep,\n+ context: ctx,\nprimary: make(map[tcpip.NetworkProtocolNumber][]*referencedNetworkEndpoint),\nendpoints: make(map[NetworkEndpointID]*referencedNetworkEndpoint),\nmcastJoins: make(map[NetworkEndpointID]int32),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -796,6 +796,9 @@ func (s *Stack) NewPacketEndpoint(cooked bool, netProto tcpip.NetworkProtocolNum\nreturn s.rawFactory.NewPacketEndpoint(s, cooked, netProto, waiterQueue)\n}\n+// NICContext is an opaque pointer used to store client-supplied NIC metadata.\n+type NICContext interface{}\n+\n// NICOptions specifies the configuration of a NIC as it is being created.\n// The zero value creates an enabled, unnamed NIC.\ntype NICOptions struct {\n@@ -805,6 +808,12 @@ type NICOptions struct {\n// Disabled specifies whether to avoid calling Attach on the passed\n// LinkEndpoint.\nDisabled bool\n+\n+ // Context specifies user-defined data that will be returned in stack.NICInfo\n+ // for the NIC. Clients of this library can use it to add metadata that\n+ // should be tracked alongside a NIC, to avoid having to keep a\n+ // map[tcpip.NICID]metadata mirroring stack.Stack's nic map.\n+ Context NICContext\n}\n// CreateNICWithOptions creates a NIC with the provided id, LinkEndpoint, and\n@@ -819,7 +828,7 @@ func (s *Stack) CreateNICWithOptions(id tcpip.NICID, ep LinkEndpoint, opts NICOp\nreturn tcpip.ErrDuplicateNICID\n}\n- n := newNIC(s, id, opts.Name, ep)\n+ n := newNIC(s, id, opts.Name, ep, opts.Context)\ns.nics[id] = n\nif !opts.Disabled {\n@@ -886,6 +895,10 @@ type NICInfo struct {\nMTU uint32\nStats NICStats\n+\n+ // Context is user-supplied data optionally supplied in CreateNICWithOptions.\n+ // See type NICOptions for more details.\n+ Context NICContext\n}\n// NICInfo returns a map of NICIDs to their associated information.\n@@ -908,6 +921,7 @@ func (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\nFlags: flags,\nMTU: nic.linkEP.MTU(),\nStats: nic.stats,\n+ Context: nic.context,\n}\n}\nreturn nics\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -2001,6 +2001,46 @@ func TestNICAutoGenAddr(t *testing.T) {\n}\n}\n+// TestNICContextPreservation tests that you can read out via stack.NICInfo the\n+// Context data you pass via NICContext.Context in stack.CreateNICWithOptions.\n+func TestNICContextPreservation(t *testing.T) {\n+ var ctx *int\n+ tests := []struct {\n+ name string\n+ opts stack.NICOptions\n+ want stack.NICContext\n+ }{\n+ {\n+ \"context_set\",\n+ stack.NICOptions{Context: ctx},\n+ ctx,\n+ },\n+ {\n+ \"context_not_set\",\n+ stack.NICOptions{},\n+ nil,\n+ },\n+ }\n+ for _, test := range tests {\n+ t.Run(test.name, func(t *testing.T) {\n+ s := stack.New(stack.Options{})\n+ id := tcpip.NICID(1)\n+ ep := channel.New(0, 0, tcpip.LinkAddress(\"\\x00\\x00\\x00\\x00\\x00\\x00\"))\n+ if err := s.CreateNICWithOptions(id, ep, test.opts); err != nil {\n+ t.Fatalf(\"got stack.CreateNICWithOptions(%d, %+v, %+v) = %s, want nil\", id, ep, test.opts, err)\n+ }\n+ nicinfos := s.NICInfo()\n+ nicinfo, ok := nicinfos[id]\n+ if !ok {\n+ t.Fatalf(\"got nicinfos[%d] = _, %t, want _, true; nicinfos = %+v\", id, ok, nicinfos)\n+ }\n+ if got, want := nicinfo.Context == test.want, true; got != want {\n+ t.Fatal(\"got nicinfo.Context == ctx = %t, want %t; nicinfo.Context = %p, ctx = %p\", got, want, nicinfo.Context, test.want)\n+ }\n+ })\n+ }\n+}\n+\n// TestNICAutoGenAddrWithOpaque tests the auto-generation of IPv6 link-local\n// addresses with opaque interface identifiers. Link Local addresses should\n// always be generated with opaque IIDs if configured to use them, even if the\n" } ]
Go
Apache License 2.0
google/gvisor
Allow clients to store an opaque NICContext with NICs ...retrievable later via stack.NICInfo(). Clients of this library can use it to add metadata that should be tracked alongside a NIC, to avoid having to keep a map[tcpip.NICID]metadata mirroring stack.Stack's nic map. PiperOrigin-RevId: 288924900
259,972
09.01.2020 13:06:24
28,800
8643933d6e58492cbe9d5c78124873ab40f65feb
Change BindToDeviceOption to store NICID This makes it possible to call the sockopt from go even when the NIC has no name.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -985,13 +985,23 @@ func getSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, family\nif err := ep.GetSockOpt(&v); err != nil {\nreturn nil, syserr.TranslateNetstackError(err)\n}\n- if len(v) == 0 {\n+ if v == 0 {\nreturn []byte{}, nil\n}\nif outLen < linux.IFNAMSIZ {\nreturn nil, syserr.ErrInvalidArgument\n}\n- return append([]byte(v), 0), nil\n+ s := t.NetworkContext()\n+ if s == nil {\n+ return nil, syserr.ErrNoDevice\n+ }\n+ nic, ok := s.Interfaces()[int32(v)]\n+ if !ok {\n+ // The NICID no longer indicates a valid interface, probably because that\n+ // interface was removed.\n+ return nil, syserr.ErrUnknownDevice\n+ }\n+ return append([]byte(nic.Name), 0), nil\ncase linux.SO_BROADCAST:\nif outLen < sizeOfInt32 {\n@@ -1438,7 +1448,20 @@ func setSockOptSocket(t *kernel.Task, s socket.Socket, ep commonEndpoint, name i\nif n == -1 {\nn = len(optVal)\n}\n- return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.BindToDeviceOption(optVal[:n])))\n+ name := string(optVal[:n])\n+ if name == \"\" {\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.BindToDeviceOption(0)))\n+ }\n+ s := t.NetworkContext()\n+ if s == nil {\n+ return syserr.ErrNoDevice\n+ }\n+ for nicID, nic := range s.Interfaces() {\n+ if nic.Name == name {\n+ return syserr.TranslateNetstackError(ep.SetSockOpt(tcpip.BindToDeviceOption(nicID)))\n+ }\n+ }\n+ return syserr.ErrUnknownDevice\ncase linux.SO_BROADCAST:\nif len(optVal) < sizeOfInt32 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack.go", "new_path": "pkg/tcpip/stack/stack.go", "diff": "@@ -901,6 +901,14 @@ type NICInfo struct {\nContext NICContext\n}\n+// HasNIC returns true if the NICID is defined in the stack.\n+func (s *Stack) HasNIC(id tcpip.NICID) bool {\n+ s.mu.RLock()\n+ _, ok := s.nics[id]\n+ s.mu.RUnlock()\n+ return ok\n+}\n+\n// NICInfo returns a map of NICIDs to their associated information.\nfunc (s *Stack) NICInfo() map[tcpip.NICID]NICInfo {\ns.mu.RLock()\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/transport_demuxer_test.go", "new_path": "pkg/tcpip/stack/transport_demuxer_test.go", "diff": "@@ -41,7 +41,7 @@ const (\ntype testContext struct {\nt *testing.T\n- linkEPs map[string]*channel.Endpoint\n+ linkEps map[tcpip.NICID]*channel.Endpoint\ns *stack.Stack\nep tcpip.Endpoint\n@@ -66,27 +66,24 @@ func (c *testContext) createV6Endpoint(v6only bool) {\n}\n}\n-// newDualTestContextMultiNic creates the testing context and also linkEpNames\n-// named NICs.\n-func newDualTestContextMultiNic(t *testing.T, mtu uint32, linkEpNames []string) *testContext {\n+// newDualTestContextMultiNIC creates the testing context and also linkEpIDs NICs.\n+func newDualTestContextMultiNIC(t *testing.T, mtu uint32, linkEpIDs []tcpip.NICID) *testContext {\ns := stack.New(stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\nTransportProtocols: []stack.TransportProtocol{udp.NewProtocol()}})\n- linkEPs := make(map[string]*channel.Endpoint)\n- for i, linkEpName := range linkEpNames {\n- channelEP := channel.New(256, mtu, \"\")\n- nicID := tcpip.NICID(i + 1)\n- opts := stack.NICOptions{Name: linkEpName}\n- if err := s.CreateNICWithOptions(nicID, channelEP, opts); err != nil {\n- t.Fatalf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n+ linkEps := make(map[tcpip.NICID]*channel.Endpoint)\n+ for _, linkEpID := range linkEpIDs {\n+ channelEp := channel.New(256, mtu, \"\")\n+ if err := s.CreateNIC(linkEpID, channelEp); err != nil {\n+ t.Fatalf(\"CreateNIC failed: %v\", err)\n}\n- linkEPs[linkEpName] = channelEP\n+ linkEps[linkEpID] = channelEp\n- if err := s.AddAddress(nicID, ipv4.ProtocolNumber, stackAddr); err != nil {\n+ if err := s.AddAddress(linkEpID, ipv4.ProtocolNumber, stackAddr); err != nil {\nt.Fatalf(\"AddAddress IPv4 failed: %v\", err)\n}\n- if err := s.AddAddress(nicID, ipv6.ProtocolNumber, stackV6Addr); err != nil {\n+ if err := s.AddAddress(linkEpID, ipv6.ProtocolNumber, stackV6Addr); err != nil {\nt.Fatalf(\"AddAddress IPv6 failed: %v\", err)\n}\n}\n@@ -105,7 +102,7 @@ func newDualTestContextMultiNic(t *testing.T, mtu uint32, linkEpNames []string)\nreturn &testContext{\nt: t,\ns: s,\n- linkEPs: linkEPs,\n+ linkEps: linkEps,\n}\n}\n@@ -122,7 +119,7 @@ func newPayload() []byte {\nreturn b\n}\n-func (c *testContext) sendV6Packet(payload []byte, h *headers, linkEpName string) {\n+func (c *testContext) sendV6Packet(payload []byte, h *headers, linkEpID tcpip.NICID) {\n// Allocate a buffer for data and headers.\nbuf := buffer.NewView(header.UDPMinimumSize + header.IPv6MinimumSize + len(payload))\ncopy(buf[len(buf)-len(payload):], payload)\n@@ -153,7 +150,7 @@ func (c *testContext) sendV6Packet(payload []byte, h *headers, linkEpName string\nu.SetChecksum(^u.CalculateChecksum(xsum))\n// Inject packet.\n- c.linkEPs[linkEpName].InjectInbound(ipv6.ProtocolNumber, tcpip.PacketBuffer{\n+ c.linkEps[linkEpID].InjectInbound(ipv6.ProtocolNumber, tcpip.PacketBuffer{\nData: buf.ToVectorisedView(),\n})\n}\n@@ -183,7 +180,7 @@ func TestTransportDemuxerRegister(t *testing.T) {\nfunc TestDistribution(t *testing.T) {\ntype endpointSockopts struct {\nreuse int\n- bindToDevice string\n+ bindToDevice tcpip.NICID\n}\nfor _, test := range []struct {\nname string\n@@ -191,71 +188,71 @@ func TestDistribution(t *testing.T) {\nendpoints []endpointSockopts\n// wantedDistribution is the wanted ratio of packets received on each\n// endpoint for each NIC on which packets are injected.\n- wantedDistributions map[string][]float64\n+ wantedDistributions map[tcpip.NICID][]float64\n}{\n{\n\"BindPortReuse\",\n// 5 endpoints that all have reuse set.\n[]endpointSockopts{\n- {1, \"\"},\n- {1, \"\"},\n- {1, \"\"},\n- {1, \"\"},\n- {1, \"\"},\n+ {1, 0},\n+ {1, 0},\n+ {1, 0},\n+ {1, 0},\n+ {1, 0},\n},\n- map[string][]float64{\n+ map[tcpip.NICID][]float64{\n// Injected packets on dev0 get distributed evenly.\n- \"dev0\": {0.2, 0.2, 0.2, 0.2, 0.2},\n+ 1: {0.2, 0.2, 0.2, 0.2, 0.2},\n},\n},\n{\n\"BindToDevice\",\n// 3 endpoints with various bindings.\n[]endpointSockopts{\n- {0, \"dev0\"},\n- {0, \"dev1\"},\n- {0, \"dev2\"},\n+ {0, 1},\n+ {0, 2},\n+ {0, 3},\n},\n- map[string][]float64{\n+ map[tcpip.NICID][]float64{\n// Injected packets on dev0 go only to the endpoint bound to dev0.\n- \"dev0\": {1, 0, 0},\n+ 1: {1, 0, 0},\n// Injected packets on dev1 go only to the endpoint bound to dev1.\n- \"dev1\": {0, 1, 0},\n+ 2: {0, 1, 0},\n// Injected packets on dev2 go only to the endpoint bound to dev2.\n- \"dev2\": {0, 0, 1},\n+ 3: {0, 0, 1},\n},\n},\n{\n\"ReuseAndBindToDevice\",\n// 6 endpoints with various bindings.\n[]endpointSockopts{\n- {1, \"dev0\"},\n- {1, \"dev0\"},\n- {1, \"dev1\"},\n- {1, \"dev1\"},\n- {1, \"dev1\"},\n- {1, \"\"},\n+ {1, 1},\n+ {1, 1},\n+ {1, 2},\n+ {1, 2},\n+ {1, 2},\n+ {1, 0},\n},\n- map[string][]float64{\n+ map[tcpip.NICID][]float64{\n// Injected packets on dev0 get distributed among endpoints bound to\n// dev0.\n- \"dev0\": {0.5, 0.5, 0, 0, 0, 0},\n+ 1: {0.5, 0.5, 0, 0, 0, 0},\n// Injected packets on dev1 get distributed among endpoints bound to\n// dev1 or unbound.\n- \"dev1\": {0, 0, 1. / 3, 1. / 3, 1. / 3, 0},\n+ 2: {0, 0, 1. / 3, 1. / 3, 1. / 3, 0},\n// Injected packets on dev999 go only to the unbound.\n- \"dev999\": {0, 0, 0, 0, 0, 1},\n+ 1000: {0, 0, 0, 0, 0, 1},\n},\n},\n} {\nt.Run(test.name, func(t *testing.T) {\nfor device, wantedDistribution := range test.wantedDistributions {\n- t.Run(device, func(t *testing.T) {\n- var devices []string\n+ t.Run(string(device), func(t *testing.T) {\n+ var devices []tcpip.NICID\nfor d := range test.wantedDistributions {\ndevices = append(devices, d)\n}\n- c := newDualTestContextMultiNic(t, defaultMTU, devices)\n+ c := newDualTestContextMultiNIC(t, defaultMTU, devices)\ndefer c.cleanup()\nc.createV6Endpoint(false)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -552,7 +552,7 @@ type ReusePortOption int\n// BindToDeviceOption is used by SetSockOpt/GetSockOpt to specify that sockets\n// should bind only on a specific NIC.\n-type BindToDeviceOption string\n+type BindToDeviceOption NICID\n// QuickAckOption is stubbed out in SetSockOpt/GetSockOpt.\ntype QuickAckOption int\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -1279,19 +1279,14 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\nreturn nil\ncase tcpip.BindToDeviceOption:\n- e.mu.Lock()\n- defer e.mu.Unlock()\n- if v == \"\" {\n- e.bindToDevice = 0\n- return nil\n+ id := tcpip.NICID(v)\n+ if id != 0 && !e.stack.HasNIC(id) {\n+ return tcpip.ErrUnknownDevice\n}\n- for nicID, nic := range e.stack.NICInfo() {\n- if nic.Name == string(v) {\n- e.bindToDevice = nicID\n+ e.mu.Lock()\n+ e.bindToDevice = id\n+ e.mu.Unlock()\nreturn nil\n- }\n- }\n- return tcpip.ErrUnknownDevice\ncase tcpip.QuickAckOption:\nif v == 0 {\n@@ -1550,12 +1545,8 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ncase *tcpip.BindToDeviceOption:\ne.mu.RLock()\n- defer e.mu.RUnlock()\n- if nic, ok := e.stack.NICInfo()[e.bindToDevice]; ok {\n- *o = tcpip.BindToDeviceOption(nic.Name)\n- return nil\n- }\n- *o = \"\"\n+ *o = tcpip.BindToDeviceOption(e.bindToDevice)\n+ e.mu.RUnlock()\nreturn nil\ncase *tcpip.QuickAckOption:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -1083,12 +1083,12 @@ func TestTrafficClassV6(t *testing.T) {\nfunc TestConnectBindToDevice(t *testing.T) {\nfor _, test := range []struct {\nname string\n- device string\n+ device tcpip.NICID\nwant tcp.EndpointState\n}{\n- {\"RightDevice\", \"nic1\", tcp.StateEstablished},\n- {\"WrongDevice\", \"nic2\", tcp.StateSynSent},\n- {\"AnyDevice\", \"\", tcp.StateEstablished},\n+ {\"RightDevice\", 1, tcp.StateEstablished},\n+ {\"WrongDevice\", 2, tcp.StateSynSent},\n+ {\"AnyDevice\", 0, tcp.StateEstablished},\n} {\nt.Run(test.name, func(t *testing.T) {\nc := context.New(t, defaultMTU)\n@@ -3794,47 +3794,41 @@ func TestBindToDeviceOption(t *testing.T) {\n}\ndefer ep.Close()\n- opts := stack.NICOptions{Name: \"my_device\"}\n- if err := s.CreateNICWithOptions(321, loopback.New(), opts); err != nil {\n- t.Errorf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n- }\n-\n- // Make an nameless NIC.\n- if err := s.CreateNIC(54321, loopback.New()); err != nil {\n+ if err := s.CreateNIC(321, loopback.New()); err != nil {\nt.Errorf(\"CreateNIC failed: %v\", err)\n}\n- // strPtr is used instead of taking the address of string literals, which is\n+ // nicIDPtr is used instead of taking the address of NICID literals, which is\n// a compiler error.\n- strPtr := func(s string) *string {\n+ nicIDPtr := func(s tcpip.NICID) *tcpip.NICID {\nreturn &s\n}\ntestActions := []struct {\nname string\n- setBindToDevice *string\n+ setBindToDevice *tcpip.NICID\nsetBindToDeviceError *tcpip.Error\ngetBindToDevice tcpip.BindToDeviceOption\n}{\n- {\"GetDefaultValue\", nil, nil, \"\"},\n- {\"BindToNonExistent\", strPtr(\"non_existent_device\"), tcpip.ErrUnknownDevice, \"\"},\n- {\"BindToExistent\", strPtr(\"my_device\"), nil, \"my_device\"},\n- {\"UnbindToDevice\", strPtr(\"\"), nil, \"\"},\n+ {\"GetDefaultValue\", nil, nil, 0},\n+ {\"BindToNonExistent\", nicIDPtr(999), tcpip.ErrUnknownDevice, 0},\n+ {\"BindToExistent\", nicIDPtr(321), nil, 321},\n+ {\"UnbindToDevice\", nicIDPtr(0), nil, 0},\n}\nfor _, testAction := range testActions {\nt.Run(testAction.name, func(t *testing.T) {\nif testAction.setBindToDevice != nil {\nbindToDevice := tcpip.BindToDeviceOption(*testAction.setBindToDevice)\n- if got, want := ep.SetSockOpt(bindToDevice), testAction.setBindToDeviceError; got != want {\n- t.Errorf(\"SetSockOpt(%v) got %v, want %v\", bindToDevice, got, want)\n+ if gotErr, wantErr := ep.SetSockOpt(bindToDevice), testAction.setBindToDeviceError; gotErr != wantErr {\n+ t.Errorf(\"SetSockOpt(%v) got %v, want %v\", bindToDevice, gotErr, wantErr)\n}\n}\n- bindToDevice := tcpip.BindToDeviceOption(\"to be modified by GetSockOpt\")\n- if ep.GetSockOpt(&bindToDevice) != nil {\n- t.Errorf(\"GetSockOpt got %v, want %v\", ep.GetSockOpt(&bindToDevice), nil)\n+ bindToDevice := tcpip.BindToDeviceOption(88888)\n+ if err := ep.GetSockOpt(&bindToDevice); err != nil {\n+ t.Errorf(\"GetSockOpt got %v, want %v\", err, nil)\n}\nif got, want := bindToDevice, testAction.getBindToDevice; got != want {\n- t.Errorf(\"bindToDevice got %q, want %q\", got, want)\n+ t.Errorf(\"bindToDevice got %d, want %d\", got, want)\n}\n})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/endpoint.go", "new_path": "pkg/tcpip/transport/udp/endpoint.go", "diff": "@@ -631,19 +631,14 @@ func (e *endpoint) SetSockOpt(opt interface{}) *tcpip.Error {\ne.mu.Unlock()\ncase tcpip.BindToDeviceOption:\n- e.mu.Lock()\n- defer e.mu.Unlock()\n- if v == \"\" {\n- e.bindToDevice = 0\n- return nil\n+ id := tcpip.NICID(v)\n+ if id != 0 && !e.stack.HasNIC(id) {\n+ return tcpip.ErrUnknownDevice\n}\n- for nicID, nic := range e.stack.NICInfo() {\n- if nic.Name == string(v) {\n- e.bindToDevice = nicID\n+ e.mu.Lock()\n+ e.bindToDevice = id\n+ e.mu.Unlock()\nreturn nil\n- }\n- }\n- return tcpip.ErrUnknownDevice\ncase tcpip.BroadcastOption:\ne.mu.Lock()\n@@ -767,12 +762,8 @@ func (e *endpoint) GetSockOpt(opt interface{}) *tcpip.Error {\ncase *tcpip.BindToDeviceOption:\ne.mu.RLock()\n- defer e.mu.RUnlock()\n- if nic, ok := e.stack.NICInfo()[e.bindToDevice]; ok {\n- *o = tcpip.BindToDeviceOption(nic.Name)\n- return nil\n- }\n- *o = tcpip.BindToDeviceOption(\"\")\n+ *o = tcpip.BindToDeviceOption(e.bindToDevice)\n+ e.mu.RUnlock()\nreturn nil\ncase *tcpip.KeepaliveEnabledOption:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -513,42 +513,37 @@ func TestBindToDeviceOption(t *testing.T) {\nt.Errorf(\"CreateNICWithOptions(_, _, %+v) failed: %v\", opts, err)\n}\n- // Make an nameless NIC.\n- if err := s.CreateNIC(54321, loopback.New()); err != nil {\n- t.Errorf(\"CreateNIC failed: %v\", err)\n- }\n-\n- // strPtr is used instead of taking the address of string literals, which is\n+ // nicIDPtr is used instead of taking the address of NICID literals, which is\n// a compiler error.\n- strPtr := func(s string) *string {\n+ nicIDPtr := func(s tcpip.NICID) *tcpip.NICID {\nreturn &s\n}\ntestActions := []struct {\nname string\n- setBindToDevice *string\n+ setBindToDevice *tcpip.NICID\nsetBindToDeviceError *tcpip.Error\ngetBindToDevice tcpip.BindToDeviceOption\n}{\n- {\"GetDefaultValue\", nil, nil, \"\"},\n- {\"BindToNonExistent\", strPtr(\"non_existent_device\"), tcpip.ErrUnknownDevice, \"\"},\n- {\"BindToExistent\", strPtr(\"my_device\"), nil, \"my_device\"},\n- {\"UnbindToDevice\", strPtr(\"\"), nil, \"\"},\n+ {\"GetDefaultValue\", nil, nil, 0},\n+ {\"BindToNonExistent\", nicIDPtr(999), tcpip.ErrUnknownDevice, 0},\n+ {\"BindToExistent\", nicIDPtr(321), nil, 321},\n+ {\"UnbindToDevice\", nicIDPtr(0), nil, 0},\n}\nfor _, testAction := range testActions {\nt.Run(testAction.name, func(t *testing.T) {\nif testAction.setBindToDevice != nil {\nbindToDevice := tcpip.BindToDeviceOption(*testAction.setBindToDevice)\n- if got, want := ep.SetSockOpt(bindToDevice), testAction.setBindToDeviceError; got != want {\n- t.Errorf(\"SetSockOpt(%v) got %v, want %v\", bindToDevice, got, want)\n+ if gotErr, wantErr := ep.SetSockOpt(bindToDevice), testAction.setBindToDeviceError; gotErr != wantErr {\n+ t.Errorf(\"SetSockOpt(%v) got %v, want %v\", bindToDevice, gotErr, wantErr)\n}\n}\n- bindToDevice := tcpip.BindToDeviceOption(\"to be modified by GetSockOpt\")\n- if ep.GetSockOpt(&bindToDevice) != nil {\n- t.Errorf(\"GetSockOpt got %v, want %v\", ep.GetSockOpt(&bindToDevice), nil)\n+ bindToDevice := tcpip.BindToDeviceOption(88888)\n+ if err := ep.GetSockOpt(&bindToDevice); err != nil {\n+ t.Errorf(\"GetSockOpt got %v, want %v\", err, nil)\n}\nif got, want := bindToDevice, testAction.getBindToDevice; got != want {\n- t.Errorf(\"bindToDevice got %q, want %q\", got, want)\n+ t.Errorf(\"bindToDevice got %d, want %d\", got, want)\n}\n})\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Change BindToDeviceOption to store NICID This makes it possible to call the sockopt from go even when the NIC has no name. PiperOrigin-RevId: 288955236
259,891
09.01.2020 13:41:52
28,800
89d11b4d96b0c40e373f14ba72d570c9b894f976
Added a test that we don't pass yet
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -323,10 +323,9 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// TODO(gvisor.dev/issue/170): We should support IPTIP\n// filtering. We reject any nonzero IPTIP values for now.\n- emptyIPTIP := linux.IPTIP{}\n- if entry.IP != emptyIPTIP {\n- log.Warningf(\"netfilter: non-empty struct iptip found\")\n- return syserr.ErrInvalidArgument\n+ filter, err := filterFromIPTIP(entry.IP)\n+ if err != nil {\n+ return err\n}\n// Get the target of the rule.\n@@ -336,7 +335,10 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\noptVal = optVal[consumed:]\n- table.Rules = append(table.Rules, iptables.Rule{Target: target})\n+ table.Rules = append(table.Rules, iptables.Rule{\n+ Filter: filter,\n+ Target: target,\n+ })\noffsets = append(offsets, offset)\noffset += linux.SizeOfIPTEntry + consumed\n}\n@@ -447,6 +449,31 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nreturn nil, 0, syserr.ErrInvalidArgument\n}\n+func filterFromIPTIP(iptip linux.IPTIP) (iptables.IPHeaderFilter, *syserr.Error) {\n+ if containsUnsupportedFields(iptip) {\n+ log.Warningf(\"netfilter: unsupported fields in struct iptip: %+v\")\n+ return iptables.IPHeaderFilter{}, syserr.ErrInvalidArgument\n+ }\n+ return iptables.IPHeaderFilter{\n+ Protocol: iptip.Protocol,\n+ }, nil\n+}\n+\n+func containsUnsupportedFields(iptip linux.IPTIP) bool {\n+ // Currently we check that everything except protocol is zeroed.\n+ var emptyInetAddr = linux.InetAddr{}\n+ var emptyInterface = [linux.IFNAMSIZ]byte{}\n+ return iptip.Dst != emptyInetAddr ||\n+ iptip.SrcMask != emptyInetAddr ||\n+ iptip.DstMask != emptyInetAddr ||\n+ iptip.InputInterface != emptyInterface ||\n+ iptip.OutputInterface != emptyInterface ||\n+ iptip.InputInterfaceMask != emptyInterface ||\n+ iptip.OutputInterfaceMask != emptyInterface ||\n+ iptip.Flags != 0 ||\n+ iptip.InverseFlags != 0\n+}\n+\nfunc hookFromLinux(hook int) iptables.Hook {\nswitch hook {\ncase linux.NF_INET_PRE_ROUTING:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -185,6 +185,13 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\nfunc (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) Verdict {\nrule := table.Rules[ruleIdx]\n+\n+ // First check whether the packet matches the IP header filter.\n+ // TODO(gvisor.dev/issue/170): Support other fields of the filter.\n+ // if rule.Filter.Protocol != pkt.Protocol {\n+ // return Continue\n+ // }\n+\n// Go through each rule matcher. If they all match, run\n// the rule target.\nfor _, matcher := range rule.Matchers {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -151,8 +151,8 @@ func (table *Table) SetMetadata(metadata interface{}) {\n// packets this rule applies to. If there are no matchers in the rule, it\n// applies to any packet.\ntype Rule struct {\n- // IPHeaderFilters holds basic IP filtering fields common to every rule.\n- IPHeaderFilter IPHeaderFilter\n+ // IPHeaderFilter holds basic IP filtering fields common to every rule.\n+ Filter IPHeaderFilter\n// Matchers is the list of matchers for this rule.\nMatchers []Matcher\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/BUILD", "new_path": "test/iptables/BUILD", "diff": "@@ -4,6 +4,7 @@ package(licenses = [\"notice\"])\ngo_library(\nname = \"iptables\",\n+ testonly = 1,\nsrcs = [\n\"filter_input.go\",\n\"iptables.go\",\n@@ -11,6 +12,9 @@ go_library(\n],\nimportpath = \"gvisor.dev/gvisor/test/iptables\",\nvisibility = [\"//test/iptables:__subpackages__\"],\n+ deps = [\n+ \"//runsc/testutil\",\n+ ],\n)\ngo_test(\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -28,6 +28,7 @@ const (\n)\nfunc init() {\n+ RegisterTestCase(FilterInputDropOnlyUDP{})\nRegisterTestCase(FilterInputDropUDP{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropDifferentUDPPort{})\n@@ -65,6 +66,35 @@ func (FilterInputDropUDP) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, dropPort, sendloopDuration)\n}\n+// FilterInputDropOnlyUDP tests that \"-p udp -j DROP\" only affects UDP traffic.\n+type FilterInputDropOnlyUDP struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDropOnlyUDP) Name() string {\n+ return \"FilterInputDropOnlyUDP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDropOnlyUDP) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for a TCP connection, which should be allowed.\n+ if err := listenTCP(acceptPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"failed to establish a connection %v\", err)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDropOnlyUDP) LocalAction(ip net.IP) error {\n+ // Try to establish a TCP connection with the container, which should\n+ // succeed.\n+ return connectLoopTCP(ip, acceptPort, sendloopDuration)\n+}\n+\n// FilterInputDropUDPPort tests that we can drop UDP traffic by port.\ntype FilterInputDropUDPPort struct{}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -160,11 +160,11 @@ func logContainer(output string, err error) {\nlog.Infof(msg)\n}\n-func TestFilterInputDropUDP(t *testing.T) {\n- if err := singleTest(FilterInputDropUDP{}); err != nil {\n- t.Fatal(err)\n- }\n-}\n+// func TestFilterInputDropUDP(t *testing.T) {\n+// if err := singleTest(FilterInputDropUDP{}); err != nil {\n+// t.Fatal(err)\n+// }\n+// }\n// func TestFilterInputDropUDPPort(t *testing.T) {\n// if err := singleTest(FilterInputDropUDPPort{}); err != nil {\n@@ -183,3 +183,9 @@ func TestFilterInputDropUDP(t *testing.T) {\n// t.Fatal(err)\n// }\n// }\n+\n+func TestFilterInputDropOnlyUDP(t *testing.T) {\n+ if err := singleTest(FilterInputDropOnlyUDP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_util.go", "new_path": "test/iptables/iptables_util.go", "diff": "@@ -19,6 +19,8 @@ import (\n\"net\"\n\"os/exec\"\n\"time\"\n+\n+ \"gvisor.dev/gvisor/runsc/testutil\"\n)\nconst iptablesBinary = \"iptables\"\n@@ -80,3 +82,41 @@ func sendUDPLoop(ip net.IP, port int, duration time.Duration) error {\nreturn nil\n}\n+\n+func listenTCP(port int, timeout time.Duration) error {\n+ localAddr := net.TCPAddr{Port: acceptPort}\n+ listener, err := net.ListenTCP(\"tcp4\", &localAddr)\n+ if err != nil {\n+ return err\n+ }\n+ defer listener.Close()\n+ listener.SetDeadline(time.Now().Add(timeout))\n+ conn, err := listener.AcceptTCP()\n+ if err != nil {\n+ return fmt.Errorf(\"failed to establish a connection %v\", err)\n+ }\n+ defer conn.Close()\n+\n+ return nil\n+}\n+\n+func connectLoopTCP(ip net.IP, port int, timeout time.Duration) error {\n+ contAddr := net.TCPAddr{\n+ IP: ip,\n+ Port: port,\n+ }\n+ // The container may not be listening when we first connect, so retry\n+ // upon error.\n+ cb := func() error {\n+ conn, err := net.DialTCP(\"tcp4\", nil, &contAddr)\n+ if conn != nil {\n+ conn.Close()\n+ }\n+ return err\n+ }\n+ if err := testutil.Poll(cb, timeout); err != nil {\n+ return fmt.Errorf(\"timed out waiting to send IP, most recent error: %v\", err)\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/runner/BUILD", "new_path": "test/iptables/runner/BUILD", "diff": "@@ -10,6 +10,7 @@ container_image(\ngo_image(\nname = \"runner\",\n+ testonly = 1,\nsrcs = [\"main.go\"],\nbase = \":iptables-base\",\ndeps = [\"//test/iptables\"],\n" } ]
Go
Apache License 2.0
google/gvisor
Added a test that we don't pass yet
259,891
09.01.2020 15:38:21
28,800
ff719159befaee7d2abcfeb88905a7486cd34845
Confirmed that it works if I hardcode 17 in for pkt.Protocol. Need to address parsing the packet early :(
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -188,9 +188,9 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\n- // if rule.Filter.Protocol != pkt.Protocol {\n- // return Continue\n- // }\n+ if rule.Filter.Protocol != pkt.Protocol {\n+ return Continue\n+ }\n// Go through each rule matcher. If they all match, run\n// the rule target.\n" } ]
Go
Apache License 2.0
google/gvisor
Confirmed that it works if I hardcode 17 in for pkt.Protocol. Need to address parsing the packet early :(
259,896
09.01.2020 15:38:28
28,800
04abc9cf558930472605bf740a4333d6fafe5930
Add test for redirect port Fix the indentation and print statements. Moved the NAT redirect tests to new file. Added negative test to check redirect rule on ports other than redirected port.
[ { "change_type": "MODIFY", "old_path": "test/iptables/BUILD", "new_path": "test/iptables/BUILD", "diff": "@@ -8,6 +8,7 @@ go_library(\n\"filter_input.go\",\n\"iptables.go\",\n\"iptables_util.go\",\n+ \"nat.go\",\n],\nimportpath = \"gvisor.dev/gvisor/test/iptables\",\nvisibility = [\"//test/iptables:__subpackages__\"],\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -23,7 +23,6 @@ import (\nconst (\ndropPort = 2401\nacceptPort = 2402\n- redirectPort = 42\nsendloopDuration = 2 * time.Second\nnetwork = \"udp4\"\n)\n@@ -32,7 +31,6 @@ func init() {\nRegisterTestCase(FilterInputDropUDP{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropDifferentUDPPort{})\n- RegisterTestCase(FilterInputRedirectUDPPort{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -124,29 +122,3 @@ func (FilterInputDropDifferentUDPPort) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropDifferentUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n-\n-// FilterInputRedirectUDPPort tests that packets are redirected to different port.\n-type FilterInputRedirectUDPPort struct{}\n-\n-// Name implements TestCase.Name.\n-func (FilterInputRedirectUDPPort) Name() string {\n- return \"FilterInputRedirectUDPPort\"\n-}\n-\n-// ContainerAction implements TestCase.ContainerAction.\n-func (FilterInputRedirectUDPPort) ContainerAction(ip net.IP) error {\n- if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\", fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n- return err\n- }\n-\n- if err := listenUDP(redirectPort, sendloopDuration); err != nil {\n- return fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", acceptPort, redirectPort, err)\n- }\n-\n- return nil\n-}\n-\n-// LocalAction implements TestCase.LocalAction.\n-func (FilterInputRedirectUDPPort) LocalAction(ip net.IP) error {\n- return sendUDPLoop(ip, acceptPort, sendloopDuration)\n-}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -178,9 +178,14 @@ func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n}\n}\n-func TestFilterInputRedirectUDPPort(t *testing.T) {\n- if err := singleTest(FilterInputRedirectUDPPort{}); err != nil {\n+func TestFilterNATRedirectUDPPort(t *testing.T) {\n+ if err := singleTest(FilterNATRedirectUDPPort{}); err != nil {\nt.Fatal(err)\n}\n}\n+func TestFilterNATDropUDP(t *testing.T) {\n+ if err := singleTest(FilterNATDropUDP{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/iptables/nat.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 iptables\n+\n+import (\n+ \"fmt\"\n+ \"net\"\n+)\n+\n+const (\n+ redirectPort = 42\n+)\n+\n+func init() {\n+ RegisterTestCase(FilterNATRedirectUDPPort{})\n+ RegisterTestCase(FilterNATDropUDP{})\n+}\n+\n+// FilterInputRedirectUDPPort tests that packets are redirected to different port.\n+type FilterNATRedirectUDPPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterNATRedirectUDPPort) Name() string {\n+ return \"FilterNATRedirectUDPPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterNATRedirectUDPPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\",\n+ fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ return err\n+ }\n+\n+ if err := listenUDP(redirectPort, sendloopDuration); err != nil {\n+ return fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", redirectPort, err)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterNATRedirectUDPPort) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n+\n+// FilterNATDropUDP tests that packets are not received in ports other than redirect port.\n+type FilterNATDropUDP struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterNATDropUDP) Name() string {\n+ return \"FilterNATDropUDP\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterNATDropUDP) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\",\n+ fmt.Sprintf(\"%d\", redirectPort)); err != nil {\n+ return err\n+ }\n+\n+ if err := listenUDP(acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"packets on port %d should have been redirected to port %d\", acceptPort, redirectPort)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterNATDropUDP) LocalAction(ip net.IP) error {\n+ return sendUDPLoop(ip, acceptPort, sendloopDuration)\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add test for redirect port Fix the indentation and print statements. Moved the NAT redirect tests to new file. Added negative test to check redirect rule on ports other than redirected port.
260,004
09.01.2020 15:55:24
28,800
8fafd3142e85175fe56bc3333d859f1a8cfbb878
Separate NDP tests into its own package Internal tools timeout after 60s during tests that are required to pass before changes can be submitted. Separate out NDP tests into its own package to help prevent timeouts when testing.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/BUILD", "new_path": "pkg/tcpip/stack/BUILD", "diff": "@@ -52,7 +52,6 @@ go_test(\nname = \"stack_x_test\",\nsize = \"small\",\nsrcs = [\n- \"ndp_test.go\",\n\"stack_test.go\",\n\"transport_demuxer_test.go\",\n\"transport_test.go\",\n@@ -62,14 +61,12 @@ go_test(\n\"//pkg/rand\",\n\"//pkg/tcpip\",\n\"//pkg/tcpip/buffer\",\n- \"//pkg/tcpip/checker\",\n\"//pkg/tcpip/header\",\n\"//pkg/tcpip/iptables\",\n\"//pkg/tcpip/link/channel\",\n\"//pkg/tcpip/link/loopback\",\n\"//pkg/tcpip/network/ipv4\",\n\"//pkg/tcpip/network/ipv6\",\n- \"//pkg/tcpip/transport/icmp\",\n\"//pkg/tcpip/transport/udp\",\n\"//pkg/waiter\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n@@ -86,3 +83,23 @@ go_test(\n\"//pkg/tcpip\",\n],\n)\n+\n+go_test(\n+ name = \"ndp_test\",\n+ size = \"small\",\n+ srcs = [\"ndp_test.go\"],\n+ deps = [\n+ \":stack\",\n+ \"//pkg/rand\",\n+ \"//pkg/tcpip\",\n+ \"//pkg/tcpip/buffer\",\n+ \"//pkg/tcpip/checker\",\n+ \"//pkg/tcpip/header\",\n+ \"//pkg/tcpip/link/channel\",\n+ \"//pkg/tcpip/network/ipv6\",\n+ \"//pkg/tcpip/transport/icmp\",\n+ \"//pkg/tcpip/transport/udp\",\n+ \"//pkg/waiter\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/ndp_test.go", "new_path": "pkg/tcpip/stack/ndp_test.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package stack_test\n+package ndp_test\nimport (\n\"encoding/binary\"\n@@ -285,6 +285,8 @@ func (n *ndpDispatcher) OnRecursiveDNSServerOption(nicID tcpip.NICID, addrs []tc\n// Included in the subtests is a test to make sure that an invalid\n// RetransmitTimer (<1ms) values get fixed to the default RetransmitTimer of 1s.\nfunc TestDADResolve(t *testing.T) {\n+ t.Parallel()\n+\ntests := []struct {\nname string\ndupAddrDetectTransmits uint8\n@@ -417,6 +419,8 @@ func TestDADResolve(t *testing.T) {\n// a node doing DAD for the same address), or if another node is detected to own\n// the address already (receive an NA message for the tentative address).\nfunc TestDADFail(t *testing.T) {\n+ t.Parallel()\n+\ntests := []struct {\nname string\nmakeBuf func(tgt tcpip.Address) buffer.Prependable\n@@ -560,6 +564,8 @@ func TestDADFail(t *testing.T) {\n// TestDADStop tests to make sure that the DAD process stops when an address is\n// removed.\nfunc TestDADStop(t *testing.T) {\n+ t.Parallel()\n+\nndpDisp := ndpDispatcher{\ndadC: make(chan ndpDADEvent),\n}\n@@ -632,6 +638,71 @@ func TestDADStop(t *testing.T) {\n}\n}\n+// TestNICAutoGenAddrDoesDAD tests that the successful auto-generation of IPv6\n+// link-local addresses will only be assigned after the DAD process resolves.\n+func TestNICAutoGenAddrDoesDAD(t *testing.T) {\n+ t.Parallel()\n+\n+ ndpDisp := ndpDispatcher{\n+ dadC: make(chan ndpDADEvent),\n+ }\n+ ndpConfigs := stack.DefaultNDPConfigurations()\n+ opts := stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n+ NDPConfigs: ndpConfigs,\n+ AutoGenIPv6LinkLocal: true,\n+ NDPDisp: &ndpDisp,\n+ }\n+\n+ e := channel.New(0, 1280, linkAddr1)\n+ s := stack.New(opts)\n+ if err := s.CreateNIC(1, e); err != nil {\n+ t.Fatalf(\"CreateNIC(_) = %s\", err)\n+ }\n+\n+ // Address should not be considered bound to the\n+ // NIC yet (DAD ongoing).\n+ addr, err := s.GetMainNICAddress(1, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"got stack.GetMainNICAddress(_, _) = (_, %v), want = (_, nil)\", err)\n+ }\n+ if want := (tcpip.AddressWithPrefix{}); addr != want {\n+ t.Fatalf(\"got stack.GetMainNICAddress(_, _) = (%s, nil), want = (%s, nil)\", addr, want)\n+ }\n+\n+ linkLocalAddr := header.LinkLocalAddr(linkAddr1)\n+\n+ // Wait for DAD to resolve.\n+ select {\n+ case <-time.After(time.Duration(ndpConfigs.DupAddrDetectTransmits)*ndpConfigs.RetransmitTimer + time.Second):\n+ // We should get a resolution event after 1s (default time to\n+ // resolve as per default NDP configurations). Waiting for that\n+ // resolution time + an extra 1s without a resolution event\n+ // means something is wrong.\n+ t.Fatal(\"timed out waiting for DAD resolution\")\n+ case e := <-ndpDisp.dadC:\n+ if e.err != nil {\n+ t.Fatal(\"got DAD error: \", e.err)\n+ }\n+ if e.nicID != 1 {\n+ t.Fatalf(\"got DAD event w/ nicID = %d, want = 1\", e.nicID)\n+ }\n+ if e.addr != linkLocalAddr {\n+ t.Fatalf(\"got DAD event w/ addr = %s, want = %s\", addr, linkLocalAddr)\n+ }\n+ if !e.resolved {\n+ t.Fatal(\"got DAD event w/ resolved = false, want = true\")\n+ }\n+ }\n+ addr, err = s.GetMainNICAddress(1, header.IPv6ProtocolNumber)\n+ if err != nil {\n+ t.Fatalf(\"stack.GetMainNICAddress(_, _) err = %s\", err)\n+ }\n+ if want := (tcpip.AddressWithPrefix{Address: linkLocalAddr, PrefixLen: header.IPv6LinkLocalPrefix.PrefixLen}); addr != want {\n+ t.Fatalf(\"got stack.GetMainNICAddress(_, _) = %s, want = %s\", addr, want)\n+ }\n+}\n+\n// TestSetNDPConfigurationFailsForBadNICID tests to make sure we get an error if\n// we attempt to update NDP configurations using an invalid NICID.\nfunc TestSetNDPConfigurationFailsForBadNICID(t *testing.T) {\n@@ -649,6 +720,8 @@ func TestSetNDPConfigurationFailsForBadNICID(t *testing.T) {\n// configurations without affecting the default NDP configurations or other\n// interfaces' configurations.\nfunc TestSetNDPConfigurations(t *testing.T) {\n+ t.Parallel()\n+\ntests := []struct {\nname string\ndupAddrDetectTransmits uint8\n@@ -875,6 +948,8 @@ func raBufWithPI(ip tcpip.Address, rl uint16, prefix tcpip.AddressWithPrefix, on\n// TestNoRouterDiscovery tests that router discovery will not be performed if\n// configured not to.\nfunc TestNoRouterDiscovery(t *testing.T) {\n+ t.Parallel()\n+\n// Being configured to discover routers means handle and\n// discover are set to true and forwarding is set to false.\n// This tests all possible combinations of the configurations,\n@@ -887,8 +962,6 @@ func TestNoRouterDiscovery(t *testing.T) {\nforwarding := i&4 == 0\nt.Run(fmt.Sprintf(\"HandleRAs(%t), DiscoverDefaultRouters(%t), Forwarding(%t)\", handle, discover, forwarding), func(t *testing.T) {\n- t.Parallel()\n-\nndpDisp := ndpDispatcher{\nrouterC: make(chan ndpRouterEvent, 1),\n}\n@@ -1123,6 +1196,8 @@ func TestRouterDiscoveryMaxRouters(t *testing.T) {\n// TestNoPrefixDiscovery tests that prefix discovery will not be performed if\n// configured not to.\nfunc TestNoPrefixDiscovery(t *testing.T) {\n+ t.Parallel()\n+\nprefix := tcpip.AddressWithPrefix{\nAddress: tcpip.Address(\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\"),\nPrefixLen: 64,\n@@ -1140,8 +1215,6 @@ func TestNoPrefixDiscovery(t *testing.T) {\nforwarding := i&4 == 0\nt.Run(fmt.Sprintf(\"HandleRAs(%t), DiscoverOnLinkPrefixes(%t), Forwarding(%t)\", handle, discover, forwarding), func(t *testing.T) {\n- t.Parallel()\n-\nndpDisp := ndpDispatcher{\nprefixC: make(chan ndpPrefixEvent, 1),\n}\n@@ -1498,6 +1571,8 @@ func contains(list []tcpip.ProtocolAddress, item tcpip.AddressWithPrefix) bool {\n// TestNoAutoGenAddr tests that SLAAC is not performed when configured not to.\nfunc TestNoAutoGenAddr(t *testing.T) {\n+ t.Parallel()\n+\nprefix, _, _ := prefixSubnetAddr(0, \"\")\n// Being configured to auto-generate addresses means handle and\n@@ -1512,8 +1587,6 @@ func TestNoAutoGenAddr(t *testing.T) {\nforwarding := i&4 == 0\nt.Run(fmt.Sprintf(\"HandleRAs(%t), AutoGenAddr(%t), Forwarding(%t)\", handle, autogen, forwarding), func(t *testing.T) {\n- t.Parallel()\n-\nndpDisp := ndpDispatcher{\nautoGenAddrC: make(chan ndpAutoGenAddrEvent, 1),\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -24,7 +24,6 @@ import (\n\"sort\"\n\"strings\"\n\"testing\"\n- \"time\"\n\"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/rand\"\n@@ -50,6 +49,8 @@ const (\n// where another value is explicitly used. It is chosen to match the MTU\n// of loopback interfaces on linux systems.\ndefaultMTU = 65536\n+\n+ linkAddr = \"\\x02\\x02\\x03\\x04\\x05\\x06\"\n)\n// fakeNetworkEndpoint is a network-layer protocol endpoint. It counts sent and\n@@ -1909,7 +1910,7 @@ func TestNICAutoGenAddr(t *testing.T) {\n{\n\"Disabled\",\nfalse,\n- linkAddr1,\n+ linkAddr,\nstack.OpaqueInterfaceIdentifierOptions{\nNICNameFromID: func(nicID tcpip.NICID, _ string) string {\nreturn fmt.Sprintf(\"nic%d\", nicID)\n@@ -1920,7 +1921,7 @@ func TestNICAutoGenAddr(t *testing.T) {\n{\n\"Enabled\",\ntrue,\n- linkAddr1,\n+ linkAddr,\nstack.OpaqueInterfaceIdentifierOptions{},\ntrue,\n},\n@@ -2068,14 +2069,14 @@ func TestNICAutoGenAddrWithOpaque(t *testing.T) {\nname: \"Disabled\",\nnicName: \"nic1\",\nautoGen: false,\n- linkAddr: linkAddr1,\n+ linkAddr: linkAddr,\nsecretKey: secretKey[:],\n},\n{\nname: \"Enabled\",\nnicName: \"nic1\",\nautoGen: true,\n- linkAddr: linkAddr1,\n+ linkAddr: linkAddr,\nsecretKey: secretKey[:],\n},\n// These are all cases where we would not have generated a\n@@ -2213,69 +2214,6 @@ func TestNoLinkLocalAutoGenForLoopbackNIC(t *testing.T) {\n}\n}\n-// TestNICAutoGenAddrDoesDAD tests that the successful auto-generation of IPv6\n-// link-local addresses will only be assigned after the DAD process resolves.\n-func TestNICAutoGenAddrDoesDAD(t *testing.T) {\n- ndpDisp := ndpDispatcher{\n- dadC: make(chan ndpDADEvent),\n- }\n- ndpConfigs := stack.DefaultNDPConfigurations()\n- opts := stack.Options{\n- NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n- NDPConfigs: ndpConfigs,\n- AutoGenIPv6LinkLocal: true,\n- NDPDisp: &ndpDisp,\n- }\n-\n- e := channel.New(10, 1280, linkAddr1)\n- s := stack.New(opts)\n- if err := s.CreateNIC(1, e); err != nil {\n- t.Fatalf(\"CreateNIC(_) = %s\", err)\n- }\n-\n- // Address should not be considered bound to the\n- // NIC yet (DAD ongoing).\n- addr, err := s.GetMainNICAddress(1, header.IPv6ProtocolNumber)\n- if err != nil {\n- t.Fatalf(\"got stack.GetMainNICAddress(_, _) = (_, %v), want = (_, nil)\", err)\n- }\n- if want := (tcpip.AddressWithPrefix{}); addr != want {\n- t.Fatalf(\"got stack.GetMainNICAddress(_, _) = (%s, nil), want = (%s, nil)\", addr, want)\n- }\n-\n- linkLocalAddr := header.LinkLocalAddr(linkAddr1)\n-\n- // Wait for DAD to resolve.\n- select {\n- case <-time.After(time.Duration(ndpConfigs.DupAddrDetectTransmits)*ndpConfigs.RetransmitTimer + time.Second):\n- // We should get a resolution event after 1s (default time to\n- // resolve as per default NDP configurations). Waiting for that\n- // resolution time + an extra 1s without a resolution event\n- // means something is wrong.\n- t.Fatal(\"timed out waiting for DAD resolution\")\n- case e := <-ndpDisp.dadC:\n- if e.err != nil {\n- t.Fatal(\"got DAD error: \", e.err)\n- }\n- if e.nicID != 1 {\n- t.Fatalf(\"got DAD event w/ nicID = %d, want = 1\", e.nicID)\n- }\n- if e.addr != linkLocalAddr {\n- t.Fatalf(\"got DAD event w/ addr = %s, want = %s\", addr, linkLocalAddr)\n- }\n- if !e.resolved {\n- t.Fatal(\"got DAD event w/ resolved = false, want = true\")\n- }\n- }\n- addr, err = s.GetMainNICAddress(1, header.IPv6ProtocolNumber)\n- if err != nil {\n- t.Fatalf(\"stack.GetMainNICAddress(_, _) err = %s\", err)\n- }\n- if want := (tcpip.AddressWithPrefix{Address: linkLocalAddr, PrefixLen: header.IPv6LinkLocalPrefix.PrefixLen}); addr != want {\n- t.Fatalf(\"got stack.GetMainNICAddress(_, _) = %s, want = %s\", addr, want)\n- }\n-}\n-\n// TestNewPEB tests that a new PrimaryEndpointBehavior value (peb) is respected\n// when an address's kind gets \"promoted\" to permanent from permanentExpired.\nfunc TestNewPEBOnPromotionToPermanent(t *testing.T) {\n" } ]
Go
Apache License 2.0
google/gvisor
Separate NDP tests into its own package Internal tools timeout after 60s during tests that are required to pass before changes can be submitted. Separate out NDP tests into its own package to help prevent timeouts when testing. PiperOrigin-RevId: 288990597
259,962
09.01.2020 17:56:58
28,800
356d81146bafc4b4548163eb87e886c851b49e12
Deflake a couple of TCP syscall tests when run under gotsan.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_bind_to_device_distribution.cc", "new_path": "test/syscalls/linux/socket_bind_to_device_distribution.cc", "diff": "@@ -183,7 +183,14 @@ TEST_P(BindToDeviceDistributionTest, Tcp) {\n}\n// Receive some data from a socket to be sure that the connect()\n// system call has been completed on another side.\n- int data;\n+ // Do a short read and then close the socket to trigger a RST. This\n+ // ensures that both ends of the connection are cleaned up and no\n+ // goroutines hang around in TIME-WAIT. We do this so that this test\n+ // does not timeout under gotsan runs where lots of goroutines can\n+ // cause the test to use absurd amounts of memory.\n+ //\n+ // See: https://tools.ietf.org/html/rfc2525#page-50 section 2.17\n+ uint16_t data;\nEXPECT_THAT(\nRetryEINTR(recv)(fd.ValueOrDie().get(), &data, sizeof(data), 0),\nSyscallSucceedsWithValue(sizeof(data)));\n@@ -198,16 +205,30 @@ TEST_P(BindToDeviceDistributionTest, Tcp) {\n}\nfor (int i = 0; i < kConnectAttempts; i++) {\n- FileDescriptor const fd = ASSERT_NO_ERRNO_AND_VALUE(\n+ const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(\nSocket(connector.family(), SOCK_STREAM, IPPROTO_TCP));\nASSERT_THAT(\nRetryEINTR(connect)(fd.get(), reinterpret_cast<sockaddr*>(&conn_addr),\nconnector.addr_len),\nSyscallSucceeds());\n+ // Do two separate sends to ensure two segments are received. This is\n+ // required for netstack where read is incorrectly assuming a whole\n+ // segment is read when endpoint.Read() is called which is technically\n+ // incorrect as the syscall that invoked endpoint.Read() may only\n+ // consume it partially. This results in a case where a close() of\n+ // such a socket does not trigger a RST in netstack due to the\n+ // endpoint assuming that the endpoint has no unread data.\n+ EXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),\n+ SyscallSucceedsWithValue(sizeof(i)));\n+\n+ // TODO(gvisor.dev/issue/1449): Remove this block once netstack correctly\n+ // generates a RST.\n+ if (IsRunningOnGvisor()) {\nEXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),\nSyscallSucceedsWithValue(sizeof(i)));\n}\n+ }\n// Join threads to be sure that all connections have been counted.\nfor (auto const& listen_thread : listen_threads) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/socket_inet_loopback.cc", "new_path": "test/syscalls/linux/socket_inet_loopback.cc", "diff": "@@ -714,7 +714,7 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\nsockaddr_storage listen_addr = listener.addr;\nsockaddr_storage conn_addr = connector.addr;\nconstexpr int kThreadCount = 3;\n- constexpr int kConnectAttempts = 4096;\n+ constexpr int kConnectAttempts = 10000;\n// Create the listening socket.\nFileDescriptor listener_fds[kThreadCount];\n@@ -729,7 +729,7 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\nASSERT_THAT(\nbind(fd, reinterpret_cast<sockaddr*>(&listen_addr), listener.addr_len),\nSyscallSucceeds());\n- ASSERT_THAT(listen(fd, kConnectAttempts / 3), SyscallSucceeds());\n+ ASSERT_THAT(listen(fd, 40), SyscallSucceeds());\n// On the first bind we need to determine which port was bound.\nif (i != 0) {\n@@ -772,7 +772,14 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\n}\n// Receive some data from a socket to be sure that the connect()\n// system call has been completed on another side.\n- int data;\n+ // Do a short read and then close the socket to trigger a RST. This\n+ // ensures that both ends of the connection are cleaned up and no\n+ // goroutines hang around in TIME-WAIT. We do this so that this test\n+ // does not timeout under gotsan runs where lots of goroutines can\n+ // cause the test to use absurd amounts of memory.\n+ //\n+ // See: https://tools.ietf.org/html/rfc2525#page-50 section 2.17\n+ uint16_t data;\nEXPECT_THAT(\nRetryEINTR(recv)(fd.ValueOrDie().get(), &data, sizeof(data), 0),\nSyscallSucceedsWithValue(sizeof(data)));\n@@ -795,9 +802,23 @@ TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread_NoRandomSave) {\nconnector.addr_len),\nSyscallSucceeds());\n+ // Do two separate sends to ensure two segments are received. This is\n+ // required for netstack where read is incorrectly assuming a whole\n+ // segment is read when endpoint.Read() is called which is technically\n+ // incorrect as the syscall that invoked endpoint.Read() may only\n+ // consume it partially. This results in a case where a close() of\n+ // such a socket does not trigger a RST in netstack due to the\n+ // endpoint assuming that the endpoint has no unread data.\n+ EXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),\n+ SyscallSucceedsWithValue(sizeof(i)));\n+\n+ // TODO(gvisor.dev/issue/1449): Remove this block once netstack correctly\n+ // generates a RST.\n+ if (IsRunningOnGvisor()) {\nEXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),\nSyscallSucceedsWithValue(sizeof(i)));\n}\n+ }\n});\n// Join threads to be sure that all connections have been counted\n" } ]
Go
Apache License 2.0
google/gvisor
Deflake a couple of TCP syscall tests when run under gotsan. PiperOrigin-RevId: 289010316
259,962
10.01.2020 06:01:10
28,800
dacd349d6fb4fc7453b1fbf694158fd25496ed42
panic fix in retransmitTimerExpired. This is a band-aid fix for now to prevent panics.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/snd.go", "new_path": "pkg/tcpip/transport/tcp/snd.go", "diff": "@@ -442,6 +442,13 @@ func (s *sender) retransmitTimerExpired() bool {\nreturn true\n}\n+ // TODO(b/147297758): Band-aid fix, retransmitTimer can fire in some edge cases\n+ // when writeList is empty. Remove this once we have a proper fix for this\n+ // issue.\n+ if s.writeList.Front() == nil {\n+ return true\n+ }\n+\ns.ep.stack.Stats().TCP.Timeouts.Increment()\ns.ep.stats.SendErrors.Timeouts.Increment()\n" } ]
Go
Apache License 2.0
google/gvisor
panic fix in retransmitTimerExpired. This is a band-aid fix for now to prevent panics. PiperOrigin-RevId: 289078453
259,896
10.01.2020 09:05:25
28,800
9aeb053bbaf834aab5b716b8645996943262b525
Add tests for redirect port Fix indentation and change function names.
[ { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -178,14 +178,14 @@ func TestFilterInputDropDifferentUDPPort(t *testing.T) {\n}\n}\n-func TestFilterNATRedirectUDPPort(t *testing.T) {\n- if err := singleTest(FilterNATRedirectUDPPort{}); err != nil {\n+func TestNATRedirectUDPPort(t *testing.T) {\n+ if err := singleTest(NATRedirectUDPPort{}); err != nil {\nt.Fatal(err)\n}\n}\n-func TestFilterNATDropUDP(t *testing.T) {\n- if err := singleTest(FilterNATDropUDP{}); err != nil {\n+func TestNATDropUDP(t *testing.T) {\n+ if err := singleTest(NATDropUDP{}); err != nil {\nt.Fatal(err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/nat.go", "new_path": "test/iptables/nat.go", "diff": "-// Copyright 2019 The gVisor Authors.\n+// Copyright 2020 The gVisor Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n@@ -24,20 +24,20 @@ const (\n)\nfunc init() {\n- RegisterTestCase(FilterNATRedirectUDPPort{})\n- RegisterTestCase(FilterNATDropUDP{})\n+ RegisterTestCase(NATRedirectUDPPort{})\n+ RegisterTestCase(NATDropUDP{})\n}\n-// FilterInputRedirectUDPPort tests that packets are redirected to different port.\n-type FilterNATRedirectUDPPort struct{}\n+// InputRedirectUDPPort tests that packets are redirected to different port.\n+type NATRedirectUDPPort struct{}\n// Name implements TestCase.Name.\n-func (FilterNATRedirectUDPPort) Name() string {\n- return \"FilterNATRedirectUDPPort\"\n+func (NATRedirectUDPPort) Name() string {\n+ return \"NATRedirectUDPPort\"\n}\n// ContainerAction implements TestCase.ContainerAction.\n-func (FilterNATRedirectUDPPort) ContainerAction(ip net.IP) error {\n+func (NATRedirectUDPPort) ContainerAction(ip net.IP) error {\nif err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\",\nfmt.Sprintf(\"%d\", redirectPort)); err != nil {\nreturn err\n@@ -46,25 +46,24 @@ func (FilterNATRedirectUDPPort) ContainerAction(ip net.IP) error {\nif err := listenUDP(redirectPort, sendloopDuration); err != nil {\nreturn fmt.Errorf(\"packets on port %d should be allowed, but encountered an error: %v\", redirectPort, err)\n}\n-\nreturn nil\n}\n// LocalAction implements TestCase.LocalAction.\n-func (FilterNATRedirectUDPPort) LocalAction(ip net.IP) error {\n+func (NATRedirectUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n-// FilterNATDropUDP tests that packets are not received in ports other than redirect port.\n-type FilterNATDropUDP struct{}\n+// NATDropUDP tests that packets are not received in ports other than redirect port.\n+type NATDropUDP struct{}\n// Name implements TestCase.Name.\n-func (FilterNATDropUDP) Name() string {\n- return \"FilterNATDropUDP\"\n+func (NATDropUDP) Name() string {\n+ return \"NATDropUDP\"\n}\n// ContainerAction implements TestCase.ContainerAction.\n-func (FilterNATDropUDP) ContainerAction(ip net.IP) error {\n+func (NATDropUDP) ContainerAction(ip net.IP) error {\nif err := filterTable(\"-t\", \"nat\", \"-A\", \"PREROUTING\", \"-p\", \"udp\", \"-j\", \"REDIRECT\", \"--to-ports\",\nfmt.Sprintf(\"%d\", redirectPort)); err != nil {\nreturn err\n@@ -78,6 +77,6 @@ func (FilterNATDropUDP) ContainerAction(ip net.IP) error {\n}\n// LocalAction implements TestCase.LocalAction.\n-func (FilterNATDropUDP) LocalAction(ip net.IP) error {\n+func (NATDropUDP) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add tests for redirect port Fix indentation and change function names.
259,854
10.01.2020 13:33:12
28,800
6b83111499e9a8f42b6aa3998839922ba70eefdc
goid: new package Allows retrieving the goroutine ID for concurrency testing when the race detector is enabled. Updates
[ { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/BUILD", "diff": "+load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"goid\",\n+ srcs = [\n+ \"goid.go\",\n+ \"goid_amd64.s\",\n+ \"goid_race.go\",\n+ \"goid_unsafe.go\",\n+ ],\n+ importpath = \"gvisor.dev/gvisor/pkg/goid\",\n+ visibility = [\"//visibility:public\"],\n+)\n+\n+go_test(\n+ name = \"goid_test\",\n+ size = \"small\",\n+ srcs = [\n+ \"empty_test.go\",\n+ \"goid_test.go\",\n+ ],\n+ embed = [\":goid\"],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/empty_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build !race\n+\n+package goid\n+\n+import \"testing\"\n+\n+// TestNothing exists to make the build system happy.\n+func TestNothing(t *testing.T) {}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/goid.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build !race\n+\n+// Package goid provides access to the ID of the current goroutine in\n+// race/gotsan builds.\n+package goid\n+\n+// Get returns the ID of the current goroutine.\n+func Get() int64 {\n+ panic(\"unimplemented for non-race builds\")\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/goid_race.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// Only available in race/gotsan builds.\n+// +build race\n+\n+// Package goid provides access to the ID of the current goroutine in\n+// race/gotsan builds.\n+package goid\n+\n+// Get returns the ID of the current goroutine.\n+func Get() int64 {\n+ return goid()\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/goid_test.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build race\n+\n+package goid\n+\n+import (\n+ \"runtime\"\n+ \"sync\"\n+ \"testing\"\n+)\n+\n+func TestInitialGoID(t *testing.T) {\n+ const max = 10000\n+ if id := goid(); id < 0 || id > max {\n+ t.Errorf(\"got goid = %d, want 0 < goid <= %d\", id, max)\n+ }\n+}\n+\n+// TestGoIDSquence verifies that goid returns values which could plausibly be\n+// goroutine IDs. If this test breaks or becomes flaky, the structs in\n+// goid_unsafe.go may need to be updated.\n+func TestGoIDSquence(t *testing.T) {\n+ // Goroutine IDs are cached by each P.\n+ runtime.GOMAXPROCS(1)\n+\n+ // Fill any holes in lower range.\n+ for i := 0; i < 50; i++ {\n+ var wg sync.WaitGroup\n+ wg.Add(1)\n+ go func() {\n+ wg.Done()\n+\n+ // Leak the goroutine to prevent the ID from being\n+ // reused.\n+ select {}\n+ }()\n+ wg.Wait()\n+ }\n+\n+ id := goid()\n+ for i := 0; i < 100; i++ {\n+ var (\n+ newID int64\n+ wg sync.WaitGroup\n+ )\n+ wg.Add(1)\n+ go func() {\n+ newID = goid()\n+ wg.Done()\n+\n+ // Leak the goroutine to prevent the ID from being\n+ // reused.\n+ select {}\n+ }()\n+ wg.Wait()\n+ if max := id + 100; newID <= id || newID > max {\n+ t.Errorf(\"unexpected goroutine ID pattern, got goid = %d, want %d < goid <= %d (previous = %d)\", newID, id, max, id)\n+ }\n+ id = newID\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/goid/goid_unsafe.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package goid\n+\n+// Structs from Go runtime. These may change in the future and require\n+// updating. These structs are currently the same on both AMD64 and ARM64,\n+// but may diverge in the future.\n+\n+type stack struct {\n+ lo uintptr\n+ hi uintptr\n+}\n+\n+type gobuf struct {\n+ sp uintptr\n+ pc uintptr\n+ g uintptr\n+ ctxt uintptr\n+ ret uint64\n+ lr uintptr\n+ bp uintptr\n+}\n+\n+type g struct {\n+ stack stack\n+ stackguard0 uintptr\n+ stackguard1 uintptr\n+\n+ _panic uintptr\n+ _defer uintptr\n+ m uintptr\n+ sched gobuf\n+ syscallsp uintptr\n+ syscallpc uintptr\n+ stktopsp uintptr\n+ param uintptr\n+ atomicstatus uint32\n+ stackLock uint32\n+ goid int64\n+\n+ // More fields...\n+ //\n+ // We only use goid and the fields before it are only listed to\n+ // calculate the correct offset.\n+}\n+\n+func getg() *g\n+\n+// goid returns the ID of the current goroutine.\n+func goid() int64 {\n+ return getg().goid\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
goid: new package Allows retrieving the goroutine ID for concurrency testing when the race detector is enabled. Updates #1472 PiperOrigin-RevId: 289155308
260,004
10.01.2020 14:30:33
28,800
bcedf6a8e48b958e39ad7a7dba908354620a0d09
Put CancellableTimer tests in the tcpip_test package CancellableTimer tests were in a timer_test package but lived within the tcpip directory. This caused issues with go tools.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/BUILD", "new_path": "pkg/tcpip/BUILD", "diff": "@@ -30,7 +30,7 @@ go_test(\n)\ngo_test(\n- name = \"timer_test\",\n+ name = \"tcpip_x_test\",\nsize = \"small\",\nsrcs = [\"timer_test.go\"],\ndeps = [\":tcpip\"],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/timer_test.go", "new_path": "pkg/tcpip/timer_test.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package timer_test\n+package tcpip_test\nimport (\n\"sync\"\n" } ]
Go
Apache License 2.0
google/gvisor
Put CancellableTimer tests in the tcpip_test package CancellableTimer tests were in a timer_test package but lived within the tcpip directory. This caused issues with go tools. PiperOrigin-RevId: 289166345
259,847
10.01.2020 16:34:59
28,800
bf6429b944aed6de073c62ceb446cfaed5042dbc
Don't set RWF_HIPRI on InvalidOffset test. This test fails on ubuntu 18.04 because preadv2 for some reason returns EOPNOTSUPP instead of EINVAL. Instead of root-causing the failure, I'm dropping the flag in the preadv2 call since it isn't under test in this scenario.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/preadv2.cc", "new_path": "test/syscalls/linux/preadv2.cc", "diff": "@@ -202,7 +202,7 @@ TEST(Preadv2Test, TestInvalidOffset) {\niov[0].iov_len = 0;\nEXPECT_THAT(preadv2(fd.get(), iov.get(), /*iovcnt=*/1, /*offset=*/-8,\n- /*flags=*/RWF_HIPRI),\n+ /*flags=*/0),\nSyscallFailsWithErrno(EINVAL));\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Don't set RWF_HIPRI on InvalidOffset test. This test fails on ubuntu 18.04 because preadv2 for some reason returns EOPNOTSUPP instead of EINVAL. Instead of root-causing the failure, I'm dropping the flag in the preadv2 call since it isn't under test in this scenario. PiperOrigin-RevId: 289188358
259,891
10.01.2020 18:07:15
28,800
d793677cd424fef10ac0b080871d181db0bcdec0
I think INPUT works with protocol
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -25,6 +25,7 @@ import (\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/syserr\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n\"gvisor.dev/gvisor/pkg/tcpip/iptables\"\n\"gvisor.dev/gvisor/pkg/tcpip/stack\"\n)\n@@ -455,7 +456,7 @@ func filterFromIPTIP(iptip linux.IPTIP) (iptables.IPHeaderFilter, *syserr.Error)\nreturn iptables.IPHeaderFilter{}, syserr.ErrInvalidArgument\n}\nreturn iptables.IPHeaderFilter{\n- Protocol: iptip.Protocol,\n+ Protocol: tcpip.TransportProtocolNumber(iptip.Protocol),\n}, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/BUILD", "new_path": "pkg/tcpip/iptables/BUILD", "diff": "@@ -14,5 +14,6 @@ go_library(\ndeps = [\n\"//pkg/log\",\n\"//pkg/tcpip\",\n+ \"//pkg/tcpip/header\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -21,6 +21,7 @@ import (\n\"gvisor.dev/gvisor/pkg/log\"\n\"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\nconst (\n@@ -183,12 +184,13 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\npanic(fmt.Sprintf(\"Traversed past the entire list of iptables rules in table %q.\", tablename))\n}\n+// Precondition: pk.NetworkHeader is set.\nfunc (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ruleIdx int) Verdict {\nrule := table.Rules[ruleIdx]\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\n- if rule.Filter.Protocol != pkt.Protocol {\n+ if rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\nreturn Continue\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -173,7 +173,7 @@ type IPHeaderFilter struct {\nInputInterface string\nOutputInterfaceMask string\nInputInterfaceMask string\n- Protocol uint16\n+ Protocol tcpip.TransportProtocolNumber\nFlags uint8\nInverseFlags uint8\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -353,7 +353,8 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt tcpip.PacketBuffer) {\n}\npkt.NetworkHeader = headerView[:h.HeaderLength()]\n- // iptables filtering.\n+ // iptables filtering. All packets that reach here are intended for\n+ // this machine and will not be forwarded.\nipt := e.stack.IPTables()\nif ok := ipt.Check(iptables.Input, pkt); !ok {\n// iptables is telling us to drop the packet.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/packet_buffer.go", "new_path": "pkg/tcpip/packet_buffer.go", "diff": "package tcpip\n-import \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+import (\n+ \"gvisor.dev/gvisor/pkg/tcpip/buffer\"\n+)\n// A PacketBuffer contains all the data of a network packet.\n//\n@@ -65,3 +67,24 @@ func (pk PacketBuffer) Clone() PacketBuffer {\npk.Data = pk.Data.Clone(nil)\nreturn pk\n}\n+\n+//// TransportProtocol returns the transport protocol of pk.\n+////\n+//// Precondition: pk.NetworkHeader is set.\n+//func (pk PacketBuffer) TransportProtocolIPv4() uint16 {\n+// if pk.NetworkHeader == nil {\n+// panic(\"This should only be called when pk.NetworkHeader is set.\")\n+// }\n+// return header.IPv4(pk.NetworkHeader).TransportProtocol()\n+//}\n+\n+// func (pk Packet) findNetHeader() header.IPv4 {\n+// // Inbound:\n+// // Data holds everything, but may have had some headers shaved off.\n+// // Figure out whether it's set or still somewhere in data and return\n+// // appropriately.\n+\n+// // Outbound:\n+// // NetworkHeader will be set if we've added one. Otherwise there's no\n+// // header.\n+// }\n" } ]
Go
Apache License 2.0
google/gvisor
I think INPUT works with protocol
259,896
13.01.2020 09:11:40
28,800
98327a94cce7597589ac22b8557c5d9a2a03464d
Add test for iptables TCP rule Added tests for tcp protocol with input and output rules including options sport and dport Increased timeout in iptables_test as TCP tests were timing out with existing value.
[ { "change_type": "MODIFY", "old_path": "test/iptables/BUILD", "new_path": "test/iptables/BUILD", "diff": "@@ -6,6 +6,7 @@ go_library(\nname = \"iptables\",\nsrcs = [\n\"filter_input.go\",\n+ \"filter_output.go\",\n\"iptables.go\",\n\"iptables_util.go\",\n\"nat.go\",\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "@@ -31,6 +31,8 @@ func init() {\nRegisterTestCase(FilterInputDropUDP{})\nRegisterTestCase(FilterInputDropUDPPort{})\nRegisterTestCase(FilterInputDropDifferentUDPPort{})\n+ RegisterTestCase(FilterInputDropTCPDestPort{})\n+ RegisterTestCase(FilterInputDropTCPSrcPort{})\n}\n// FilterInputDropUDP tests that we can drop UDP traffic.\n@@ -122,3 +124,67 @@ func (FilterInputDropDifferentUDPPort) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropDifferentUDPPort) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, acceptPort, sendloopDuration)\n}\n+\n+// FilterInputDropTCP tests that connections are not accepted on specified source ports.\n+type FilterInputDropTCPDestPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDropTCPDestPort) Name() string {\n+ return \"FilterInputDropTCPDestPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDropTCPDestPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--dport\",\n+ fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for TCP packets on drop port.\n+ if err := listenTCP(dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"Connections on port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDropTCPDestPort) LocalAction(ip net.IP) error {\n+ if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"Connection destined to port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// FilterInputDropTCPSrcPort tests that connections are not accepted on specified source ports.\n+type FilterInputDropTCPSrcPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterInputDropTCPSrcPort) Name() string {\n+ return \"FilterInputDropTCPSrcPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterInputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--sport\",\n+ fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for TCP packets on accept port.\n+ if err := listenTCP(acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connections destined to port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterInputDropTCPSrcPort) LocalAction(ip net.IP) error {\n+ if err := connectTCP(ip, acceptPort, dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connection sent from port %d should not be accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "test/iptables/filter_output.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package iptables\n+\n+import (\n+ \"fmt\"\n+ \"net\"\n+)\n+\n+func init() {\n+ RegisterTestCase(FilterOutputDropTCPDestPort{})\n+ RegisterTestCase(FilterOutputDropTCPSrcPort{})\n+}\n+\n+// FilterOutputDropTCPDestPort tests that connections are not accepted on specified source ports.\n+type FilterOutputDropTCPDestPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterOutputDropTCPDestPort) Name() string {\n+ return \"FilterOutputDropTCPDestPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterOutputDropTCPDestPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"OUTPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--dport\",\n+ fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for TCP packets on accept port.\n+ if err := listenTCP(acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connections destined to port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterOutputDropTCPDestPort) LocalAction(ip net.IP) error {\n+ if err := connectTCP(ip, acceptPort, dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connection sent from port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// FilterOutputDropTCPSrcPort tests that connections are not accepted on specified source ports.\n+type FilterOutputDropTCPSrcPort struct{}\n+\n+// Name implements TestCase.Name.\n+func (FilterOutputDropTCPSrcPort) Name() string {\n+ return \"FilterOutputDropTCPSrcPort\"\n+}\n+\n+// ContainerAction implements TestCase.ContainerAction.\n+func (FilterOutputDropTCPSrcPort) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"OUTPUT\", \"-p\", \"tcp\", \"-m\", \"tcp\", \"--sport\",\n+ fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+\n+ // Listen for TCP packets on drop port.\n+ if err := listenTCP(dropPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connections on port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n+\n+// LocalAction implements TestCase.LocalAction.\n+func (FilterOutputDropTCPSrcPort) LocalAction(ip net.IP) error {\n+ if err := connectTCP(ip, dropPort, acceptPort, sendloopDuration); err == nil {\n+ return fmt.Errorf(\"connection destined to port %d should not be accepted, but got accepted\", dropPort)\n+ }\n+\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_test.go", "new_path": "test/iptables/iptables_test.go", "diff": "@@ -28,7 +28,7 @@ import (\n\"gvisor.dev/gvisor/runsc/testutil\"\n)\n-const timeout time.Duration = 10 * time.Second\n+const timeout time.Duration = 18 * time.Second\nvar image = flag.String(\"image\", \"bazel/test/iptables/runner:runner\", \"image to run tests in\")\n@@ -189,3 +189,27 @@ func TestNATDropUDP(t *testing.T) {\nt.Fatal(err)\n}\n}\n+\n+func TestFilterInputDropTCPDestPort(t *testing.T) {\n+ if err := singleTest(FilterInputDropTCPDestPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterInputDropTCPSrcPort(t *testing.T) {\n+ if err := singleTest(FilterInputDropTCPSrcPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterOutputDropTCPDestPort(t *testing.T) {\n+ if err := singleTest(FilterOutputDropTCPDestPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n+\n+func TestFilterOutputDropTCPSrcPort(t *testing.T) {\n+ if err := singleTest(FilterOutputDropTCPSrcPort{}); err != nil {\n+ t.Fatal(err)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/iptables_util.go", "new_path": "test/iptables/iptables_util.go", "diff": "@@ -80,3 +80,58 @@ func sendUDPLoop(ip net.IP, port int, duration time.Duration) error {\nreturn nil\n}\n+\n+// listenTCP listens for connections on a TCP port\n+func listenTCP(port int, timeout time.Duration) error {\n+ localAddr := net.TCPAddr{\n+ Port: port,\n+ }\n+\n+ // Starts listening on port\n+ lConn, err := net.ListenTCP(\"tcp4\", &localAddr)\n+ if err != nil {\n+ return err\n+ }\n+ defer lConn.Close()\n+\n+ // Accept connections on port\n+ lConn.SetDeadline(time.Now().Add(timeout))\n+ conn, err := lConn.AcceptTCP()\n+ if err == nil {\n+ conn.Close()\n+ }\n+ return err\n+}\n+\n+// connectTCP connects the TCP server over specified local port, server IP\n+// and remote/server port\n+func connectTCP(ip net.IP, remotePort int, localPort int, duration time.Duration) error {\n+ remote := net.TCPAddr{\n+ IP: ip,\n+ Port: remotePort,\n+ }\n+\n+ local := net.TCPAddr{\n+ Port: localPort,\n+ }\n+\n+ // Container may not be up. Retry DialTCP\n+ // over a given duration\n+ to := time.After(duration)\n+ var res error\n+ for timedOut := false; !timedOut; {\n+ conn, err := net.DialTCP(\"tcp4\", &local, &remote)\n+ res = err\n+ if res == nil {\n+ conn.Close()\n+ return nil\n+ }\n+ select{\n+ case <-to:\n+ timedOut = true\n+ default:\n+ time.Sleep(200 * time.Millisecond)\n+ }\n+ }\n+ return res\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add test for iptables TCP rule Added tests for tcp protocol with input and output rules including options sport and dport Increased timeout in iptables_test as TCP tests were timing out with existing value.
259,853
13.01.2020 10:14:30
28,800
f54b9c0ee6e02f9c8bf32aa268c9028ff741bf7c
tests: fix errors detected by asan.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/inotify.cc", "new_path": "test/syscalls/linux/inotify.cc", "diff": "@@ -977,7 +977,7 @@ TEST(Inotify, WatchOnRelativePath) {\nASSERT_NO_ERRNO_AND_VALUE(Open(file1.path(), O_RDONLY));\n// Change working directory to root.\n- const char* old_working_dir = get_current_dir_name();\n+ const FileDescriptor cwd = ASSERT_NO_ERRNO_AND_VALUE(Open(\".\", O_PATH));\nEXPECT_THAT(chdir(root.path().c_str()), SyscallSucceeds());\n// Add a watch on file1 with a relative path.\n@@ -997,7 +997,7 @@ TEST(Inotify, WatchOnRelativePath) {\n// continue to hold a reference, random save/restore tests can fail if a save\n// is triggered after \"root\" is unlinked; we can't save deleted fs objects\n// with active references.\n- EXPECT_THAT(chdir(old_working_dir), SyscallSucceeds());\n+ EXPECT_THAT(fchdir(cwd.get()), SyscallSucceeds());\n}\nTEST(Inotify, ZeroLengthReadWriteDoesNotGenerateEvent) {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/poll.cc", "new_path": "test/syscalls/linux/poll.cc", "diff": "@@ -275,7 +275,8 @@ TEST_F(PollTest, Nfds) {\n// Each entry in the 'fds' array refers to the eventfd and polls for\n// \"writable\" events (events=POLLOUT). This essentially guarantees that the\n// poll() is a no-op and allows negative testing of the 'nfds' parameter.\n- std::vector<struct pollfd> fds(max_fds, {.fd = efd.get(), .events = POLLOUT});\n+ std::vector<struct pollfd> fds(max_fds + 1,\n+ {.fd = efd.get(), .events = POLLOUT});\n// Verify that 'nfds' up to RLIMIT_NOFILE are allowed.\nEXPECT_THAT(RetryEINTR(poll)(fds.data(), 1, 1), SyscallSucceedsWithValue(1));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/readv_common.cc", "new_path": "test/syscalls/linux/readv_common.cc", "diff": "@@ -154,7 +154,7 @@ void ReadBuffersOverlapping(int fd) {\nchar* expected_ptr = expected.data();\nmemcpy(expected_ptr, &kReadvTestData[overlap_bytes], overlap_bytes);\nmemcpy(&expected_ptr[overlap_bytes], &kReadvTestData[overlap_bytes],\n- kReadvTestDataSize);\n+ kReadvTestDataSize - overlap_bytes);\nstruct iovec iovs[2];\niovs[0].iov_base = buffer.data();\n" } ]
Go
Apache License 2.0
google/gvisor
tests: fix errors detected by asan. PiperOrigin-RevId: 289467083
259,853
13.01.2020 13:08:36
28,800
fff04769518b279a364c928307a71055eaa6166d
benchmarks/tcp: set a number of channels to GOMAXPROCS Updates
[ { "change_type": "MODIFY", "old_path": "benchmarks/tcp/tcp_benchmark.sh", "new_path": "benchmarks/tcp/tcp_benchmark.sh", "diff": "@@ -41,6 +41,8 @@ duplicate=0.1 # 0.1% means duplicates are 1/10x as frequent as losses.\nduration=30 # 30s is enough time to consistent results (experimentally).\nhelper_dir=$(dirname $0)\nnetstack_opts=\n+disable_linux_gso=\n+num_client_threads=1\n# Check for netem support.\nlsmod_output=$(lsmod | grep sch_netem)\n@@ -125,6 +127,13 @@ while [ $# -gt 0 ]; do\nshift\nnetstack_opts=\"${netstack_opts} -memprofile=$1\"\n;;\n+ --disable-linux-gso)\n+ disable_linux_gso=1\n+ ;;\n+ --num-client-threads)\n+ shift\n+ num_client_threads=$1\n+ ;;\n--helpers)\nshift\n[ \"$#\" -le 0 ] && echo \"no helper dir provided\" && exit 1\n@@ -147,6 +156,8 @@ while [ $# -gt 0 ]; do\necho \" --loss set the loss probability (%)\"\necho \" --duplicate set the duplicate probability (%)\"\necho \" --helpers set the helper directory\"\n+ echo \" --num-client-threads number of parallel client threads to run\"\n+ echo \" --disable-linux-gso disable segmentation offload in the Linux network stack\"\necho \"\"\necho \"The output will of the script will be:\"\necho \" <throughput> <client-cpu-usage> <server-cpu-usage>\"\n@@ -301,6 +312,14 @@ fi\n# Add client and server addresses, and bring everything up.\n${nsjoin_binary} /tmp/client.netns ip addr add ${client_addr}/${mask} dev client.0\n${nsjoin_binary} /tmp/server.netns ip addr add ${server_addr}/${mask} dev server.0\n+if [ \"${disable_linux_gso}\" == \"1\" ]; then\n+ ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 tso off\n+ ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gro off\n+ ${nsjoin_binary} /tmp/client.netns ethtool -K client.0 gso off\n+ ${nsjoin_binary} /tmp/server.netns ethtool -K server.0 tso off\n+ ${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gso off\n+ ${nsjoin_binary} /tmp/server.netns ethtool -K server.0 gro off\n+fi\n${nsjoin_binary} /tmp/client.netns ip link set client.0 up\n${nsjoin_binary} /tmp/client.netns ip link set lo up\n${nsjoin_binary} /tmp/server.netns ip link set server.0 up\n@@ -338,7 +357,7 @@ trap cleanup EXIT\n# Run the benchmark, recording the results file.\nwhile ${nsjoin_binary} /tmp/client.netns iperf \\\\\n- -p ${proxy_port} -c ${client_addr} -t ${duration} -f m 2>&1 \\\\\n+ -p ${proxy_port} -c ${client_addr} -t ${duration} -f m -P ${num_client_threads} 2>&1 \\\\\n| tee \\$results_file \\\\\n| grep \"connect failed\" >/dev/null; do\nsleep 0.1 # Wait for all services.\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/tcp/tcp_proxy.go", "new_path": "benchmarks/tcp/tcp_proxy.go", "diff": "@@ -94,11 +94,11 @@ type netstackImpl struct {\nmode string\n}\n-func setupNetwork(ifaceName string) (fd int, err error) {\n+func setupNetwork(ifaceName string, numChannels int) (fds []int, err error) {\n// Get all interfaces in the namespace.\nifaces, err := net.Interfaces()\nif err != nil {\n- return -1, fmt.Errorf(\"querying interfaces: %v\", err)\n+ return nil, fmt.Errorf(\"querying interfaces: %v\", err)\n}\nfor _, iface := range ifaces {\n@@ -107,9 +107,11 @@ func setupNetwork(ifaceName string) (fd int, err error) {\n}\n// Create the socket.\nconst protocol = 0x0300 // htons(ETH_P_ALL)\n+ fds := make([]int, numChannels)\n+ for i := range fds {\nfd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, protocol)\nif err != nil {\n- return -1, fmt.Errorf(\"unable to create raw socket: %v\", err)\n+ return nil, fmt.Errorf(\"unable to create raw socket: %v\", err)\n}\n// Bind to the appropriate device.\n@@ -119,27 +121,29 @@ func setupNetwork(ifaceName string) (fd int, err error) {\nPkttype: syscall.PACKET_HOST,\n}\nif err := syscall.Bind(fd, &ll); err != nil {\n- return -1, fmt.Errorf(\"unable to bind to %q: %v\", iface.Name, err)\n+ return nil, fmt.Errorf(\"unable to bind to %q: %v\", iface.Name, err)\n}\n// RAW Sockets by default have a very small SO_RCVBUF of 256KB,\n// up it to at least 1MB to reduce packet drops.\nif err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, rcvBufSize); err != nil {\n- return -1, fmt.Errorf(\"setsockopt(..., SO_RCVBUF, %v,..) = %v\", rcvBufSize, err)\n+ return nil, fmt.Errorf(\"setsockopt(..., SO_RCVBUF, %v,..) = %v\", rcvBufSize, err)\n}\nif !*swgso && *gso != 0 {\nif err := syscall.SetsockoptInt(fd, syscall.SOL_PACKET, unix.PACKET_VNET_HDR, 1); err != nil {\n- return -1, fmt.Errorf(\"unable to enable the PACKET_VNET_HDR option: %v\", err)\n+ return nil, fmt.Errorf(\"unable to enable the PACKET_VNET_HDR option: %v\", err)\n}\n}\n- return fd, nil\n+ fds[i] = fd\n}\n- return -1, fmt.Errorf(\"failed to find interface: %v\", ifaceName)\n+ return fds, nil\n+ }\n+ return nil, fmt.Errorf(\"failed to find interface: %v\", ifaceName)\n}\nfunc newNetstackImpl(mode string) (impl, error) {\n- fd, err := setupNetwork(*iface)\n+ fds, err := setupNetwork(*iface, runtime.GOMAXPROCS(-1))\nif err != nil {\nreturn nil, err\n}\n@@ -177,7 +181,7 @@ func newNetstackImpl(mode string) (impl, error) {\nmac[0] &^= 0x1 // Clear multicast bit.\nmac[0] |= 0x2 // Set local assignment bit (IEEE802).\nep, err := fdbased.New(&fdbased.Options{\n- FDs: []int{fd},\n+ FDs: fds,\nMTU: uint32(*mtu),\nEthernetHeader: true,\nAddress: tcpip.LinkAddress(mac),\n" } ]
Go
Apache License 2.0
google/gvisor
benchmarks/tcp: set a number of channels to GOMAXPROCS Updates #231 PiperOrigin-RevId: 289502669
259,891
13.01.2020 14:14:49
28,800
36641a21953b72d64d4378d4974ef467e901a5fe
Only allow INPUT modifications.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -365,9 +365,22 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\n}\n+ // TODO(gvisor.dev/issue/170): Support other chains.\n+ // Since we only support modifying the INPUT chain right now, make sure\n+ // all other chains point to ACCEPT rules.\n+ for hook, ruleIdx := range table.BuiltinChains {\n+ if hook != iptables.Input {\n+ if _, ok := table.Rules[ruleIdx].Target.(iptables.UnconditionalAcceptTarget); !ok {\n+ log.Warningf(\"Hook %d is unsupported.\", hook)\n+ return syserr.ErrInvalidArgument\n+ }\n+ }\n+ }\n+\n// TODO(gvisor.dev/issue/170): Check the following conditions:\n// - There are no loops.\n// - There are no chains without an unconditional final rule.\n+ // - There are no chains without an unconditional underflow rule.\nipt := stack.IPTables()\ntable.SetMetadata(metadata{\n" } ]
Go
Apache License 2.0
google/gvisor
Only allow INPUT modifications.
259,891
13.01.2020 14:54:32
28,800
1c3d3c70b93d483894dd49fb444171347f0ca250
Fix test building.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ip_test.go", "new_path": "pkg/tcpip/network/ip_test.go", "diff": "@@ -212,10 +212,17 @@ func buildIPv6Route(local, remote tcpip.Address) (stack.Route, *tcpip.Error) {\nreturn s.FindRoute(1, local, remote, ipv6.ProtocolNumber, false /* multicastLoop */)\n}\n+func buildDummyStack() *stack.Stack {\n+ return stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol(), tcp.NewProtocol()},\n+ })\n+}\n+\nfunc TestIPv4Send(t *testing.T) {\no := testObject{t: t, v4: true}\nproto := ipv4.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, nil, &o)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, nil, &o, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -250,7 +257,7 @@ func TestIPv4Send(t *testing.T) {\nfunc TestIPv4Receive(t *testing.T) {\no := testObject{t: t, v4: true}\nproto := ipv4.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -318,7 +325,7 @@ func TestIPv4ReceiveControl(t *testing.T) {\nt.Run(c.name, func(t *testing.T) {\no := testObject{t: t}\nproto := ipv4.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -385,7 +392,7 @@ func TestIPv4ReceiveControl(t *testing.T) {\nfunc TestIPv4FragmentationReceive(t *testing.T) {\no := testObject{t: t, v4: true}\nproto := ipv4.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv4Addr, localIpv4PrefixLen}, nil, &o, nil, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -456,7 +463,7 @@ func TestIPv4FragmentationReceive(t *testing.T) {\nfunc TestIPv6Send(t *testing.T) {\no := testObject{t: t}\nproto := ipv6.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, nil, &o)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, nil, &o, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -491,7 +498,7 @@ func TestIPv6Send(t *testing.T) {\nfunc TestIPv6Receive(t *testing.T) {\no := testObject{t: t}\nproto := ipv6.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, &o, nil)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, &o, nil, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n@@ -568,7 +575,7 @@ func TestIPv6ReceiveControl(t *testing.T) {\nt.Run(c.name, func(t *testing.T) {\no := testObject{t: t}\nproto := ipv6.NewProtocol()\n- ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, &o, nil)\n+ ep, err := proto.NewEndpoint(1, tcpip.AddressWithPrefix{localIpv6Addr, localIpv6PrefixLen}, nil, &o, nil, buildDummyStack())\nif err != nil {\nt.Fatalf(\"NewEndpoint failed: %v\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/icmp_test.go", "new_path": "pkg/tcpip/network/ipv6/icmp_test.go", "diff": "@@ -109,7 +109,7 @@ func TestICMPCounts(t *testing.T) {\nif netProto == nil {\nt.Fatalf(\"cannot find protocol instance for network protocol %d\", ProtocolNumber)\n}\n- ep, err := netProto.NewEndpoint(0, tcpip.AddressWithPrefix{lladdr1, netProto.DefaultPrefixLen()}, &stubLinkAddressCache{}, &stubDispatcher{}, nil)\n+ ep, err := netProto.NewEndpoint(0, tcpip.AddressWithPrefix{lladdr1, netProto.DefaultPrefixLen()}, &stubLinkAddressCache{}, &stubDispatcher{}, nil, s)\nif err != nil {\nt.Fatalf(\"NewEndpoint(_) = _, %s, want = _, nil\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv6/ndp_test.go", "new_path": "pkg/tcpip/network/ipv6/ndp_test.go", "diff": "@@ -62,7 +62,7 @@ func setupStackAndEndpoint(t *testing.T, llladdr, rlladdr tcpip.Address) (*stack\nt.Fatalf(\"cannot find protocol instance for network protocol %d\", ProtocolNumber)\n}\n- ep, err := netProto.NewEndpoint(0, tcpip.AddressWithPrefix{rlladdr, netProto.DefaultPrefixLen()}, &stubLinkAddressCache{}, &stubDispatcher{}, nil)\n+ ep, err := netProto.NewEndpoint(0, tcpip.AddressWithPrefix{rlladdr, netProto.DefaultPrefixLen()}, &stubLinkAddressCache{}, &stubDispatcher{}, nil, s)\nif err != nil {\nt.Fatalf(\"NewEndpoint(_) = _, %s, want = _, nil\", err)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/stack_test.go", "new_path": "pkg/tcpip/stack/stack_test.go", "diff": "@@ -200,7 +200,7 @@ func (*fakeNetworkProtocol) ParseAddresses(v buffer.View) (src, dst tcpip.Addres\nreturn tcpip.Address(v[1:2]), tcpip.Address(v[0:1])\n}\n-func (f *fakeNetworkProtocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, ep stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {\n+func (f *fakeNetworkProtocol) NewEndpoint(nicID tcpip.NICID, addrWithPrefix tcpip.AddressWithPrefix, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, ep stack.LinkEndpoint, _ *stack.Stack) (stack.NetworkEndpoint, *tcpip.Error) {\nreturn &fakeNetworkEndpoint{\nnicID: nicID,\nid: stack.NetworkEndpointID{LocalAddress: addrWithPrefix.Address},\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -1228,7 +1228,10 @@ func TestTTL(t *testing.T) {\n} else {\np = ipv6.NewProtocol()\n}\n- ep, err := p.NewEndpoint(0, tcpip.AddressWithPrefix{}, nil, nil, nil)\n+ ep, err := p.NewEndpoint(0, tcpip.AddressWithPrefix{}, nil, nil, nil, stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ }))\nif err != nil {\nt.Fatal(err)\n}\n@@ -1261,7 +1264,10 @@ func TestSetTTL(t *testing.T) {\n} else {\np = ipv6.NewProtocol()\n}\n- ep, err := p.NewEndpoint(0, tcpip.AddressWithPrefix{}, nil, nil, nil)\n+ ep, err := p.NewEndpoint(0, tcpip.AddressWithPrefix{}, nil, nil, nil, stack.New(stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ }))\nif err != nil {\nt.Fatal(err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Fix test building.
259,891
13.01.2020 16:10:00
28,800
bd292894097ffdf316bc78d81aebd0a2988124f3
Protocol filtering works.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -187,7 +187,7 @@ func (it *IPTables) checkRule(hook Hook, pkt tcpip.PacketBuffer, table Table, ru\n// First check whether the packet matches the IP header filter.\n// TODO(gvisor.dev/issue/170): Support other fields of the filter.\n- if rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\n+ if rule.Filter.Protocol != 0 && rule.Filter.Protocol != header.IPv4(pkt.NetworkHeader).TransportProtocol() {\nreturn Continue\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Protocol filtering works.
259,884
05.12.2019 20:54:13
18,000
eef069778b020e02d36c546ce9c92894254a75aa
Build runsc in Docker container This removes the build dependency on Bazel.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -58,7 +58,17 @@ node_modules: package.json package-lock.json\n$(NPM) ci\nupstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc: upstream-gvisor\n- cd upstream/gvisor && bazel build runsc\n+ mkdir -p /tmp/gvisor-website/build_output\n+ docker run \\\n+ -v $(PWD)/upstream/gvisor:/workspace \\\n+ -v /tmp/gvisor-website/build_output:/tmp/gvisor-website/build_output \\\n+ -w /workspace \\\n+ --entrypoint 'sh' \\\n+ l.gcr.io/google/bazel \\\n+ -c '\\\n+ groupadd --gid $(shell id -g) $(shell id -gn) && \\\n+ useradd --uid $(shell id -u) --gid $(shell id -g) -ms /bin/bash $(USER) && \\\n+ su $(USER) -c \"bazel --output_user_root=/tmp/gvisor-website/build_output build //runsc\"'\nbin/generate-syscall-docs: $(GEN_SOURCE)\nmkdir -p bin/\n" } ]
Go
Apache License 2.0
google/gvisor
Build runsc in Docker container This removes the build dependency on Bazel.
259,884
05.12.2019 20:55:19
18,000
89ac3bdc31d85412a9ce2073e96313588f6fb636
Run npm in Docker image. This partially removes the build dependency on node.js.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "HUGO := hugo\nHUGO_VERSION := 0.53\nHTMLPROOFER_VERSION := 3.10.2\n-NPM := npm\nGCLOUD := gcloud\nGCP_PROJECT := gvisor-website\n@@ -55,7 +54,14 @@ static-staging: compatibility-docs node_modules config.toml $(shell find archety\nnode_modules: package.json package-lock.json\n# Use npm ci because npm install will update the package-lock.json.\n# See: https://github.com/npm/npm/issues/18286\n- $(NPM) ci\n+ docker run \\\n+ -e USER=\"$(shell id -u)\" \\\n+ -e HOME=\"/tmp\" \\\n+ -u=\"$(shell id -u):$(shell id -g)\" \\\n+ -v $(PWD):/workspace \\\n+ -w /workspace \\\n+ --entrypoint 'npm' \\\n+ node ci\nupstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc: upstream-gvisor\nmkdir -p /tmp/gvisor-website/build_output\n" } ]
Go
Apache License 2.0
google/gvisor
Run npm in Docker image. This partially removes the build dependency on node.js.
259,884
06.12.2019 08:37:19
18,000
6e5080f5dc3527b2382bd2a91f7d5eace4793b17
Use hugo Docker image in Makefile Removes the local dependency on hugo for building.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "-HUGO := hugo\nHUGO_VERSION := 0.53\nHTMLPROOFER_VERSION := 3.10.2\nGCLOUD := gcloud\n@@ -43,12 +42,29 @@ content/docs/community/sigs: upstream/community $(wildcard upstream/community/si\n$(APP_TARGET): public $(APP_SOURCE)\ncp -a cmd/gvisor-website/$(patsubst public/%,%,$@) public/\n-static-production: compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n- HUGO_ENV=\"production\" $(HUGO)\n+static-production: hugo-docker-image compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n+ docker run \\\n+ -e HUGO_ENV=\"production\" \\\n+ -e USER=\"$(shell id -u)\" \\\n+ -e HOME=\"/tmp\" \\\n+ -u=\"$(shell id -u):$(shell id -g)\" \\\n+ -v $(PWD):/workspace \\\n+ -w /workspace \\\n+ gcr.io/gvisor-website/hugo:$(HUGO_VERSION) \\\n+ hugo\n.PHONY: static-production\n-static-staging: compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n- $(HUGO) -b \"https://staging-$(shell git branch | grep \\* | cut -d ' ' -f2)-dot-gvisor-website.appspot.com\"\n+static-staging: hugo-docker-image compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\n+ docker run \\\n+ -e HUGO_ENV=\"production\" \\\n+ -e USER=\"$(shell id -u)\" \\\n+ -e HOME=\"/tmp\" \\\n+ -u=\"$(shell id -u):$(shell id -g)\" \\\n+ -v $(PWD):/workspace \\\n+ -w /workspace \\\n+ gcr.io/gvisor-website/hugo:$(HUGO_VERSION) \\\n+ hugo \\\n+ -b \"https://staging-$(shell git branch | grep \\* | cut -d ' ' -f2)-dot-gvisor-website.appspot.com\"\n.PHONY: static-staging\nnode_modules: package.json package-lock.json\n@@ -84,13 +100,24 @@ compatibility-docs: bin/generate-syscall-docs upstream/gvisor/bazel-bin/runsc/li\n./upstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc help syscalls -o json | ./bin/generate-syscall-docs -out ./content/docs/user_guide/compatibility/\n.PHONY: compatibility-docs\n-check: website\n- docker run -v $(shell pwd)/public:/public gcr.io/gvisor-website/html-proofer:3.10.2 htmlproofer --disable-external --check-html public/static\n+check: htmlproofer-docker-image website\n+ docker run -v $(shell pwd)/public:/public gcr.io/gvisor-website/html-proofer:$(HTMLPROOFER_VERSION) htmlproofer --disable-external --check-html public/static\n.PHONY: check\n# Run a local content development server. Redirects will not be supported.\n-devserver: all-upstream compatibility-docs\n- $(HUGO) server -FD --port 8080\n+devserver: hugo-docker-image all-upstream compatibility-docs\n+ docker run \\\n+ -e USER=\"$(shell id -u)\" \\\n+ -e HOME=\"/tmp\" \\\n+ -u=\"$(shell id -u):$(shell id -g)\" \\\n+ -v $(PWD):/workspace \\\n+ -w /workspace \\\n+ -p 8080:8080 \\\n+ gcr.io/gvisor-website/hugo:$(HUGO_VERSION) \\\n+ hugo server \\\n+ -FD \\\n+ --bind 0.0.0.0 \\\n+ --port 8080\n.PHONY: server\nserver: website\n@@ -116,16 +143,14 @@ stage: all-upstream app static-staging\ncloud-build:\ngcloud builds submit --config cloudbuild.yaml .\n-# Build and push the hugo Docker image used by Cloud Build.\n+# Build the hugo Docker image.\nhugo-docker-image:\ndocker build --build-arg HUGO_VERSION=$(HUGO_VERSION) -t gcr.io/gvisor-website/hugo:$(HUGO_VERSION) cloudbuild/hugo/\n- docker push gcr.io/gvisor-website/hugo:$(HUGO_VERSION)\n.PHONY: hugo-docker-image\n-# Build and push the html-proofer image used by Cloud Build.\n+# Build the html-proofer image used by Cloud Build.\nhtmlproofer-docker-image:\ndocker build --build-arg HTMLPROOFER_VERSION=$(HTMLPROOFER_VERSION) -t gcr.io/gvisor-website/html-proofer:$(HTMLPROOFER_VERSION) cloudbuild/html-proofer/\n- docker push gcr.io/gvisor-website/html-proofer:$(HTMLPROOFER_VERSION)\n.PHONY: htmlproofer-docker-image\nclean:\n" }, { "change_type": "MODIFY", "old_path": "cloudbuild/html-proofer/Dockerfile", "new_path": "cloudbuild/html-proofer/Dockerfile", "diff": "@@ -13,7 +13,7 @@ RUN set -x \\\nlibcurl \\\nlibxml2-dev \\\nlibxslt-dev \\\n- openssh\n+ openssh \\\n&& gem install \\\nhtml-proofer:${HTMLPROOFER_VERSION} \\\nnokogiri:1.10.1 \\\n" } ]
Go
Apache License 2.0
google/gvisor
Use hugo Docker image in Makefile Removes the local dependency on hugo for building.
259,884
06.12.2019 09:05:46
18,000
2274c9929a0feff9dab29b72a8f0395077e15ad8
Add --rm to docker run commands.
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -44,6 +44,7 @@ $(APP_TARGET): public $(APP_SOURCE)\nstatic-production: hugo-docker-image compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\ndocker run \\\n+ --rm \\\n-e HUGO_ENV=\"production\" \\\n-e USER=\"$(shell id -u)\" \\\n-e HOME=\"/tmp\" \\\n@@ -56,6 +57,7 @@ static-production: hugo-docker-image compatibility-docs node_modules config.toml\nstatic-staging: hugo-docker-image compatibility-docs node_modules config.toml $(shell find archetypes assets content themes -type f | sed 's/ /\\\\ /g')\ndocker run \\\n+ --rm \\\n-e HUGO_ENV=\"production\" \\\n-e USER=\"$(shell id -u)\" \\\n-e HOME=\"/tmp\" \\\n@@ -71,6 +73,7 @@ node_modules: package.json package-lock.json\n# Use npm ci because npm install will update the package-lock.json.\n# See: https://github.com/npm/npm/issues/18286\ndocker run \\\n+ --rm \\\n-e USER=\"$(shell id -u)\" \\\n-e HOME=\"/tmp\" \\\n-u=\"$(shell id -u):$(shell id -g)\" \\\n@@ -82,6 +85,7 @@ node_modules: package.json package-lock.json\nupstream/gvisor/bazel-bin/runsc/linux_amd64_pure_stripped/runsc: upstream-gvisor\nmkdir -p /tmp/gvisor-website/build_output\ndocker run \\\n+ --rm \\\n-v $(PWD)/upstream/gvisor:/workspace \\\n-v /tmp/gvisor-website/build_output:/tmp/gvisor-website/build_output \\\n-w /workspace \\\n@@ -107,6 +111,7 @@ check: htmlproofer-docker-image website\n# Run a local content development server. Redirects will not be supported.\ndevserver: hugo-docker-image all-upstream compatibility-docs\ndocker run \\\n+ --rm \\\n-e USER=\"$(shell id -u)\" \\\n-e HOME=\"/tmp\" \\\n-u=\"$(shell id -u):$(shell id -g)\" \\\n@@ -124,11 +129,6 @@ server: website\ncd public/ && go run main.go --custom-domain localhost\n.PHONY: server\n-# Deploy the website to App Engine.\n-deploy: website\n- cd public && $(GCLOUD) app deploy\n-.PHONY: deploy\n-\n# Stage the website to App Engine at a version based on the git branch name.\nstage: all-upstream app static-staging\n# Disallow indexing staged content.\n" } ]
Go
Apache License 2.0
google/gvisor
Add --rm to docker run commands.
259,884
06.12.2019 09:14:33
18,000
039f309bc9ef9a70e0fe9f6c0372ced57b173a93
Update readme with new docs. Rearrange the docs into sections on using Github or Git locally. Remove the troubleshooting FAQ since we build using Docker.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -4,24 +4,14 @@ This repository holds the content for the gVisor website. It uses\n[hugo](https://gohugo.io/) to generate the website and\n[Docsy](https://github.com/google/docsy) as the theme.\n-## Requirements\n+## Using Github\n-Building the website requires the extended version of\n-[hugo](https://gohugo.io/) and [node.js](https://nodejs.org/) in order to\n-generate CSS files. Please install them before building.\n+The easiest way to contribute to the documentation is to use the \"Edit this\n+page\" link on any documentation page to edit the page content directly via\n+GitHub and submit a pull request. This should generally be done for changes to\n+a single page.\n-- Node.js >= 10.15.0 LTS\n-- hugo extended >= v0.53\n-\n-## Contributing to Documentation\n-\n-### Using Github\n-\n-You can use the \"Edit this page\" link on any documentation page to edit the\n-page content directly via GitHub and submit a pull request. This should\n-generally be done for relatively small changes.\n-\n-### Using Git\n+## Using Git\nYou can submit pull requests by making changes in a Git branch. See more\ninformation on GitHub pull requests\n@@ -32,47 +22,37 @@ Documentation is written in markdown with hugo extensions. Please read more\nabout [content management](https://gohugo.io/categories/content-management) in\nthe hugo documentation.\n-You can use the hugo web server for testing. This will start a webserver that\n-will rebuild the site when you make content changes:\n+### Requirements\n-```\n-make server\n-```\n+Building the website requires [Docker](https://www.docker.com/). Please\n+[install](https://docs.docker.com/install/) it before building.\n-Access the site at http://localhost:8080\n-\n-## Building\n+### Building\n-If you are making changes to App Engine config or application code, you can\n-build the website using `make`. This will output the App Engine application\n-code, configuration, and html and CSS into the `public/` directory.\n+If you want to simply build the website, you can do that using `make`. This\n+will output the App Engine application code, configuration, and html and CSS\n+into the `public/` directory.\n```\nmake\n```\n-If you have Go installed you can run a local version of the website via the\n-`public/` directory.\n+### Testing\n+\n+You can use the hugo web server for testing documentation or style changes.\n+This will start a webserver that will rebuild the site when you make content\n+changes:\n```\n-cd public/\n-go run main.go\n+make devserver\n```\nAccess the site at http://localhost:8080\n-## Troubleshooting\n-\n-#### I get errors when building the website.\n-\n-If you get the following errors you should check that you have the \"extended\"\n-version of Hugo. This is the version of hugo named \"hugo\\_extended\" on the\n-[releases page](https://github.com/gohugoio/hugo/releases).\n+If you need to test all functionality including redirects you can start the App\n+Engine app locally. However, you will need to restart the app when making\n+content changes:\n```\n-ERROR 2019/04/03 11:25:58 Failed to add template \"partials/navbar.html\" in path \"/home/me/gvisor-website/layouts/partials/navbar.html\": template: partials/navbar.html:5: function \"resources\" not defined\n-ERROR 2019/04/03 11:25:58 partials/navbar.html : template: partials/navbar.html:5: function \"resources\" not defined\n-ERROR 2019/04/03 11:25:58 Unable to locate template for shortcode \"readfile\" in page \"docs/user_guide/docker.md\"\n-ERROR 2019/04/03 11:25:58 Unable to locate template for shortcode \"readfile\" in page \"docs/user_guide/oci.md\"\n-ERROR 2019/04/03 11:25:58 Unable to locate template for shortcode \"blocks\" in page \"_index.html\"\n+make server\n```\n" } ]
Go
Apache License 2.0
google/gvisor
Update readme with new docs. - Rearrange the docs into sections on using Github or Git locally. - Remove the troubleshooting FAQ since we build using Docker.
259,884
14.01.2020 17:06:53
-32,400
80111fc68ba57e5b7c7e694f12813283db2a8c80
Remove troubleshooting section Remove troubleshooting section that was added back in merge.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -77,11 +77,3 @@ Custom CSS styles should go into the\nIf you need to override or create variables used in scss styles, update the\n[_variables_project.scss](assets/scss/_variables_project.scss) file.\n-\n-## Troubleshooting\n-\n-#### I get errors when building the website.\n-\n-If you get the following errors you should check that you have the \"extended\"\n-version of Hugo. This is the version of hugo named \"hugo\\_extended\" on the\n-[releases page](https://github.com/gohugoio/hugo/releases).\n\\ No newline at end of file\n" } ]
Go
Apache License 2.0
google/gvisor
Remove troubleshooting section Remove troubleshooting section that was added back in merge.
259,884
21.12.2019 02:59:04
18,000
eae7c2f6bd27f7553d77e60842a4bddc09cac5c5
Add a tutorial on CNI
[ { "change_type": "ADD", "old_path": null, "new_path": "content/docs/tutorials/cni.md", "diff": "++++\n+title = \"Using CNI\"\n+weight = 1\n++++\n+\n+This tutorial will show you how to set up networking for a gVisor sandbox using\n+the [Container Networking Interface (CNI)](https://github.com/containernetworking/cni).\n+\n+## Install CNI Plugins\n+\n+First you will need to install the CNI plugins. CNI plugins are used to set up\n+a network namespace that `runsc` can use with the sandbox.\n+\n+Start by creating the directories for CNI plugin binaries:\n+\n+```\n+sudo mkdir -p /opt/cni/bin\n+```\n+\n+Download the CNI plugins:\n+\n+```\n+wget https://github.com/containernetworking/plugins/releases/download/v0.8.3/cni-plugins-linux-amd64-v0.8.3.tgz\n+```\n+\n+Next, unpack the plugins into the CNI binary directory:\n+\n+```\n+sudo tar -xvf cni-plugins-linux-amd64-v0.8.3.tgz -C /opt/cni/bin/\n+```\n+\n+## Configure CNI Plugins\n+\n+This section will show you how to configure CNI plugins. This tutorial will use\n+the \"bridge\" and \"loopback\" plugins which will create the necessary bridge and\n+loopback devices in our network namespace. However, you should be able to use\n+any CNI compatible plugin to set up networking for gVisor sandboxes.\n+\n+The bridge plugin configuration specifies the IP address subnet range for IP\n+addresses that will be assigned to sandboxes as well as the network routing\n+configuration. This tutorial will assign IP addresses from the `10.22.0.0/16`\n+range and allow all outbound traffic, however you can modify this configuration\n+to suit your use case.\n+\n+Create the bridge and loopback plugin configurations:\n+\n+```\n+sudo mkdir -p /etc/cni/net.d\n+\n+sudo sh -c 'cat > /etc/cni/net.d/10-bridge.conf << EOF\n+{\n+ \"cniVersion\": \"0.4.0\",\n+ \"name\": \"mynet\",\n+ \"type\": \"bridge\",\n+ \"bridge\": \"cni0\",\n+ \"isGateway\": true,\n+ \"ipMasq\": true,\n+ \"ipam\": {\n+ \"type\": \"host-local\",\n+ \"subnet\": \"10.22.0.0/16\",\n+ \"routes\": [\n+ { \"dst\": \"0.0.0.0/0\" }\n+ ]\n+ }\n+}\n+EOF'\n+\n+sudo sh -c 'cat > /etc/cni/net.d/99-loopback.conf << EOF\n+{\n+ \"cniVersion\": \"0.4.0\",\n+ \"name\": \"lo\",\n+ \"type\": \"loopback\"\n+}\n+EOF'\n+```\n+\n+## Create a Network Namespace\n+\n+For each gVisor sandbox you will create a network namespace and configure it\n+using CNI. First, create a random network namespace name and then create\n+the namespace.\n+\n+The network namespace path will then be `/var/run/netns/${CNI_CONTAINERID}`.\n+\n+```\n+export CNI_PATH=/opt/cni/bin\n+export CNI_CONTAINERID=$(printf '%x%x%x%x' $RANDOM $RANDOM $RANDOM $RANDOM)\n+export CNI_COMMAND=ADD\n+export CNI_NETNS=/var/run/netns/${CNI_CONTAINERID}\n+\n+sudo ip netns add ${CNI_CONTAINERID}\n+```\n+\n+Next, run the bridge and loopback plugins to apply the configuration that was\n+created earlier to the namespace. Each plugin outputs some JSON indicating the\n+results of executing hte plugin. For example, The bridge plugin's response\n+includes the IP address assigned to the ethernet device created in the network\n+namespace. Take note of the IP address for use later.\n+\n+```\n+export CNI_IFNAME=\"eth0\"\n+sudo -E /opt/cni/bin/bridge < /etc/cni/net.d/10-bridge.conf\n+export CNI_IFNAME=\"lo\"\n+sudo -E /opt/cni/bin/loopback < /etc/cni/net.d/99-loopback.conf\n+```\n+\n+Get the IP address assigned to our sandbox:\n+\n+```\n+POD_IP=$(sudo ip netns exec ${CNI_CONTAINERID} ip -4 addr show eth0 | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}')\n+```\n+\n+## Create the OCI Bundle\n+\n+Now that our network namespace is created and configured, we can create the OCI\n+bundle for our container. As part of the bundle's `config.json` we will specify\n+that the container use the network namespace that we created.\n+\n+The container will run a simple python webserver that we will be able to\n+connect to via the IP address assigned to it via the bridge CNI plugin.\n+\n+Create the bundle and root filesystem directories:\n+\n+```\n+sudo mkdir -p bundle\n+cd bundle\n+sudo mkdir rootfs\n+sudo docker export $(docker create python) | sudo tar --same-owner -pxf - -C rootfs\n+sudo mkdir -p rootfs/var/www/html\n+sudo sh -c 'echo \"Hello World!\" > rootfs/var/www/html/index.html'\n+```\n+\n+Next create the `config.json` specifying the network namespace.\n+```\n+sudo /usr/local/bin/runsc spec\n+sudo sed -i 's;\"sh\";\"python\", \"-m\", \"http.server\";' config.json\n+sudo sed -i \"s;\\\"cwd\\\": \\\"/\\\";\\\"cwd\\\": \\\"/var/www/html\\\";\" config.json\n+sudo sed -i \"s;\\\"type\\\": \\\"network\\\";\\\"type\\\": \\\"network\\\",\\n\\t\\t\\t\\t\\\"path\\\": \\\"/var/run/netns/${CNI_CONTAINERID}\\\";\" config.json\n+```\n+\n+## Run the Container\n+\n+Now we can run and connect to the webserver. Run the container in gVisor. Use\n+the same ID used for the network namespace to be consistent:\n+\n+```\n+sudo runsc run -detach ${CNI_CONTAINERID}\n+```\n+\n+Connect to the server via the sandbox's IP address:\n+\n+```\n+curl http://${POD_IP}:8000/\n+```\n+\n+You should see the server returning `Hello World!`.\n+\n+## Cleanup\n+\n+After you are finished running the container, you can clean up the network\n+namespace .\n+\n+```\n+sudo runsc kill ${CNI_CONTAINERID}\n+sudo runsc delete ${CNI_CONTAINERID}\n+\n+export CNI_COMMAND=DEL\n+\n+export CNI_IFNAME=\"lo\"\n+sudo -E /opt/cni/bin/loopback < /etc/cni/net.d/99-loopback.conf\n+export CNI_IFNAME=\"eth0\"\n+sudo -E /opt/cni/bin/bridge < /etc/cni/net.d/10-bridge.conf\n+\n+sudo ip netns delete ${CNI_CONTAINERID}\n+```\n" }, { "change_type": "MODIFY", "old_path": "content/docs/tutorials/kubernetes.md", "new_path": "content/docs/tutorials/kubernetes.md", "diff": "+++\ntitle = \"WordPress with Kubernetes\"\n+weight = 11\n+++\n## Deploy a WordPress site using GKE Sandbox\n" }, { "change_type": "MODIFY", "old_path": "content/docs/user_guide/quick_start/oci.md", "new_path": "content/docs/user_guide/quick_start/oci.md", "diff": "@@ -43,7 +43,7 @@ Finally run the container.\nsudo runsc run hello\n```\n-Next try [running gVisor using Docker](../docker/).\n+Next try [using CNI to set up networking](../../../tutorials/cni/) or [running gVisor using Docker](../docker/).\n[oci]: https://opencontainers.org/\n" } ]
Go
Apache License 2.0
google/gvisor
Add a tutorial on CNI
259,891
14.01.2020 17:54:02
28,800
95e9de31d20ee1c7262fe5870e10485a369e6497
Address Nic's comments.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -153,6 +153,8 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\nreturn false\ncase Stolen, Queue, Repeat, None, Jump, Return, Continue:\npanic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\n+ default:\n+ panic(fmt.Sprintf(\"Unknown verdict %v.\", verdict))\n}\n}\n@@ -174,6 +176,8 @@ func (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename stri\ncontinue\ncase Stolen, Queue, Repeat, None, Jump, Return:\npanic(fmt.Sprintf(\"Unimplemented verdict %v.\", verdict))\n+ default:\n+ panic(fmt.Sprintf(\"Unknown verdict %v.\", verdict))\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Address Nic's comments.
259,962
15.01.2020 11:17:25
28,800
f874723e64bd8a2e747bb336e0b6b8f0da1f044a
Bump SO_SNDBUF for fdbased endpoint used by runsc. Updates
[ { "change_type": "MODIFY", "old_path": "benchmarks/tcp/tcp_proxy.go", "new_path": "benchmarks/tcp/tcp_proxy.go", "diff": "@@ -85,7 +85,7 @@ func (netImpl) printStats() {\nconst (\nnicID = 1 // Fixed.\n- rcvBufSize = 4 << 20 // 1MB.\n+ bufSize = 4 << 20 // 4MB.\n)\ntype netstackImpl struct {\n@@ -125,13 +125,13 @@ func setupNetwork(ifaceName string, numChannels int) (fds []int, err error) {\n}\n// RAW Sockets by default have a very small SO_RCVBUF of 256KB,\n- // up it to at least 1MB to reduce packet drops.\n- if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, rcvBufSize); err != nil {\n- return nil, fmt.Errorf(\"setsockopt(..., SO_RCVBUF, %v,..) = %v\", rcvBufSize, err)\n+ // up it to at least 4MB to reduce packet drops.\n+ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, bufSize); err != nil {\n+ return nil, fmt.Errorf(\"setsockopt(..., SO_RCVBUF, %v,..) = %v\", bufSize, err)\n}\n- if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, rcvBufSize); err != nil {\n- return nil, fmt.Errorf(\"setsockopt(..., SO_RCVBUF, %v,..) = %v\", rcvBufSize, err)\n+ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, bufSize); err != nil {\n+ return nil, fmt.Errorf(\"setsockopt(..., SO_SNDBUF, %v,..) = %v\", bufSize, err)\n}\nif !*swgso && *gso != 0 {\n" }, { "change_type": "MODIFY", "old_path": "runsc/sandbox/network.go", "new_path": "runsc/sandbox/network.go", "diff": "@@ -321,16 +321,21 @@ func createSocket(iface net.Interface, ifaceLink netlink.Link, enableGSO bool) (\n}\n}\n- // Use SO_RCVBUFFORCE because on linux the receive buffer for an\n- // AF_PACKET socket is capped by \"net.core.rmem_max\". rmem_max\n- // defaults to a unusually low value of 208KB. This is too low\n- // for gVisor to be able to receive packets at high throughputs\n- // without incurring packet drops.\n- const rcvBufSize = 4 << 20 // 4MB.\n+ // Use SO_RCVBUFFORCE/SO_SNDBUFFORCE because on linux the receive/send buffer\n+ // for an AF_PACKET socket is capped by \"net.core.rmem_max/wmem_max\".\n+ // wmem_max/rmem_max default to a unusually low value of 208KB. This is too low\n+ // for gVisor to be able to receive packets at high throughputs without\n+ // incurring packet drops.\n+ const bufSize = 4 << 20 // 4MB.\n- if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUFFORCE, rcvBufSize); err != nil {\n- return nil, fmt.Errorf(\"failed to increase socket rcv buffer to %d: %v\", rcvBufSize, err)\n+ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_RCVBUFFORCE, bufSize); err != nil {\n+ return nil, fmt.Errorf(\"failed to increase socket rcv buffer to %d: %v\", bufSize, err)\n}\n+\n+ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_SNDBUFFORCE, bufSize); err != nil {\n+ return nil, fmt.Errorf(\"failed to increase socket snd buffer to %d: %v\", bufSize, err)\n+ }\n+\nreturn &socketEntry{deviceFile, gsoMaxSize}, nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Bump SO_SNDBUF for fdbased endpoint used by runsc. Updates #231 PiperOrigin-RevId: 289897881
259,974
16.01.2020 10:26:23
28,800
420d335fc9495ec18a20f710869770d0708d9a49
Enable clone syscall support on arm64. sys_clone has many flavors in Linux, and amd64 chose a different one from x86(different arguments order). Ref kernel/fork.c for more info. COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1545 from xiaobo55x:clone
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/BUILD", "new_path": "pkg/sentry/syscalls/linux/BUILD", "diff": "@@ -13,6 +13,8 @@ go_library(\n\"sigset.go\",\n\"sys_aio.go\",\n\"sys_capability.go\",\n+ \"sys_clone_amd64.go\",\n+ \"sys_clone_arm64.go\",\n\"sys_epoll.go\",\n\"sys_eventfd.go\",\n\"sys_file.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_clone_amd64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build amd64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+)\n+\n+// Clone implements linux syscall clone(2).\n+// sys_clone has so many flavors. We implement the default one in linux 3.11\n+// x86_64:\n+// sys_clone(clone_flags, newsp, parent_tidptr, child_tidptr, tls_val)\n+func Clone(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ flags := int(args[0].Int())\n+ stack := args[1].Pointer()\n+ parentTID := args[2].Pointer()\n+ childTID := args[3].Pointer()\n+ tls := args[4].Pointer()\n+ return clone(t, flags, stack, parentTID, childTID, tls)\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_clone_arm64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+// +build arm64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/sentry/arch\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+)\n+\n+// Clone implements linux syscall clone(2).\n+// sys_clone has so many flavors, and we implement the default one in linux 3.11\n+// arm64(kernel/fork.c with CONFIG_CLONE_BACKWARDS defined in the config file):\n+// sys_clone(clone_flags, newsp, parent_tidptr, tls_val, child_tidptr)\n+func Clone(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ flags := int(args[0].Int())\n+ stack := args[1].Pointer()\n+ parentTID := args[2].Pointer()\n+ tls := args[3].Pointer()\n+ childTID := args[4].Pointer()\n+ return clone(t, flags, stack, parentTID, childTID, tls)\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_thread.go", "new_path": "pkg/sentry/syscalls/linux/sys_thread.go", "diff": "@@ -220,19 +220,6 @@ func clone(t *kernel.Task, flags int, stack usermem.Addr, parentTID usermem.Addr\nreturn uintptr(ntid), ctrl, err\n}\n-// Clone implements linux syscall clone(2).\n-// sys_clone has so many flavors. We implement the default one in linux 3.11\n-// x86_64:\n-// sys_clone(clone_flags, newsp, parent_tidptr, child_tidptr, tls_val)\n-func Clone(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n- flags := int(args[0].Int())\n- stack := args[1].Pointer()\n- parentTID := args[2].Pointer()\n- childTID := args[3].Pointer()\n- tls := args[4].Pointer()\n- return clone(t, flags, stack, parentTID, childTID, tls)\n-}\n-\n// Fork implements Linux syscall fork(2).\nfunc Fork(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n// \"A call to fork() is equivalent to a call to clone(2) specifying flags\n" } ]
Go
Apache License 2.0
google/gvisor
Enable clone syscall support on arm64. sys_clone has many flavors in Linux, and amd64 chose a different one from x86(different arguments order). Ref kernel/fork.c for more info. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I6c8cbc685f4a6e786b171715ab68292fc95cbf48 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1545 from xiaobo55x:clone 156bd2dfbc63ef5291627b0578ddea77997393b2 PiperOrigin-RevId: 290093953
259,975
16.01.2020 13:00:58
28,800
94be30a18dc7c75dc70716ce1ede74a7fb1352fb
Add run-gcp command. Add command to run benchmarks on GCP backed machines using the gcloud producer. Run with: `bazel run :benchmarks -- run-gcp [BENCHMARK_NAME]` Tested with the startup benchmark.
[ { "change_type": "MODIFY", "old_path": "benchmarks/harness/__init__.py", "new_path": "benchmarks/harness/__init__.py", "diff": "# limitations under the License.\n\"\"\"Core benchmark utilities.\"\"\"\n+import getpass\nimport os\n# LOCAL_WORKLOADS_PATH defines the path to use for local workloads. This is a\n@@ -23,3 +24,9 @@ LOCAL_WORKLOADS_PATH = os.path.join(\n# REMOTE_WORKLOADS_PATH defines the path to use for storing the workloads on the\n# remote host. This is a format string that accepts a single string parameter.\nREMOTE_WORKLOADS_PATH = \"workloads/{}\"\n+\n+# DEFAULT_USER is the default user running this script.\n+DEFAULT_USER = getpass.getuser()\n+\n+# DEFAULT_USER_HOME is the home directory of the user running the script.\n+DEFAULT_USER_HOME = os.environ[\"HOME\"] if \"HOME\" in os.environ else \"\"\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/harness/machine.py", "new_path": "benchmarks/harness/machine.py", "diff": "@@ -214,6 +214,9 @@ class RemoteMachine(Machine):\n# Push to the remote machine and build.\nlogging.info(\"Building %s@%s remotely...\", workload, self._name)\nremote_path = self._ssh_connection.send_workload(workload)\n+ # Workloads are all tarballs.\n+ self.run(\"tar -xvf {remote_path}/tar.tar -C {remote_path}\".format(\n+ remote_path=remote_path))\nself.run(\"docker build --tag={} {}\".format(workload, remote_path))\nreturn workload # Workload is the tag.\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/harness/machine_producers/gcloud_producer.py", "new_path": "benchmarks/harness/machine_producers/gcloud_producer.py", "diff": "@@ -29,7 +29,6 @@ collisions with user instances shouldn't happen.\nproducer.release_machines(NUM_MACHINES)\n\"\"\"\nimport datetime\n-import getpass\nimport json\nimport subprocess\nimport threading\n@@ -40,8 +39,6 @@ from benchmarks.harness import machine\nfrom benchmarks.harness.machine_producers import gcloud_mock_recorder\nfrom benchmarks.harness.machine_producers import machine_producer\n-DEFAULT_USER = getpass.getuser()\n-\nclass GCloudProducer(machine_producer.MachineProducer):\n\"\"\"Implementation of MachineProducer backed by GCP.\n@@ -50,9 +47,10 @@ class GCloudProducer(machine_producer.MachineProducer):\nAttributes:\nproject: The GCP project name under which to create the machines.\n- ssh_key_path: path to a valid ssh key. See README on vaild ssh keys.\n+ ssh_key_file: path to a valid ssh private key. See README on vaild ssh keys.\nimage: image name as a string.\nimage_project: image project as a string.\n+ machine_type: type of GCP to create. e.g. n1-standard-4\nzone: string to a valid GCP zone.\nssh_user: string of user name for ssh_key\nssh_password: string of password for ssh key\n@@ -63,18 +61,22 @@ class GCloudProducer(machine_producer.MachineProducer):\ndef __init__(self,\nproject: str,\n- ssh_key_path: str,\n+ ssh_key_file: str,\nimage: str,\nimage_project: str,\n+ machine_type: str,\nzone: str,\nssh_user: str,\n+ ssh_password: str,\nmock: gcloud_mock_recorder.MockPrinter = None):\nself.project = project\n- self.ssh_key_path = ssh_key_path\n+ self.ssh_key_file = ssh_key_file\nself.image = image\nself.image_project = image_project\n+ self.machine_type = machine_type\nself.zone = zone\n- self.ssh_user = ssh_user if ssh_user else DEFAULT_USER\n+ self.ssh_user = ssh_user\n+ self.ssh_password = ssh_password\nself.mock = mock\nself.condition = threading.Condition()\n@@ -94,12 +96,11 @@ class GCloudProducer(machine_producer.MachineProducer):\n\"\"\"Releases the requested number of machines, deleting the instances.\"\"\"\nif not machine_list:\nreturn\n- with self.condition:\ncmd = \"gcloud compute instances delete --quiet\".split(\" \")\nnames = [str(m) for m in machine_list]\ncmd.extend(names)\ncmd.append(\"--zone={zone}\".format(zone=self.zone))\n- self._run_command(cmd)\n+ self._run_command(cmd, detach=True)\ndef _machines_from_instances(\nself, instances: List[Dict[str, Any]]) -> List[machine.Machine]:\n@@ -111,9 +112,11 @@ class GCloudProducer(machine_producer.MachineProducer):\n\"hostname\":\ninstance[\"networkInterfaces\"][0][\"accessConfigs\"][0][\"natIP\"],\n\"key_path\":\n- self.ssh_key_path,\n+ self.ssh_key_file,\n\"username\":\n- self.ssh_user\n+ self.ssh_user,\n+ \"key_password\":\n+ self.ssh_password\n}\nmachines.append(machine.RemoteMachine(name=name, **kwargs))\nreturn machines\n@@ -148,8 +151,11 @@ class GCloudProducer(machine_producer.MachineProducer):\n\"_build_instances cannot create instances without names.\")\ncmd = \"gcloud compute instances create\".split(\" \")\ncmd.extend(names)\n- cmd.extend(\"--preemptible --image={image} --zone={zone}\".format(\n- image=self.image, zone=self.zone).split(\" \"))\n+ cmd.extend(\n+ \"--preemptible --image={image} --zone={zone} --machine-type={machine_type}\"\n+ .format(\n+ image=self.image, zone=self.zone,\n+ machine_type=self.machine_type).split(\" \"))\nif self.image_project:\ncmd.append(\"--image-project={project}\".format(project=self.image_project))\nres = self._run_command(cmd)\n@@ -184,7 +190,7 @@ class GCloudProducer(machine_producer.MachineProducer):\nArgs:\nnames: list of machine names to which to add the ssh-key\n- self.ssh_key_path.\n+ self.ssh_key_file.\nRaises:\nsubprocess.CalledProcessError: when underlying subprocess call returns an\n@@ -193,7 +199,7 @@ class GCloudProducer(machine_producer.MachineProducer):\n\"\"\"\nfor name in names:\ncmd = \"gcloud compute ssh {name}\".format(name=name).split(\" \")\n- cmd.append(\"--ssh-key-file={key}\".format(key=self.ssh_key_path))\n+ cmd.append(\"--ssh-key-file={key}\".format(key=self.ssh_key_file))\ncmd.append(\"--zone={zone}\".format(zone=self.zone))\ncmd.append(\"--command=uname\")\ntimeout = datetime.timedelta(seconds=5 * 60)\n@@ -221,7 +227,9 @@ class GCloudProducer(machine_producer.MachineProducer):\nres = self._run_command(cmd)\nreturn json.loads(res.stdout)\n- def _run_command(self, cmd: List[str]) -> subprocess.CompletedProcess:\n+ def _run_command(self,\n+ cmd: List[str],\n+ detach: bool = False) -> [None, subprocess.CompletedProcess]:\n\"\"\"Runs command as a subprocess.\nRuns command as subprocess and returns the result.\n@@ -230,14 +238,24 @@ class GCloudProducer(machine_producer.MachineProducer):\nArgs:\ncmd: command to be run as a list of strings.\n+ detach: if True, run the child process and don't wait for it to return.\nReturns:\n- Completed process object to be parsed by caller.\n+ Completed process object to be parsed by caller or None if detach=True.\nRaises:\nCalledProcessError: if subprocess.run returns an error.\n\"\"\"\ncmd = cmd + [\"--format=json\"]\n+ if detach:\n+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n+ if self.mock:\n+ out, _ = p.communicate()\n+ self.mock.record(\n+ subprocess.CompletedProcess(\n+ returncode=p.returncode, stdout=out, args=p.args))\n+ return\n+\nres = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nif self.mock:\nself.mock.record(res)\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/harness/ssh_connection.py", "new_path": "benchmarks/harness/ssh_connection.py", "diff": "@@ -94,7 +94,7 @@ class SSHConnection:\nreturn stdout, stderr\ndef send_workload(self, name: str) -> str:\n- \"\"\"Sends a workload to the remote machine.\n+ \"\"\"Sends a workload tarball to the remote machine.\nArgs:\nname: The workload name.\n@@ -103,9 +103,6 @@ class SSHConnection:\nThe remote path.\n\"\"\"\nwith self._client() as client:\n- for dirpath, _, filenames in os.walk(\n- harness.LOCAL_WORKLOADS_PATH.format(name)):\n- for filename in filenames:\n- send_one_file(client, os.path.join(dirpath, filename),\n+ send_one_file(client, harness.LOCAL_WORKLOADS_PATH.format(name),\nharness.REMOTE_WORKLOADS_PATH.format(name))\nreturn harness.REMOTE_WORKLOADS_PATH.format(name)\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/runner/__init__.py", "new_path": "benchmarks/runner/__init__.py", "diff": "import copy\nimport csv\n+import json\nimport logging\n+import os\nimport pkgutil\nimport pydoc\nimport re\n+import subprocess\nimport sys\nimport types\nfrom typing import List\n@@ -26,8 +29,10 @@ from typing import Tuple\nimport click\n+from benchmarks import harness\nfrom benchmarks import suites\nfrom benchmarks.harness import benchmark_driver\n+from benchmarks.harness.machine_producers import gcloud_producer\nfrom benchmarks.harness.machine_producers import machine_producer\nfrom benchmarks.harness.machine_producers import mock_producer\nfrom benchmarks.harness.machine_producers import yaml_producer\n@@ -116,6 +121,61 @@ def run_mock(ctx, **kwargs):\nrun(ctx, mock_producer.MockMachineProducer(), **kwargs)\[email protected](\"run-gcp\", commands.GCPCommand)\[email protected]_context\n+def run_gcp(ctx, project: str, ssh_key_file: str, image: str,\n+ image_project: str, machine_type: str, zone: str, ssh_user: str,\n+ ssh_password: str, **kwargs):\n+ \"\"\"Runs all benchmarks on GCP instances.\"\"\"\n+\n+ if not ssh_user:\n+ ssh_user = harness.DEFAULT_USER\n+\n+ # Get the default project if one was not provided.\n+ if not project:\n+ sub = subprocess.run(\n+ \"gcloud config get-value project\".split(\" \"), stdout=subprocess.PIPE)\n+ if sub.returncode:\n+ raise ValueError(\n+ \"Cannot get default project from gcloud. Is it configured>\")\n+ project = sub.stdout.decode(\"utf-8\").strip(\"\\n\")\n+\n+ if not image_project:\n+ image_project = project\n+\n+ # Check that the ssh-key exists and is readable.\n+ if not os.access(ssh_key_file, os.R_OK):\n+ raise ValueError(\n+ \"ssh key given `{ssh_key}` is does not exist or is not readable.\"\n+ .format(ssh_key=ssh_key_file))\n+\n+ # Check that the image exists.\n+ sub = subprocess.run(\n+ \"gcloud compute images describe {image} --project {image_project} --format=json\"\n+ .format(image=image, image_project=image_project).split(\" \"),\n+ stdout=subprocess.PIPE)\n+ if sub.returncode or \"READY\" not in json.loads(sub.stdout)[\"status\"]:\n+ raise ValueError(\n+ \"given image was not found or is not ready: {image} {image_project}.\"\n+ .format(image=image, image_project=image_project))\n+\n+ # Check and set zone to default.\n+ if not zone:\n+ sub = subprocess.run(\n+ \"gcloud config get-value compute/zone\".split(\" \"),\n+ stdout=subprocess.PIPE)\n+ if sub.returncode:\n+ raise ValueError(\n+ \"Default zone is not set in gcloud. Set one or pass a zone with the --zone flag.\"\n+ )\n+ zone = sub.stdout.decode(\"utf-8\").strip(\"\\n\")\n+\n+ producer = gcloud_producer.GCloudProducer(project, ssh_key_file, image,\n+ image_project, machine_type, zone,\n+ ssh_user, ssh_password)\n+ run(ctx, producer, **kwargs)\n+\n+\ndef run(ctx, producer: machine_producer.MachineProducer, method: str, runs: int,\nruntime: List[str], metric: List[str], stat: str, **kwargs):\n\"\"\"Runs arbitrary benchmarks.\n" }, { "change_type": "MODIFY", "old_path": "benchmarks/runner/commands.py", "new_path": "benchmarks/runner/commands.py", "diff": "@@ -24,6 +24,8 @@ def run_mock(**kwargs):\n\"\"\"\nimport click\n+from benchmarks import harness\n+\nclass RunCommand(click.core.Command):\n\"\"\"Base Run Command with flags.\n@@ -82,3 +84,52 @@ class LocalCommand(RunCommand):\n(\"--limit\",),\ndefault=1,\nhelp=\"Limit of number of benchmarks that can run at a given time.\"))\n+\n+\n+class GCPCommand(RunCommand):\n+ \"\"\"GCPCommand inherits all flags from RunCommand and adds flags for run_gcp method.\n+\n+ Attributes:\n+ project: GCP project\n+ ssh_key_path: path to the ssh-key to use for the run\n+ image: name of the image to build machines from\n+ image_project: GCP project under which to find image\n+ zone: a GCP zone (e.g. us-west1-b)\n+ ssh_user: username to use for the ssh-key\n+ ssh_password: password to use for the ssh-key\n+ \"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ super().__init__(*args, **kwargs)\n+\n+ project = click.core.Option(\n+ (\"--project\",),\n+ help=\"Project to run on if not default value given by 'gcloud config get-value project'.\"\n+ )\n+ ssh_key_path = click.core.Option(\n+ (\"--ssh-key-file\",),\n+ help=\"Path to a valid ssh private key to use. See README on generating a valid ssh key. Set to ~/.ssh/benchmark-tools by default.\",\n+ default=harness.DEFAULT_USER_HOME + \"/.ssh/benchmark-tools\")\n+ image = click.core.Option((\"--image\",),\n+ help=\"The image on which to build VMs.\",\n+ default=\"bm-tools-testing\")\n+ image_project = click.core.Option(\n+ (\"--image_project\",),\n+ help=\"The project under which the image to be used is listed.\",\n+ default=\"\")\n+ machine_type = click.core.Option((\"--machine_type\",),\n+ help=\"Type to make all machines.\",\n+ default=\"n1-standard-4\")\n+ zone = click.core.Option((\"--zone\",),\n+ help=\"The GCP zone to run on.\",\n+ default=\"\")\n+ ssh_user = click.core.Option((\"--ssh-user\",),\n+ help=\"User for the ssh key.\",\n+ default=harness.DEFAULT_USER)\n+ ssh_password = click.core.Option((\"--ssh-password\",),\n+ help=\"Password for the ssh key.\",\n+ default=\"\")\n+ self.params.extend([\n+ project, ssh_key_path, image, image_project, machine_type, zone,\n+ ssh_user, ssh_password\n+ ])\n" } ]
Go
Apache License 2.0
google/gvisor
Add run-gcp command. Add command to run benchmarks on GCP backed machines using the gcloud producer. Run with: `bazel run :benchmarks -- run-gcp [BENCHMARK_NAME]` Tested with the startup benchmark. PiperOrigin-RevId: 290126444
259,860
16.01.2020 14:25:56
28,800
1e7f0c822b3a7c643d532d40a14ab79eb1df85c6
Bump p9 version, adding corresponding checks to client_file.go.
[ { "change_type": "MODIFY", "old_path": "pkg/p9/client_file.go", "new_path": "pkg/p9/client_file.go", "diff": "@@ -170,6 +170,9 @@ func (c *clientFile) GetXattr(name string, size uint64) (string, error) {\nif atomic.LoadUint32(&c.closed) != 0 {\nreturn \"\", syscall.EBADF\n}\n+ if !versionSupportsGetSetXattr(c.client.version) {\n+ return \"\", syscall.EOPNOTSUPP\n+ }\nrgetxattr := Rgetxattr{}\nif err := c.client.sendRecv(&Tgetxattr{FID: c.fid, Name: name, Size: size}, &rgetxattr); err != nil {\n@@ -184,6 +187,9 @@ func (c *clientFile) SetXattr(name, value string, flags uint32) error {\nif atomic.LoadUint32(&c.closed) != 0 {\nreturn syscall.EBADF\n}\n+ if !versionSupportsGetSetXattr(c.client.version) {\n+ return syscall.EOPNOTSUPP\n+ }\nreturn c.client.sendRecv(&Tsetxattr{FID: c.fid, Name: name, Value: value, Flags: flags}, &Rsetxattr{})\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/p9/version.go", "new_path": "pkg/p9/version.go", "diff": "@@ -26,7 +26,7 @@ const (\n//\n// Clients are expected to start requesting this version number and\n// to continuously decrement it until a Tversion request succeeds.\n- highestSupportedVersion uint32 = 9\n+ highestSupportedVersion uint32 = 10\n// lowestSupportedVersion is the lowest supported version X in a\n// version string of the format 9P2000.L.Google.X.\n@@ -161,3 +161,9 @@ func versionSupportsFlipcall(v uint32) bool {\nfunc VersionSupportsOpenTruncateFlag(v uint32) bool {\nreturn v >= 9\n}\n+\n+// versionSupportsGetSetXattr returns true if version v supports\n+// the Tgetxattr and Tsetxattr messages.\n+func versionSupportsGetSetXattr(v uint32) bool {\n+ return v >= 10\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Bump p9 version, adding corresponding checks to client_file.go. PiperOrigin-RevId: 290145451
259,860
16.01.2020 18:13:27
28,800
7a45ae7e67438697296fc12345202e3c76304096
Implement setxattr for overlays.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode.go", "new_path": "pkg/sentry/fs/inode.go", "diff": "@@ -270,9 +270,9 @@ func (i *Inode) GetXattr(ctx context.Context, name string, size uint64) (string,\n}\n// SetXattr calls i.InodeOperations.SetXattr with i as the Inode.\n-func (i *Inode) SetXattr(ctx context.Context, name, value string, flags uint32) error {\n+func (i *Inode) SetXattr(ctx context.Context, d *Dirent, name, value string, flags uint32) error {\nif i.overlay != nil {\n- return overlaySetxattr(ctx, i.overlay, name, value, flags)\n+ return overlaySetxattr(ctx, i.overlay, d, name, value, flags)\n}\nreturn i.InodeOperations.SetXattr(ctx, i, name, value, flags)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/inode_overlay.go", "new_path": "pkg/sentry/fs/inode_overlay.go", "diff": "@@ -552,9 +552,16 @@ func overlayGetXattr(ctx context.Context, o *overlayEntry, name string, size uin\nreturn s, err\n}\n-// TODO(b/146028302): Support setxattr for overlayfs.\n-func overlaySetxattr(ctx context.Context, o *overlayEntry, name, value string, flags uint32) error {\n- return syserror.EOPNOTSUPP\n+func overlaySetxattr(ctx context.Context, o *overlayEntry, d *Dirent, name, value string, flags uint32) error {\n+ // Don't allow changes to overlay xattrs through a setxattr syscall.\n+ if strings.HasPrefix(XattrOverlayPrefix, name) {\n+ return syserror.EPERM\n+ }\n+\n+ if err := copyUp(ctx, d); err != nil {\n+ return err\n+ }\n+ return o.upper.SetXattr(ctx, d, name, value, flags)\n}\nfunc overlayListXattr(ctx context.Context, o *overlayEntry) (map[string]struct{}, error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "new_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "diff": "@@ -142,7 +142,7 @@ func setXattr(t *kernel.Task, d *fs.Dirent, dirPath bool, nameAddr, valueAddr us\nreturn syserror.EOPNOTSUPP\n}\n- return d.Inode.SetXattr(t, name, value, flags)\n+ return d.Inode.SetXattr(t, d, name, value, flags)\n}\nfunc copyInXattrName(t *kernel.Task, nameAddr usermem.Addr) (string, error) {\n" } ]
Go
Apache License 2.0
google/gvisor
Implement setxattr for overlays. PiperOrigin-RevId: 290186303
259,884
17.01.2020 02:13:07
18,000
10ec43c775afaa49ca638cd2d411e975e06dbe78
Clean up markdown lists
[ { "change_type": "MODIFY", "old_path": "content/docs/user_guide/checkpoint_restore.md", "new_path": "content/docs/user_guide/checkpoint_restore.md", "diff": "@@ -83,17 +83,17 @@ docker start --checkpoint --checkpoint-dir=<directory> <container>\n### Issues Preventing Compatibility with Docker\n-* **[Moby #37360][leave-running]:** Docker version 18.03.0-ce and earlier hangs\n+- **[Moby #37360][leave-running]:** Docker version 18.03.0-ce and earlier hangs\nwhen checkpointing and does not create the checkpoint. To successfully use\nthis feature, install a custom version of docker-ce from the moby repository.\nThis issue is caused by an improper implementation of the `--leave-running`\nflag. This issue is fixed in newer releases.\n-* **Docker does not support restoration into new containers:** Docker currently\n+- **Docker does not support restoration into new containers:** Docker currently\nexpects the container which created the checkpoint to be the same container\nused to restore which is not possible in runsc. When Docker supports container\nmigration and therefore restoration into new containers, this will be the\nflow.\n-* **[Moby #37344][checkpoint-dir]:** Docker does not currently support the\n+- **[Moby #37344][checkpoint-dir]:** Docker does not currently support the\n`--checkpoint-dir` flag but this will be required when restoring from a\ncheckpoint made in another container.\n" }, { "change_type": "MODIFY", "old_path": "content/docs/user_guide/debugging.md", "new_path": "content/docs/user_guide/debugging.md", "diff": "@@ -120,7 +120,7 @@ sudo runsc --root /var/run/docker/runtime-runsc-prof/moby debug --profile-heap=/\nsudo runsc --root /var/run/docker/runtime-runsc-prof/moby debug --profile-cpu=/tmp/cpu.prof --profile-delay=30 63254c6ab3a6989623fa1fb53616951eed31ac605a2637bb9ddba5d8d404b35b\n```\n-The resulting files can be opened using `go tool pprof` or [pprof][pprof]. The examples\n+The resulting files can be opened using `go tool pprof` or [pprof][]. The examples\nbelow create image file (`.svg`) with the heap profile and writes the top\nfunctions using CPU to the console:\n" }, { "change_type": "MODIFY", "old_path": "content/docs/user_guide/install.md", "new_path": "content/docs/user_guide/install.md", "diff": "@@ -102,9 +102,9 @@ Based on the release type, you will need to substitute `${DIST}` below, using\none of:\n* `master`: For HEAD.\n-* `nightly: For nightly releases.\n-* `release: For the latest release.\n-* `${yyyymmdd}: For a specific releases (see above).\n+* `nightly`: For nightly releases.\n+* `release`: For the latest release.\n+* `${yyyymmdd}`: For a specific releases (see above).\nThe repository for the release you wish to install should be added:\n" } ]
Go
Apache License 2.0
google/gvisor
Clean up markdown lists
259,884
17.01.2020 02:27:50
18,000
fd0628b5f565f24cf4145065e404bf5f40aa265f
Dedup check command
[ { "change_type": "MODIFY", "old_path": "Makefile", "new_path": "Makefile", "diff": "@@ -106,9 +106,6 @@ compatibility-docs: bin/generate-syscall-docs upstream/gvisor/bazel-bin/runsc/li\n.PHONY: compatibility-docs\ncheck: check-markdown check-html\n- docker run \\\n- -v $(shell pwd)/public:/public gcr.io/gvisor-website/html-proofer:$(HTMLPROOFER_VERSION) \\\n- htmlproofer --disable-external --check-html public/static\n.PHONY: check\ncheck-markdown: node_modules $(CONTENT_SOURCE) compatibility-docs\n@@ -125,7 +122,9 @@ check-markdown: node_modules $(CONTENT_SOURCE) compatibility-docs\n.PHONY: check-markdown\ncheck-html: website\n- docker run -v $(shell pwd)/public:/public gcr.io/gvisor-website/html-proofer:3.10.2 htmlproofer --disable-external --check-html public/static\n+ docker run \\\n+ -v $(shell pwd)/public:/public gcr.io/gvisor-website/html-proofer:$(HTMLPROOFER_VERSION) \\\n+ htmlproofer --disable-external --check-html public/static\n.PHONY: check-html\n# Run a local content development server. Redirects will not be supported.\n" } ]
Go
Apache License 2.0
google/gvisor
Dedup check command
259,974
06.12.2019 06:29:24
0
82ae857877fdf3492f40bca87657a07892c3f59b
Enable build of test/syscall tests on arm64.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/BUILD", "new_path": "test/syscalls/linux/BUILD", "diff": "@@ -19,6 +19,16 @@ exports_files(\nvisibility = [\"//:sandbox\"],\n)\n+config_setting(\n+ name = \"x86_64\",\n+ constraint_values = [\"@bazel_tools//platforms:x86_64\"],\n+)\n+\n+config_setting(\n+ name = \"aarch64\",\n+ constraint_values = [\"@bazel_tools//platforms:aarch64\"],\n+)\n+\ncc_binary(\nname = \"sigaltstack_check\",\ntestonly = 1,\n@@ -197,7 +207,10 @@ cc_binary(\ncc_binary(\nname = \"32bit_test\",\ntestonly = 1,\n- srcs = [\"32bit.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"32bit.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:memory_util\",\n@@ -584,7 +597,10 @@ cc_binary(\ncc_binary(\nname = \"exceptions_test\",\ntestonly = 1,\n- srcs = [\"exceptions.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"exceptions.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:logging\",\n@@ -640,7 +656,10 @@ cc_binary(\ncc_binary(\nname = \"exec_binary_test\",\ntestonly = 1,\n- srcs = [\"exec_binary.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"exec_binary.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:cleanup\",\n@@ -811,7 +830,10 @@ cc_binary(\ncc_binary(\nname = \"fpsig_fork_test\",\ntestonly = 1,\n- srcs = [\"fpsig_fork.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"fpsig_fork.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:logging\",\n@@ -825,7 +847,10 @@ cc_binary(\ncc_binary(\nname = \"fpsig_nested_test\",\ntestonly = 1,\n- srcs = [\"fpsig_nested.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"fpsig_nested.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:test_main\",\n@@ -1440,7 +1465,10 @@ cc_binary(\ncc_binary(\nname = \"arch_prctl_test\",\ntestonly = 1,\n- srcs = [\"arch_prctl.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"arch_prctl.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:test_main\",\n@@ -2035,7 +2063,10 @@ cc_binary(\ncc_binary(\nname = \"sigiret_test\",\ntestonly = 1,\n- srcs = [\"sigiret.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"sigiret.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:logging\",\n@@ -2043,7 +2074,10 @@ cc_binary(\n\"//test/util:test_util\",\n\"//test/util:timer_util\",\n\"@com_google_googletest//:gtest\",\n- ],\n+ ] + select({\n+ \":x86_64\": [],\n+ \":aarch64\": [\"//test/util:test_main\"],\n+ }),\n)\ncc_binary(\n@@ -3260,7 +3294,10 @@ cc_binary(\ncc_binary(\nname = \"sysret_test\",\ntestonly = 1,\n- srcs = [\"sysret.cc\"],\n+ srcs = select({\n+ \":x86_64\": [\"sysret.cc\"],\n+ \":aarch64\": [],\n+ }),\nlinkstatic = 1,\ndeps = [\n\"//test/util:logging\",\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/bad.cc", "new_path": "test/syscalls/linux/bad.cc", "diff": "@@ -22,12 +22,13 @@ namespace gvisor {\nnamespace testing {\nnamespace {\n-\n+#if defined(__x86_64__)\nTEST(BadSyscallTest, NotImplemented) {\n// get_kernel_syms is not supported in Linux > 2.6, and not implemented in\n// gVisor.\nEXPECT_THAT(syscall(SYS_get_kernel_syms), SyscallFailsWithErrno(ENOSYS));\n}\n+#endif // defined(__x86_64__)\nTEST(BadSyscallTest, NegativeOne) {\nEXPECT_THAT(syscall(-1), SyscallFailsWithErrno(ENOSYS));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/chroot.cc", "new_path": "test/syscalls/linux/chroot.cc", "diff": "@@ -162,7 +162,7 @@ TEST(ChrootTest, DotDotFromOpenFD) {\n// getdents on fd should not error.\nchar buf[1024];\n- ASSERT_THAT(syscall(SYS_getdents, fd.get(), buf, sizeof(buf)),\n+ ASSERT_THAT(syscall(SYS_getdents64, fd.get(), buf, sizeof(buf)),\nSyscallSucceeds());\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fork.cc", "new_path": "test/syscalls/linux/fork.cc", "diff": "@@ -215,6 +215,8 @@ TEST_F(ForkTest, PrivateMapping) {\nEXPECT_THAT(Wait(child), SyscallSucceedsWithValue(0));\n}\n+// CPUID is x86 specific.\n+#ifdef __x86_64__\n// Test that cpuid works after a fork.\nTEST_F(ForkTest, Cpuid) {\npid_t child = Fork();\n@@ -227,6 +229,7 @@ TEST_F(ForkTest, Cpuid) {\n}\nEXPECT_THAT(Wait(child), SyscallSucceedsWithValue(0));\n}\n+#endif\nTEST_F(ForkTest, Mmap) {\npid_t child = Fork();\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/getdents.cc", "new_path": "test/syscalls/linux/getdents.cc", "diff": "@@ -228,19 +228,27 @@ class GetdentsTest : public ::testing::Test {\n// Multiple template parameters are not allowed, so we must use explicit\n// template specialization to set the syscall number.\n+#ifdef __x86_64__\ntemplate <>\nint GetdentsTest<struct linux_dirent>::SyscallNum() {\nreturn SYS_getdents;\n}\n+#endif\ntemplate <>\nint GetdentsTest<struct linux_dirent64>::SyscallNum() {\nreturn SYS_getdents64;\n}\n-// Test both legacy getdents and getdents64.\n+#ifdef __x86_64__\n+// Test both legacy getdents and getdents64 on x86_64.\ntypedef ::testing::Types<struct linux_dirent, struct linux_dirent64>\nGetdentsTypes;\n+#elif __aarch64__\n+// Test only getdents64 on arm64.\n+typedef ::testing::Types<struct linux_dirent64>\n+ GetdentsTypes;\n+#endif\nTYPED_TEST_SUITE(GetdentsTest, GetdentsTypes);\n// N.B. TYPED_TESTs require explicitly using this-> to access members of\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/preadv2.cc", "new_path": "test/syscalls/linux/preadv2.cc", "diff": "@@ -35,6 +35,8 @@ namespace {\n#ifndef SYS_preadv2\n#if defined(__x86_64__)\n#define SYS_preadv2 327\n+#elif defined(__aarch64__)\n+#define SYS_preadv2 286\n#else\n#error \"Unknown architecture\"\n#endif\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -1986,7 +1986,7 @@ TEST(Proc, GetdentsEnoent) {\n},\nnullptr, nullptr));\nchar buf[1024];\n- ASSERT_THAT(syscall(SYS_getdents, fd.get(), buf, sizeof(buf)),\n+ ASSERT_THAT(syscall(SYS_getdents64, fd.get(), buf, sizeof(buf)),\nSyscallFailsWithErrno(ENOENT));\n}\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pwritev2.cc", "new_path": "test/syscalls/linux/pwritev2.cc", "diff": "@@ -34,6 +34,8 @@ namespace {\n#ifndef SYS_pwritev2\n#if defined(__x86_64__)\n#define SYS_pwritev2 328\n+#elif defined(__aarch64__)\n+#define SYS_pwritev2 287\n#else\n#error \"Unknown architecture\"\n#endif\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/seccomp.cc", "new_path": "test/syscalls/linux/seccomp.cc", "diff": "@@ -49,7 +49,12 @@ namespace testing {\nnamespace {\n// A syscall not implemented by Linux that we don't expect to be called.\n+#ifdef __x86_64__\nconstexpr uint32_t kFilteredSyscall = SYS_vserver;\n+#elif __aarch64__\n+// Using arch_specific_syscalls which are not implemented on arm64.\n+constexpr uint32_t kFilteredSyscall = SYS_arch_specific_syscall+15;\n+#endif\n// Applies a seccomp-bpf filter that returns `filtered_result` for\n// `sysno` and allows all other syscalls. Async-signal-safe.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/stat.cc", "new_path": "test/syscalls/linux/stat.cc", "diff": "@@ -557,6 +557,8 @@ TEST(SimpleStatTest, AnonDeviceAllocatesUniqueInodesAcrossSaveRestore) {\n#ifndef SYS_statx\n#if defined(__x86_64__)\n#define SYS_statx 332\n+#elif defined(__aarch64__)\n+#define SYS_statx 291\n#else\n#error \"Unknown architecture\"\n#endif\n" }, { "change_type": "MODIFY", "old_path": "test/util/signal_util.h", "new_path": "test/util/signal_util.h", "diff": "@@ -85,6 +85,20 @@ inline void FixupFault(ucontext_t* ctx) {\n// The encoding is 0x48 0xab 0x00.\nctx->uc_mcontext.gregs[REG_RIP] += 3;\n}\n+#elif __aarch64__\n+inline void Fault() {\n+ // Zero and dereference x0.\n+ asm(\"mov xzr, x0\\r\\n\"\n+ \"str xzr, [x0]\\r\\n\"\n+ :\n+ :\n+ : \"x0\");\n+}\n+\n+inline void FixupFault(ucontext_t* ctx) {\n+ // Skip the bad instruction above.\n+ ctx->uc_mcontext.pc += 4;\n+}\n#endif\n} // namespace testing\n" }, { "change_type": "MODIFY", "old_path": "test/util/test_util.cc", "new_path": "test/util/test_util.cc", "diff": "@@ -76,7 +76,6 @@ bool IsRunningWithHostinet() {\n\"xchg %%rdi, %%rbx\\n\" \\\n: \"=a\"(a), \"=D\"(b), \"=c\"(c), \"=d\"(d) \\\n: \"a\"(a_inp), \"2\"(c_inp))\n-#endif // defined(__x86_64__)\nCPUVendor GetCPUVendor() {\nuint32_t eax, ebx, ecx, edx;\n@@ -93,6 +92,7 @@ CPUVendor GetCPUVendor() {\n}\nreturn CPUVendor::kUnknownVendor;\n}\n+#endif // defined(__x86_64__)\nbool operator==(const KernelVersion& first, const KernelVersion& second) {\nreturn first.major == second.major && first.minor == second.minor &&\n" } ]
Go
Apache License 2.0
google/gvisor
Enable build of test/syscall tests on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I277d6c708bbf5c3edd7c3568941cfd01dc122e17
259,884
17.01.2020 02:40:46
18,000
3bdcdb0097d4a1d499d78c9e5a50dab2e1a01e0a
Dedup remark config
[ { "change_type": "DELETE", "old_path": "content/.remarkrc", "new_path": null, "diff": "-{\n- \"settings\": {\n- \"footnotes\": true\n- },\n- \"plugins\": [\n- \"remark-preset-lint-recommended\",\n- [\"remark-lint-list-item-indent\", false]\n- ]\n-}\n" }, { "change_type": "MODIFY", "old_path": "package.json", "new_path": "package.json", "diff": "\"lint-md\": \"remark ./content -f\"\n},\n\"remarkConfig\": {\n+ \"settings\": {\n+ \"footnotes\": true\n+ },\n\"plugins\": [\n- \"remark-preset-lint-recommended\"\n+ \"remark-preset-lint-recommended\",\n+ [\"remark-lint-list-item-indent\", false]\n]\n}\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Dedup remark config
259,860
17.01.2020 08:10:14
28,800
345df7cab48ac79bccf2620900cd972b3026296d
Add explanation for implementation of BSD full file locks.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/lock/lock.go", "new_path": "pkg/sentry/fs/lock/lock.go", "diff": "@@ -78,6 +78,9 @@ const (\n)\n// LockEOF is the maximal possible end of a regional file lock.\n+//\n+// A BSD-style full file lock can be represented as a regional file lock from\n+// offset 0 to LockEOF.\nconst LockEOF = math.MaxUint64\n// Lock is a regional file lock. It consists of either a single writer\n" } ]
Go
Apache License 2.0
google/gvisor
Add explanation for implementation of BSD full file locks. PiperOrigin-RevId: 290272560
259,974
17.01.2020 08:22:21
28,800
acf2d6dcc34501d2573f9c3f2b6da80308f3267e
Enable stat syscall support on arm64. x86 and arm64 use a different stat struct in Linux kernel, so the stat() syscall implementation has to handle the file stat data separately. COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1493 from xiaobo55x:stat
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/BUILD", "new_path": "pkg/sentry/syscalls/linux/BUILD", "diff": "@@ -42,6 +42,8 @@ go_library(\n\"sys_socket.go\",\n\"sys_splice.go\",\n\"sys_stat.go\",\n+ \"sys_stat_amd64.go\",\n+ \"sys_stat_arm64.go\",\n\"sys_sync.go\",\n\"sys_sysinfo.go\",\n\"sys_syslog.go\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64_arm64.go", "new_path": "pkg/sentry/syscalls/linux/linux64_arm64.go", "diff": "@@ -61,6 +61,7 @@ var ARM64 = &kernel.SyscallTable{\n22: syscalls.Supported(\"epoll_pwait\", EpollPwait),\n23: syscalls.Supported(\"dup\", Dup),\n24: syscalls.Supported(\"dup3\", Dup3),\n+ 25: syscalls.PartiallySupported(\"fcntl\", Fcntl, \"Not all options are supported.\", nil),\n26: syscalls.Supported(\"inotify_init1\", InotifyInit1),\n27: syscalls.PartiallySupported(\"inotify_add_watch\", InotifyAddWatch, \"inotify events are only available inside the sandbox.\", nil),\n28: syscalls.PartiallySupported(\"inotify_rm_watch\", InotifyRmWatch, \"inotify events are only available inside the sandbox.\", nil),\n@@ -78,7 +79,9 @@ var ARM64 = &kernel.SyscallTable{\n40: syscalls.PartiallySupported(\"mount\", Mount, \"Not all options or file systems are supported.\", nil),\n41: syscalls.Error(\"pivot_root\", syserror.EPERM, \"\", nil),\n42: syscalls.Error(\"nfsservctl\", syserror.ENOSYS, \"Removed after Linux 3.1.\", nil),\n+ 43: syscalls.PartiallySupported(\"statfs\", Statfs, \"Depends on the backing file system implementation.\", nil),\n44: syscalls.PartiallySupported(\"fstatfs\", Fstatfs, \"Depends on the backing file system implementation.\", nil),\n+ 45: syscalls.Supported(\"truncate\", Truncate),\n46: syscalls.Supported(\"ftruncate\", Ftruncate),\n47: syscalls.PartiallySupported(\"fallocate\", Fallocate, \"Not all options are supported.\", nil),\n48: syscalls.Supported(\"faccessat\", Faccessat),\n@@ -112,6 +115,7 @@ var ARM64 = &kernel.SyscallTable{\n76: syscalls.PartiallySupported(\"splice\", Splice, \"Stub implementation.\", []string{\"gvisor.dev/issue/138\"}), // TODO(b/29354098)\n77: syscalls.Supported(\"tee\", Tee),\n78: syscalls.Supported(\"readlinkat\", Readlinkat),\n+ 79: syscalls.Supported(\"fstatat\", Fstatat),\n80: syscalls.Supported(\"fstat\", Fstat),\n81: syscalls.PartiallySupported(\"sync\", Sync, \"Full data flush is not guaranteed at this time.\", nil),\n82: syscalls.PartiallySupported(\"fsync\", Fsync, \"Full data flush is not guaranteed at this time.\", nil),\n@@ -254,6 +258,8 @@ var ARM64 = &kernel.SyscallTable{\n219: syscalls.Error(\"keyctl\", syserror.EACCES, \"Not available to user.\", nil),\n220: syscalls.PartiallySupported(\"clone\", Clone, \"Mount namespace (CLONE_NEWNS) not supported. Options CLONE_PARENT, CLONE_SYSVSEM not supported.\", nil),\n221: syscalls.Supported(\"execve\", Execve),\n+ 222: syscalls.PartiallySupported(\"mmap\", Mmap, \"Generally supported with exceptions. Options MAP_FIXED_NOREPLACE, MAP_SHARED_VALIDATE, MAP_SYNC MAP_GROWSDOWN, MAP_HUGETLB are not supported.\", nil),\n+ 223: syscalls.PartiallySupported(\"fadvise64\", Fadvise64, \"Not all options are supported.\", nil),\n224: syscalls.CapError(\"swapon\", linux.CAP_SYS_ADMIN, \"\", nil),\n225: syscalls.CapError(\"swapoff\", linux.CAP_SYS_ADMIN, \"\", nil),\n226: syscalls.Supported(\"mprotect\", Mprotect),\n@@ -299,6 +305,8 @@ var ARM64 = &kernel.SyscallTable{\n282: syscalls.ErrorWithEvent(\"userfaultfd\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/266\"}), // TODO(b/118906345)\n283: syscalls.ErrorWithEvent(\"membarrier\", syserror.ENOSYS, \"\", []string{\"gvisor.dev/issue/267\"}), // TODO(gvisor.dev/issue/267)\n284: syscalls.PartiallySupported(\"mlock2\", Mlock2, \"Stub implementation. The sandbox lacks appropriate permissions.\", nil),\n+\n+ // Syscalls after 284 are \"backports\" from versions of Linux after 4.4.\n285: syscalls.ErrorWithEvent(\"copy_file_range\", syserror.ENOSYS, \"\", nil),\n286: syscalls.Supported(\"preadv2\", Preadv2),\n287: syscalls.PartiallySupported(\"pwritev2\", Pwritev2, \"Flag RWF_HIPRI is not supported.\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_stat.go", "new_path": "pkg/sentry/syscalls/linux/sys_stat.go", "diff": "@@ -16,7 +16,6 @@ package linux\nimport (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\n\"gvisor.dev/gvisor/pkg/sentry/arch\"\n\"gvisor.dev/gvisor/pkg/sentry/fs\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n@@ -125,56 +124,6 @@ func fstat(t *kernel.Task, f *fs.File, statAddr usermem.Addr) error {\nreturn copyOutStat(t, statAddr, f.Dirent.Inode.StableAttr, uattr)\n}\n-// copyOutStat copies the attributes (sattr, uattr) to the struct stat at\n-// address dst in t's address space. It encodes the stat struct to bytes\n-// manually, as stat() is a very common syscall for many applications, and\n-// t.CopyObjectOut has noticeable performance impact due to its many slice\n-// allocations and use of reflection.\n-func copyOutStat(t *kernel.Task, dst usermem.Addr, sattr fs.StableAttr, uattr fs.UnstableAttr) error {\n- b := t.CopyScratchBuffer(int(linux.SizeOfStat))[:0]\n-\n- // Dev (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.DeviceID))\n- // Ino (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.InodeID))\n- // Nlink (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uattr.Links)\n- // Mode (uint32)\n- b = binary.AppendUint32(b, usermem.ByteOrder, sattr.Type.LinuxType()|uint32(uattr.Perms.LinuxMode()))\n- // UID (uint32)\n- b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()))\n- // GID (uint32)\n- b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()))\n- // Padding (uint32)\n- b = binary.AppendUint32(b, usermem.ByteOrder, 0)\n- // Rdev (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)))\n- // Size (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Size))\n- // Blksize (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.BlockSize))\n- // Blocks (uint64)\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Usage/512))\n-\n- // ATime\n- atime := uattr.AccessTime.Timespec()\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Sec))\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Nsec))\n-\n- // MTime\n- mtime := uattr.ModificationTime.Timespec()\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Sec))\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Nsec))\n-\n- // CTime\n- ctime := uattr.StatusChangeTime.Timespec()\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Sec))\n- b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Nsec))\n-\n- _, err := t.CopyOutBytes(dst, b)\n- return err\n-}\n-\n// Statx implements linux syscall statx(2).\nfunc Statx(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\nfd := args[0].Int()\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_stat_amd64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//+build amd64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+)\n+\n+// copyOutStat copies the attributes (sattr, uattr) to the struct stat at\n+// address dst in t's address space. It encodes the stat struct to bytes\n+// manually, as stat() is a very common syscall for many applications, and\n+// t.CopyObjectOut has noticeable performance impact due to its many slice\n+// allocations and use of reflection.\n+func copyOutStat(t *kernel.Task, dst usermem.Addr, sattr fs.StableAttr, uattr fs.UnstableAttr) error {\n+ b := t.CopyScratchBuffer(int(linux.SizeOfStat))[:0]\n+\n+ // Dev (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.DeviceID))\n+ // Ino (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.InodeID))\n+ // Nlink (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uattr.Links)\n+ // Mode (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, sattr.Type.LinuxType()|uint32(uattr.Perms.LinuxMode()))\n+ // UID (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()))\n+ // GID (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()))\n+ // Padding (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, 0)\n+ // Rdev (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)))\n+ // Size (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Size))\n+ // Blksize (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.BlockSize))\n+ // Blocks (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Usage/512))\n+\n+ // ATime\n+ atime := uattr.AccessTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Nsec))\n+\n+ // MTime\n+ mtime := uattr.ModificationTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Nsec))\n+\n+ // CTime\n+ ctime := uattr.StatusChangeTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Nsec))\n+\n+ _, err := t.CopyOutBytes(dst, b)\n+ return err\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/syscalls/linux/sys_stat_arm64.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+//+build arm64\n+\n+package linux\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/binary\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+)\n+\n+// copyOutStat copies the attributes (sattr, uattr) to the struct stat at\n+// address dst in t's address space. It encodes the stat struct to bytes\n+// manually, as stat() is a very common syscall for many applications, and\n+// t.CopyObjectOut has noticeable performance impact due to its many slice\n+// allocations and use of reflection.\n+func copyOutStat(t *kernel.Task, dst usermem.Addr, sattr fs.StableAttr, uattr fs.UnstableAttr) error {\n+ b := t.CopyScratchBuffer(int(linux.SizeOfStat))[:0]\n+\n+ // Dev (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.DeviceID))\n+ // Ino (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(sattr.InodeID))\n+ // Mode (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, sattr.Type.LinuxType()|uint32(uattr.Perms.LinuxMode()))\n+ // Nlink (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Links))\n+ // UID (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()))\n+ // GID (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(uattr.Owner.GID.In(t.UserNamespace()).OrOverflow()))\n+ // Rdev (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(linux.MakeDeviceID(sattr.DeviceFileMajor, sattr.DeviceFileMinor)))\n+ // Padding (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, 0)\n+ // Size (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Size))\n+ // Blksize (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, uint32(sattr.BlockSize))\n+ // Padding (uint32)\n+ b = binary.AppendUint32(b, usermem.ByteOrder, 0)\n+ // Blocks (uint64)\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(uattr.Usage/512))\n+\n+ // ATime\n+ atime := uattr.AccessTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(atime.Nsec))\n+\n+ // MTime\n+ mtime := uattr.ModificationTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(mtime.Nsec))\n+\n+ // CTime\n+ ctime := uattr.StatusChangeTime.Timespec()\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Sec))\n+ b = binary.AppendUint64(b, usermem.ByteOrder, uint64(ctime.Nsec))\n+\n+ _, err := t.CopyOutBytes(dst, b)\n+ return err\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Enable stat syscall support on arm64. x86 and arm64 use a different stat struct in Linux kernel, so the stat() syscall implementation has to handle the file stat data separately. Signed-off-by: Haibo Xu <[email protected]> Change-Id: If3986e915a667362257a54e7fbbcc1fe18951015 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/gvisor/pull/1493 from xiaobo55x:stat f15a216d9297eb9a96d2c483d396a9919145d7fa PiperOrigin-RevId: 290274287
259,992
17.01.2020 09:33:14
28,800
ff9960985848a48863c01f91acd5b34d3e83a9c5
Add /proc/net/* files Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/BUILD", "new_path": "pkg/sentry/fsimpl/proc/BUILD", "diff": "@@ -18,7 +18,6 @@ go_library(\nimportpath = \"gvisor.dev/gvisor/pkg/sentry/fsimpl/proc\",\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/binary\",\n\"//pkg/log\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/fs\",\n@@ -37,6 +36,7 @@ go_library(\n\"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n+ \"//pkg/tcpip/header\",\n],\n)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -67,6 +67,7 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\n\"sys\": newSysDir(root, inoGen),\n\"meminfo\": newDentry(root, inoGen.NextIno(), 0444, &meminfoData{}),\n\"mounts\": kernfs.NewStaticSymlink(root, inoGen.NextIno(), \"self/mounts\"),\n+ \"net\": newNetDir(root, inoGen, k),\n\"stat\": newDentry(root, inoGen.NextIno(), 0444, &statData{}),\n\"uptime\": newDentry(root, inoGen.NextIno(), 0444, &uptimeData{}),\n\"version\": newDentry(root, inoGen.NextIno(), 0444, &versionData{}),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_net.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_net.go", "diff": "@@ -17,33 +17,88 @@ package proc\nimport (\n\"bytes\"\n\"fmt\"\n+ \"io\"\n+ \"reflect\"\n+ \"time\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/binary\"\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/fsimpl/kernfs\"\n\"gvisor.dev/gvisor/pkg/sentry/inet\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/socket\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix\"\n\"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport\"\n- \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n)\n+func newNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *kernfs.Dentry {\n+ var contents map[string]*kernfs.Dentry\n+ if stack := k.NetworkStack(); stack != nil {\n+ const (\n+ arp = \"IP address HW type Flags HW address Mask Device\"\n+ netlink = \"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\"\n+ packet = \"sk RefCnt Type Proto Iface R Rmem User Inode\"\n+ protocols = \"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\"\n+ ptype = \"Type Device Function\"\n+ upd6 = \" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"\n+ )\n+ psched := fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond))\n+\n+ contents = map[string]*kernfs.Dentry{\n+ \"dev\": newDentry(root, inoGen.NextIno(), 0444, &netDevData{stack: stack}),\n+ \"snmp\": newDentry(root, inoGen.NextIno(), 0444, &netSnmpData{stack: stack}),\n+\n+ // The following files are simple stubs until they are implemented in\n+ // netstack, if the file contains a header the stub is just the header\n+ // otherwise it is an empty file.\n+ \"arp\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(arp)),\n+ \"netlink\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(netlink)),\n+ \"netstat\": newDentry(root, inoGen.NextIno(), 0444, &netStatData{}),\n+ \"packet\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(packet)),\n+ \"protocols\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(protocols)),\n+\n+ // Linux sets psched values to: nsec per usec, psched tick in ns, 1000000,\n+ // high res timer ticks per sec (ClockGetres returns 1ns resolution).\n+ \"psched\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(psched)),\n+ \"ptype\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(ptype)),\n+ \"route\": newDentry(root, inoGen.NextIno(), 0444, &netRouteData{stack: stack}),\n+ \"tcp\": newDentry(root, inoGen.NextIno(), 0444, &netTCPData{kernel: k}),\n+ \"udp\": newDentry(root, inoGen.NextIno(), 0444, &netUDPData{kernel: k}),\n+ \"unix\": newDentry(root, inoGen.NextIno(), 0444, &netUnixData{kernel: k}),\n+ }\n+\n+ if stack.SupportsIPv6() {\n+ contents[\"if_inet6\"] = newDentry(root, inoGen.NextIno(), 0444, &ifinet6{stack: stack})\n+ contents[\"ipv6_route\"] = newDentry(root, inoGen.NextIno(), 0444, newStaticFile(\"\"))\n+ contents[\"tcp6\"] = newDentry(root, inoGen.NextIno(), 0444, &netTCP6Data{kernel: k})\n+ contents[\"udp6\"] = newDentry(root, inoGen.NextIno(), 0444, newStaticFile(upd6))\n+ }\n+ }\n+\n+ return kernfs.NewStaticDir(root, inoGen.NextIno(), 0555, contents)\n+}\n+\n// ifinet6 implements vfs.DynamicBytesSource for /proc/net/if_inet6.\n//\n// +stateify savable\ntype ifinet6 struct {\n- s inet.Stack\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack\n}\n-var _ vfs.DynamicBytesSource = (*ifinet6)(nil)\n+var _ dynamicInode = (*ifinet6)(nil)\nfunc (n *ifinet6) contents() []string {\nvar lines []string\n- nics := n.s.Interfaces()\n- for id, naddrs := range n.s.InterfaceAddrs() {\n+ nics := n.stack.Interfaces()\n+ for id, naddrs := range n.stack.InterfaceAddrs() {\nnic, ok := nics[id]\nif !ok {\n// NIC was added after NICNames was called. We'll just ignore it.\n@@ -77,18 +132,20 @@ func (n *ifinet6) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n-// netDev implements vfs.DynamicBytesSource for /proc/net/dev.\n+// netDevData implements vfs.DynamicBytesSource for /proc/net/dev.\n//\n// +stateify savable\n-type netDev struct {\n- s inet.Stack\n+type netDevData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack\n}\n-var _ vfs.DynamicBytesSource = (*netDev)(nil)\n+var _ dynamicInode = (*netDevData)(nil)\n// Generate implements vfs.DynamicBytesSource.Generate.\n-func (n *netDev) Generate(ctx context.Context, buf *bytes.Buffer) error {\n- interfaces := n.s.Interfaces()\n+func (n *netDevData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ interfaces := n.stack.Interfaces()\nbuf.WriteString(\"Inter-| Receive | Transmit\\n\")\nbuf.WriteString(\" face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed\\n\")\n@@ -96,7 +153,7 @@ func (n *netDev) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Implements the same format as\n// net/core/net-procfs.c:dev_seq_printf_stats.\nvar stats inet.StatDev\n- if err := n.s.Statistics(&stats, i.Name); err != nil {\n+ if err := n.stack.Statistics(&stats, i.Name); err != nil {\nlog.Warningf(\"Failed to retrieve interface statistics for %v: %v\", i.Name, err)\ncontinue\n}\n@@ -128,19 +185,21 @@ func (n *netDev) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n-// netUnix implements vfs.DynamicBytesSource for /proc/net/unix.\n+// netUnixData implements vfs.DynamicBytesSource for /proc/net/unix.\n//\n// +stateify savable\n-type netUnix struct {\n- k *kernel.Kernel\n+type netUnixData struct {\n+ kernfs.DynamicBytesFile\n+\n+ kernel *kernel.Kernel\n}\n-var _ vfs.DynamicBytesSource = (*netUnix)(nil)\n+var _ dynamicInode = (*netUnixData)(nil)\n// Generate implements vfs.DynamicBytesSource.Generate.\n-func (n *netUnix) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+func (n *netUnixData) Generate(ctx context.Context, buf *bytes.Buffer) error {\nbuf.WriteString(\"Num RefCount Protocol Flags Type St Inode Path\\n\")\n- for _, se := range n.k.ListSockets() {\n+ for _, se := range n.kernel.ListSockets() {\ns := se.Sock.Get()\nif s == nil {\nlog.Debugf(\"Couldn't resolve weakref %v in socket table, racing with destruction?\", se.Sock)\n@@ -213,22 +272,72 @@ func (n *netUnix) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n-// netTCP implements vfs.DynamicBytesSource for /proc/net/tcp.\n+func networkToHost16(n uint16) uint16 {\n+ // n is in network byte order, so is big-endian. The most-significant byte\n+ // should be stored in the lower address.\n//\n-// +stateify savable\n-type netTCP struct {\n- k *kernel.Kernel\n+ // We manually inline binary.BigEndian.Uint16() because Go does not support\n+ // non-primitive consts, so binary.BigEndian is a (mutable) var, so calls to\n+ // binary.BigEndian.Uint16() require a read of binary.BigEndian and an\n+ // interface method call, defeating inlining.\n+ buf := [2]byte{byte(n >> 8 & 0xff), byte(n & 0xff)}\n+ return usermem.ByteOrder.Uint16(buf[:])\n}\n-var _ vfs.DynamicBytesSource = (*netTCP)(nil)\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+ // formatted with %X. See get_tcp4_sock() and udp4_format_sock() in Linux.\n+ port := networkToHost16(a.Port)\n+\n+ // linux.SockAddrInet.Addr is stored as a byte slice in big-endian order\n+ // (i.e. most-significant byte in index 0). Linux represents this as a\n+ // __be32 which is a typedef for an unsigned int, and is printed with\n+ // %X. This means that for a little-endian machine, Linux prints the\n+ // least-significant byte of the address first. To emulate this, we first\n+ // invert the byte order for the address using usermem.ByteOrder.Uint32,\n+ // which makes it have the equivalent encoding to a __be32 on a little\n+ // endian machine. Note that this operation is a no-op on a big endian\n+ // machine. Then similar to Linux, we format it with %X, which will print\n+ // the most-significant byte of the __be32 address first, which is now\n+ // actually the least-significant byte of the original address in\n+ // linux.SockAddrInet.Addr on little endian machines, due to the conversion.\n+ addr := usermem.ByteOrder.Uint32(a.Addr[:])\n+\n+ fmt.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+\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-func (n *netTCP) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+func commonGenerateTCP(ctx context.Context, buf *bytes.Buffer, k *kernel.Kernel, family int) error {\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.\nt := kernel.TaskFromContext(ctx)\n- buf.WriteString(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode \\n\")\n- for _, se := range n.k.ListSockets() {\n+\n+ for _, se := range k.ListSockets() {\ns := se.Sock.Get()\nif s == nil {\n- log.Debugf(\"Couldn't resolve weakref %+v in socket table, racing with destruction?\", se.Sock)\n+ log.Debugf(\"Couldn't resolve weakref with ID %v in socket table, racing with destruction?\", se.ID)\ncontinue\n}\nsfile := s.(*fs.File)\n@@ -236,7 +345,7 @@ func (n *netTCP) Generate(ctx context.Context, buf *bytes.Buffer) error {\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 fa, stype, _ := sops.Type(); !(family == fa && stype == linux.SOCK_STREAM) {\ns.DecRef()\n// Not tcp4 sockets.\ncontinue\n@@ -250,27 +359,23 @@ func (n *netTCP) Generate(ctx context.Context, buf *bytes.Buffer) error {\n// Field: sl; entry number.\nfmt.Fprintf(buf, \"%4d: \", se.ID)\n- portBuf := make([]byte, 2)\n-\n// Field: local_adddress.\n- var localAddr linux.SockAddrInet\n+ var localAddr linux.SockAddr\n+ if t != nil {\nif local, _, err := sops.GetSockName(t); err == nil {\n- localAddr = *local.(*linux.SockAddrInet)\n+ localAddr = local\n}\n- binary.LittleEndian.PutUint16(portBuf, localAddr.Port)\n- fmt.Fprintf(buf, \"%08X:%04X \",\n- binary.LittleEndian.Uint32(localAddr.Addr[:]),\n- portBuf)\n+ }\n+ writeInetAddr(buf, family, localAddr)\n// Field: rem_address.\n- var remoteAddr linux.SockAddrInet\n+ var remoteAddr linux.SockAddr\n+ if t != nil {\nif remote, _, err := sops.GetPeerName(t); err == nil {\n- remoteAddr = *remote.(*linux.SockAddrInet)\n+ remoteAddr = remote\n}\n- binary.LittleEndian.PutUint16(portBuf, remoteAddr.Port)\n- fmt.Fprintf(buf, \"%08X:%04X \",\n- binary.LittleEndian.Uint32(remoteAddr.Addr[:]),\n- portBuf)\n+ }\n+ writeInetAddr(buf, family, remoteAddr)\n// Field: state; socket state.\nfmt.Fprintf(buf, \"%02X \", sops.State())\n@@ -293,7 +398,8 @@ func (n *netTCP) Generate(ctx context.Context, buf *bytes.Buffer) error {\nlog.Warningf(\"Failed to retrieve unstable attr for socket file: %v\", err)\nfmt.Fprintf(buf, \"%5d \", 0)\n} else {\n- fmt.Fprintf(buf, \"%5d \", uint32(uattr.Owner.UID.In(t.UserNamespace()).OrOverflow()))\n+ creds := auth.CredentialsFromContext(ctx)\n+ fmt.Fprintf(buf, \"%5d \", uint32(uattr.Owner.UID.In(creds.UserNamespace).OrOverflow()))\n}\n// Field: timeout; number of unanswered 0-window probes.\n@@ -335,3 +441,344 @@ func (n *netTCP) Generate(ctx context.Context, buf *bytes.Buffer) error {\nreturn nil\n}\n+\n+// netTCPData implements vfs.DynamicBytesSource for /proc/net/tcp.\n+//\n+// +stateify savable\n+type netTCPData struct {\n+ kernfs.DynamicBytesFile\n+\n+ kernel *kernel.Kernel\n+}\n+\n+var _ dynamicInode = (*netTCPData)(nil)\n+\n+func (d *netTCPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ buf.WriteString(\" sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode \\n\")\n+ return commonGenerateTCP(ctx, buf, d.kernel, linux.AF_INET)\n+}\n+\n+// netTCP6Data implements vfs.DynamicBytesSource for /proc/net/tcp6.\n+//\n+// +stateify savable\n+type netTCP6Data struct {\n+ kernfs.DynamicBytesFile\n+\n+ kernel *kernel.Kernel\n+}\n+\n+var _ dynamicInode = (*netTCP6Data)(nil)\n+\n+func (d *netTCP6Data) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ buf.WriteString(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\\n\")\n+ return commonGenerateTCP(ctx, buf, d.kernel, linux.AF_INET6)\n+}\n+\n+// netUDPData implements vfs.DynamicBytesSource for /proc/net/udp.\n+//\n+// +stateify savable\n+type netUDPData struct {\n+ kernfs.DynamicBytesFile\n+\n+ kernel *kernel.Kernel\n+}\n+\n+var _ dynamicInode = (*netUDPData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (d *netUDPData) Generate(ctx context.Context, buf *bytes.Buffer) error {\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+ t := kernel.TaskFromContext(ctx)\n+\n+ for _, se := range d.kernel.ListSockets() {\n+ s := se.Sock.Get()\n+ if s == nil {\n+ log.Debugf(\"Couldn't resolve weakref with ID %v in socket table, racing with destruction?\", se.ID)\n+ continue\n+ }\n+ sfile := s.(*fs.File)\n+ sops, ok := sfile.FileOperations.(socket.Socket)\n+ if !ok {\n+ panic(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_DGRAM {\n+ s.DecRef()\n+ // Not udp4 socket.\n+ continue\n+ }\n+\n+ // For Linux's implementation, see net/ipv4/udp.c:udp4_format_sock().\n+\n+ // Field: sl; entry number.\n+ fmt.Fprintf(buf, \"%5d: \", se.ID)\n+\n+ // Field: local_adddress.\n+ var localAddr linux.SockAddrInet\n+ if t != nil {\n+ if local, _, err := sops.GetSockName(t); err == nil {\n+ localAddr = *local.(*linux.SockAddrInet)\n+ }\n+ }\n+ writeInetAddr(buf, linux.AF_INET, &localAddr)\n+\n+ // Field: rem_address.\n+ var remoteAddr linux.SockAddrInet\n+ if t != nil {\n+ if remote, _, err := sops.GetPeerName(t); err == nil {\n+ remoteAddr = *remote.(*linux.SockAddrInet)\n+ }\n+ }\n+ writeInetAddr(buf, linux.AF_INET, &remoteAddr)\n+\n+ // Field: state; socket state.\n+ fmt.Fprintf(buf, \"%02X \", sops.State())\n+\n+ // Field: tx_queue, rx_queue; number of packets in the transmit and\n+ // receive queue. Unimplemented.\n+ fmt.Fprintf(buf, \"%08X:%08X \", 0, 0)\n+\n+ // Field: tr, tm->when. Always 0 for UDP.\n+ fmt.Fprintf(buf, \"%02X:%08X \", 0, 0)\n+\n+ // Field: retrnsmt. Always 0 for UDP.\n+ fmt.Fprintf(buf, \"%08X \", 0)\n+\n+ // Field: uid.\n+ uattr, err := sfile.Dirent.Inode.UnstableAttr(ctx)\n+ if err != nil {\n+ log.Warningf(\"Failed to retrieve unstable attr for socket file: %v\", err)\n+ fmt.Fprintf(buf, \"%5d \", 0)\n+ } else {\n+ creds := auth.CredentialsFromContext(ctx)\n+ fmt.Fprintf(buf, \"%5d \", uint32(uattr.Owner.UID.In(creds.UserNamespace).OrOverflow()))\n+ }\n+\n+ // Field: timeout. Always 0 for UDP.\n+ fmt.Fprintf(buf, \"%8d \", 0)\n+\n+ // Field: inode.\n+ fmt.Fprintf(buf, \"%8d \", sfile.InodeID())\n+\n+ // Field: ref; reference count on the socket inode. Don't count the ref\n+ // we obtain while deferencing the weakref to this socket.\n+ fmt.Fprintf(buf, \"%d \", sfile.ReadRefs()-1)\n+\n+ // Field: Socket struct address. Redacted due to the same reason as\n+ // the 'Num' field in /proc/net/unix, see netUnix.ReadSeqFileData.\n+ fmt.Fprintf(buf, \"%#016p \", (*socket.Socket)(nil))\n+\n+ // Field: drops; number of dropped packets. Unimplemented.\n+ fmt.Fprintf(buf, \"%d\", 0)\n+\n+ fmt.Fprintf(buf, \"\\n\")\n+\n+ s.DecRef()\n+ }\n+ return nil\n+}\n+\n+// netSnmpData implements vfs.DynamicBytesSource for /proc/net/snmp.\n+//\n+// +stateify savable\n+type netSnmpData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack\n+}\n+\n+var _ dynamicInode = (*netSnmpData)(nil)\n+\n+type snmpLine struct {\n+ prefix string\n+ header string\n+}\n+\n+var snmp = []snmpLine{\n+ {\n+ prefix: \"Ip\",\n+ header: \"Forwarding DefaultTTL InReceives InHdrErrors InAddrErrors ForwDatagrams InUnknownProtos InDiscards InDelivers OutRequests OutDiscards OutNoRoutes ReasmTimeout ReasmReqds ReasmOKs ReasmFails FragOKs FragFails FragCreates\",\n+ },\n+ {\n+ prefix: \"Icmp\",\n+ header: \"InMsgs InErrors InCsumErrors InDestUnreachs InTimeExcds InParmProbs InSrcQuenchs InRedirects InEchos InEchoReps InTimestamps InTimestampReps InAddrMasks InAddrMaskReps OutMsgs OutErrors OutDestUnreachs OutTimeExcds OutParmProbs OutSrcQuenchs OutRedirects OutEchos OutEchoReps OutTimestamps OutTimestampReps OutAddrMasks OutAddrMaskReps\",\n+ },\n+ {\n+ prefix: \"IcmpMsg\",\n+ },\n+ {\n+ prefix: \"Tcp\",\n+ header: \"RtoAlgorithm RtoMin RtoMax MaxConn ActiveOpens PassiveOpens AttemptFails EstabResets CurrEstab InSegs OutSegs RetransSegs InErrs OutRsts InCsumErrors\",\n+ },\n+ {\n+ prefix: \"Udp\",\n+ header: \"InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors InCsumErrors IgnoredMulti\",\n+ },\n+ {\n+ prefix: \"UdpLite\",\n+ header: \"InDatagrams NoPorts InErrors OutDatagrams RcvbufErrors SndbufErrors InCsumErrors IgnoredMulti\",\n+ },\n+}\n+\n+func toSlice(a interface{}) []uint64 {\n+ v := reflect.Indirect(reflect.ValueOf(a))\n+ return v.Slice(0, v.Len()).Interface().([]uint64)\n+}\n+\n+func sprintSlice(s []uint64) string {\n+ if len(s) == 0 {\n+ return \"\"\n+ }\n+ r := fmt.Sprint(s)\n+ return r[1 : len(r)-1] // Remove \"[]\" introduced by fmt of slice.\n+}\n+\n+// Generate implements vfs.DynamicBytesSource.\n+func (d *netSnmpData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ types := []interface{}{\n+ &inet.StatSNMPIP{},\n+ &inet.StatSNMPICMP{},\n+ nil, // TODO(gvisor.dev/issue/628): Support IcmpMsg stats.\n+ &inet.StatSNMPTCP{},\n+ &inet.StatSNMPUDP{},\n+ &inet.StatSNMPUDPLite{},\n+ }\n+ for i, stat := range types {\n+ line := snmp[i]\n+ if stat == nil {\n+ fmt.Fprintf(buf, \"%s:\\n\", line.prefix)\n+ fmt.Fprintf(buf, \"%s:\\n\", line.prefix)\n+ continue\n+ }\n+ if err := d.stack.Statistics(stat, line.prefix); err != nil {\n+ if err == syserror.EOPNOTSUPP {\n+ log.Infof(\"Failed to retrieve %s of /proc/net/snmp: %v\", line.prefix, err)\n+ } else {\n+ log.Warningf(\"Failed to retrieve %s of /proc/net/snmp: %v\", line.prefix, err)\n+ }\n+ }\n+\n+ fmt.Fprintf(buf, \"%s: %s\\n\", line.prefix, line.header)\n+\n+ if line.prefix == \"Tcp\" {\n+ tcp := stat.(*inet.StatSNMPTCP)\n+ // \"Tcp\" needs special processing because MaxConn is signed. RFC 2012.\n+ fmt.Sprintf(\"%s: %s %d %s\\n\", line.prefix, sprintSlice(tcp[:3]), int64(tcp[3]), sprintSlice(tcp[4:]))\n+ } else {\n+ fmt.Sprintf(\"%s: %s\\n\", line.prefix, sprintSlice(toSlice(stat)))\n+ }\n+ }\n+ return nil\n+}\n+\n+// netRouteData implements vfs.DynamicBytesSource for /proc/net/route.\n+//\n+// +stateify savable\n+type netRouteData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack\n+}\n+\n+var _ dynamicInode = (*netRouteData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.\n+// See Linux's net/ipv4/fib_trie.c:fib_route_seq_show.\n+func (d *netRouteData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"%-127s\\n\", \"Iface\\tDestination\\tGateway\\tFlags\\tRefCnt\\tUse\\tMetric\\tMask\\tMTU\\tWindow\\tIRTT\")\n+\n+ interfaces := d.stack.Interfaces()\n+ for _, rt := range d.stack.RouteTable() {\n+ // /proc/net/route only includes ipv4 routes.\n+ if rt.Family != linux.AF_INET {\n+ continue\n+ }\n+\n+ // /proc/net/route does not include broadcast or multicast routes.\n+ if rt.Type == linux.RTN_BROADCAST || rt.Type == linux.RTN_MULTICAST {\n+ continue\n+ }\n+\n+ iface, ok := interfaces[rt.OutputInterface]\n+ if !ok || iface.Name == \"lo\" {\n+ continue\n+ }\n+\n+ var (\n+ gw uint32\n+ prefix uint32\n+ flags = linux.RTF_UP\n+ )\n+ if len(rt.GatewayAddr) == header.IPv4AddressSize {\n+ flags |= linux.RTF_GATEWAY\n+ gw = usermem.ByteOrder.Uint32(rt.GatewayAddr)\n+ }\n+ if len(rt.DstAddr) == header.IPv4AddressSize {\n+ prefix = usermem.ByteOrder.Uint32(rt.DstAddr)\n+ }\n+ l := fmt.Sprintf(\n+ \"%s\\t%08X\\t%08X\\t%04X\\t%d\\t%d\\t%d\\t%08X\\t%d\\t%d\\t%d\",\n+ iface.Name,\n+ prefix,\n+ gw,\n+ flags,\n+ 0, // RefCnt.\n+ 0, // Use.\n+ 0, // Metric.\n+ (uint32(1)<<rt.DstLen)-1,\n+ 0, // MTU.\n+ 0, // Window.\n+ 0, // RTT.\n+ )\n+ fmt.Fprintf(buf, \"%-127s\\n\", l)\n+ }\n+ return nil\n+}\n+\n+// netStatData implements vfs.DynamicBytesSource for /proc/net/netstat.\n+//\n+// +stateify savable\n+type netStatData struct {\n+ kernfs.DynamicBytesFile\n+\n+ stack inet.Stack\n+}\n+\n+var _ dynamicInode = (*netStatData)(nil)\n+\n+// Generate implements vfs.DynamicBytesSource.\n+// See Linux's net/ipv4/fib_trie.c:fib_route_seq_show.\n+func (d *netStatData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ buf.WriteString(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed \" +\n+ \"EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps \" +\n+ \"LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive \" +\n+ \"PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost \" +\n+ \"ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog \" +\n+ \"TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser \" +\n+ \"TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging \" +\n+ \"TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo \" +\n+ \"TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit \" +\n+ \"TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans \" +\n+ \"TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes \" +\n+ \"TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail \" +\n+ \"TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent \" +\n+ \"TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose \" +\n+ \"TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed \" +\n+ \"TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld \" +\n+ \"TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected \" +\n+ \"TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback \" +\n+ \"TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter \" +\n+ \"TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail \" +\n+ \"TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK \" +\n+ \"TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail \" +\n+ \"TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow \" +\n+ \"TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets \" +\n+ \"TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv \" +\n+ \"TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect \" +\n+ \"TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd \" +\n+ \"TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq \" +\n+ \"TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge \" +\n+ \"TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\")\n+ return nil\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_sys_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_sys_test.go", "diff": "@@ -31,7 +31,7 @@ func newIPv6TestStack() *inet.TestStack {\n}\nfunc TestIfinet6NoAddresses(t *testing.T) {\n- n := &ifinet6{s: newIPv6TestStack()}\n+ n := &ifinet6{stack: newIPv6TestStack()}\nvar buf bytes.Buffer\nn.Generate(contexttest.Context(t), &buf)\nif buf.Len() > 0 {\n@@ -62,7 +62,7 @@ func TestIfinet6(t *testing.T) {\n\"101112131415161718191a1b1c1d1e1f 02 80 00 00 eth1\\n\": {},\n}\n- n := &ifinet6{s: s}\n+ n := &ifinet6{stack: s}\ncontents := n.contents()\nif len(contents) != len(want) {\nt.Errorf(\"Got len(n.contents()) = %d, want = %d\", len(contents), len(want))\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -73,6 +73,7 @@ func checkTasksStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\n\"loadavg\": {Type: linux.DT_REG},\n\"meminfo\": {Type: linux.DT_REG},\n\"mounts\": {Type: linux.DT_LNK},\n+ \"net\": {Type: linux.DT_DIR},\n\"self\": selfLink,\n\"stat\": {Type: linux.DT_REG},\n\"sys\": {Type: linux.DT_DIR},\n" } ]
Go
Apache License 2.0
google/gvisor
Add /proc/net/* files Updates #1195 PiperOrigin-RevId: 290285420
259,992
17.01.2020 10:39:24
28,800
8e8d0f96f651ce161dfe6003d738dbda28f7cb0e
Add /proc/[pid]/cgroups file Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/filesystem.go", "new_path": "pkg/sentry/fsimpl/proc/filesystem.go", "diff": "@@ -47,7 +47,12 @@ func (ft *procFSType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFile\nprocfs := &kernfs.Filesystem{}\nprocfs.VFSFilesystem().Init(vfsObj, procfs)\n- _, dentry := newTasksInode(procfs, k, pidns)\n+ var data *InternalData\n+ if opts.InternalData != nil {\n+ data = opts.InternalData.(*InternalData)\n+ }\n+\n+ _, dentry := newTasksInode(procfs, k, pidns, data.Cgroups)\nreturn procfs.VFSFilesystem(), dentry.VFSDentry(), nil\n}\n@@ -78,3 +83,9 @@ var _ dynamicInode = (*staticFile)(nil)\nfunc newStaticFile(data string) *staticFile {\nreturn &staticFile{StaticData: vfs.StaticData{Data: data}}\n}\n+\n+// InternalData contains internal data passed in to the procfs mount via\n+// vfs.GetFilesystemOptions.InternalData.\n+type InternalData struct {\n+ Cgroups map[string]string\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/subtasks.go", "new_path": "pkg/sentry/fsimpl/proc/subtasks.go", "diff": "@@ -38,15 +38,17 @@ type subtasksInode struct {\ntask *kernel.Task\npidns *kernel.PIDNamespace\ninoGen InoGenerator\n+ cgroupControllers map[string]string\n}\nvar _ kernfs.Inode = (*subtasksInode)(nil)\n-func newSubtasks(task *kernel.Task, pidns *kernel.PIDNamespace, inoGen InoGenerator) *kernfs.Dentry {\n+func newSubtasks(task *kernel.Task, pidns *kernel.PIDNamespace, inoGen InoGenerator, cgroupControllers map[string]string) *kernfs.Dentry {\nsubInode := &subtasksInode{\ntask: task,\npidns: pidns,\ninoGen: inoGen,\n+ cgroupControllers: cgroupControllers,\n}\n// Note: credentials are overridden by taskOwnedInode.\nsubInode.InodeAttrs.Init(task.Credentials(), inoGen.NextIno(), linux.ModeDirectory|0555)\n@@ -79,7 +81,7 @@ func (i *subtasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, e\nreturn nil, syserror.ENOENT\n}\n- subTaskDentry := newTaskInode(i.inoGen, subTask, i.pidns, false)\n+ subTaskDentry := newTaskInode(i.inoGen, subTask, i.pidns, false, i.cgroupControllers)\nreturn subTaskDentry.VFSDentry(), nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/task.go", "new_path": "pkg/sentry/fsimpl/proc/task.go", "diff": "package proc\nimport (\n+ \"bytes\"\n\"fmt\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n@@ -42,7 +43,7 @@ type taskInode struct {\nvar _ kernfs.Inode = (*taskInode)(nil)\n-func newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNamespace, isThreadGroup bool) *kernfs.Dentry {\n+func newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNamespace, isThreadGroup bool, cgroupControllers map[string]string) *kernfs.Dentry {\ncontents := map[string]*kernfs.Dentry{\n\"auxv\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &auxvData{task: task}),\n\"cmdline\": newTaskOwnedFile(task, inoGen.NextIno(), 0444, &cmdlineData{task: task, arg: cmdlineDataArg}),\n@@ -68,11 +69,11 @@ func newTaskInode(inoGen InoGenerator, task *kernel.Task, pidns *kernel.PIDNames\n\"uid_map\": newTaskOwnedFile(task, inoGen.NextIno(), 0644, &idMapData{task: task, gids: false}),\n}\nif isThreadGroup {\n- contents[\"task\"] = newSubtasks(task, pidns, inoGen)\n+ contents[\"task\"] = newSubtasks(task, pidns, inoGen, cgroupControllers)\n+ }\n+ if len(cgroupControllers) > 0 {\n+ contents[\"cgroup\"] = newTaskOwnedFile(task, inoGen.NextIno(), 0444, newCgroupData(cgroupControllers))\n}\n- //if len(p.cgroupControllers) > 0 {\n- // contents[\"cgroup\"] = newCGroupInode(t, msrc, p.cgroupControllers)\n- //}\ntaskInode := &taskInode{task: task}\n// Note: credentials are overridden by taskOwnedInode.\n@@ -227,3 +228,22 @@ func newNamespaceSymlink(task *kernel.Task, ino uint64, ns string) *kernfs.Dentr\nd.Init(taskInode)\nreturn d\n}\n+\n+// newCgroupData creates inode that shows cgroup information.\n+// From man 7 cgroups: \"For each cgroup hierarchy of which the process is a\n+// member, there is one entry containing three colon-separated fields:\n+// hierarchy-ID:controller-list:cgroup-path\"\n+func newCgroupData(controllers map[string]string) dynamicInode {\n+ buf := bytes.Buffer{}\n+\n+ // The hierarchy ids must be positive integers (for cgroup v1), but the\n+ // exact number does not matter, so long as they are unique. We can\n+ // just use a counter, but since linux sorts this file in descending\n+ // order, we must count down to preserve this behavior.\n+ i := len(controllers)\n+ for name, dir := range controllers {\n+ fmt.Fprintf(&buf, \"%d:%s:%s\\n\", i, name, dir)\n+ i--\n+ }\n+ return newStaticFile(buf.String())\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks.go", "new_path": "pkg/sentry/fsimpl/proc/tasks.go", "diff": "@@ -54,11 +54,16 @@ type tasksInode struct {\n// Linux. So handle them outside of OrderedChildren.\nselfSymlink *vfs.Dentry\nthreadSelfSymlink *vfs.Dentry\n+\n+ // cgroupControllers is a map of controller name to directory in the\n+ // cgroup hierarchy. These controllers are immutable and will be listed\n+ // in /proc/pid/cgroup if not nil.\n+ cgroupControllers map[string]string\n}\nvar _ kernfs.Inode = (*tasksInode)(nil)\n-func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNamespace) (*tasksInode, *kernfs.Dentry) {\n+func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNamespace, cgroupControllers map[string]string) (*tasksInode, *kernfs.Dentry) {\nroot := auth.NewRootCredentials(pidns.UserNamespace())\ncontents := map[string]*kernfs.Dentry{\n\"cpuinfo\": newDentry(root, inoGen.NextIno(), 0444, newStaticFile(cpuInfoData(k))),\n@@ -78,6 +83,7 @@ func newTasksInode(inoGen InoGenerator, k *kernel.Kernel, pidns *kernel.PIDNames\ninoGen: inoGen,\nselfSymlink: newSelfSymlink(root, inoGen.NextIno(), 0444, pidns).VFSDentry(),\nthreadSelfSymlink: newThreadSelfSymlink(root, inoGen.NextIno(), 0444, pidns).VFSDentry(),\n+ cgroupControllers: cgroupControllers,\n}\ninode.InodeAttrs.Init(root, inoGen.NextIno(), linux.ModeDirectory|0555)\n@@ -111,7 +117,7 @@ func (i *tasksInode) Lookup(ctx context.Context, name string) (*vfs.Dentry, erro\nreturn nil, syserror.ENOENT\n}\n- taskDentry := newTaskInode(i.inoGen, task, i.pidns, true)\n+ taskDentry := newTaskInode(i.inoGen, task, i.pidns, true, i.cgroupControllers)\nreturn taskDentry.VFSDentry(), nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -87,6 +87,7 @@ func checkTasksStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\nfunc checkTaskStaticFiles(gots []vfs.Dirent) ([]vfs.Dirent, error) {\nwants := map[string]vfs.Dirent{\n\"auxv\": {Type: linux.DT_REG},\n+ \"cgroup\": {Type: linux.DT_REG},\n\"cmdline\": {Type: linux.DT_REG},\n\"comm\": {Type: linux.DT_REG},\n\"environ\": {Type: linux.DT_REG},\n@@ -145,7 +146,15 @@ func setup() (context.Context, *vfs.VirtualFilesystem, vfs.VirtualDentry, error)\nvfsObj.MustRegisterFilesystemType(\"procfs\", &procFSType{}, &vfs.RegisterFilesystemTypeOptions{\nAllowUserMount: true,\n})\n- mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"procfs\", &vfs.GetFilesystemOptions{})\n+ fsOpts := vfs.GetFilesystemOptions{\n+ InternalData: &InternalData{\n+ Cgroups: map[string]string{\n+ \"cpuset\": \"/foo/cpuset\",\n+ \"memory\": \"/foo/memory\",\n+ },\n+ },\n+ }\n+ mntns, err := vfsObj.NewMountNamespace(ctx, creds, \"\", \"procfs\", &fsOpts)\nif err != nil {\nreturn nil, nil, vfs.VirtualDentry{}, fmt.Errorf(\"NewMountNamespace(): %v\", err)\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add /proc/[pid]/cgroups file Updates #1195 PiperOrigin-RevId: 290298266
259,853
17.01.2020 13:31:26
28,800
9073521098ee52cdda74a193565b7bbe75d8c35a
Convert EventMask to uint64 It is used for signalfd where the maximum signal is 64.
[ { "change_type": "MODIFY", "old_path": "pkg/waiter/waiter.go", "new_path": "pkg/waiter/waiter.go", "diff": "@@ -62,7 +62,7 @@ import (\n)\n// EventMask represents io events as used in the poll() syscall.\n-type EventMask uint16\n+type EventMask uint64\n// Events that waiters can wait on. The meaning is the same as those in the\n// poll() syscall.\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/BUILD", "new_path": "test/syscalls/BUILD", "diff": "@@ -380,6 +380,8 @@ syscall_test(test = \"//test/syscalls/linux:rseq_test\")\nsyscall_test(test = \"//test/syscalls/linux:rtsignal_test\")\n+syscall_test(test = \"//test/syscalls/linux:signalfd_test\")\n+\nsyscall_test(test = \"//test/syscalls/linux:sched_test\")\nsyscall_test(test = \"//test/syscalls/linux:sched_yield_test\")\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/signalfd.cc", "new_path": "test/syscalls/linux/signalfd.cc", "diff": "@@ -39,6 +39,7 @@ namespace testing {\nnamespace {\nconstexpr int kSigno = SIGUSR1;\n+constexpr int kSignoMax = 64; // SIGRTMAX\nconstexpr int kSignoAlt = SIGUSR2;\n// Returns a new signalfd.\n@@ -51,41 +52,45 @@ inline PosixErrorOr<FileDescriptor> NewSignalFD(sigset_t* mask, int flags = 0) {\nreturn FileDescriptor(fd);\n}\n-TEST(Signalfd, Basic) {\n+class SignalfdTest : public ::testing::TestWithParam<int> {};\n+\n+TEST_P(SignalfdTest, Basic) {\n+ int signo = GetParam();\n// Create the signalfd.\nsigset_t mask;\nsigemptyset(&mask);\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nFileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, 0));\n// Deliver the blocked signal.\nconst auto scoped_sigmask =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSigno));\n- ASSERT_THAT(tgkill(getpid(), gettid(), kSigno), SyscallSucceeds());\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, signo));\n+ ASSERT_THAT(tgkill(getpid(), gettid(), signo), SyscallSucceeds());\n// We should now read the signal.\nstruct signalfd_siginfo rbuf;\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n}\n-TEST(Signalfd, MaskWorks) {\n+TEST_P(SignalfdTest, MaskWorks) {\n+ int signo = GetParam();\n// Create two signalfds with different masks.\nsigset_t mask1, mask2;\nsigemptyset(&mask1);\nsigemptyset(&mask2);\n- sigaddset(&mask1, kSigno);\n+ sigaddset(&mask1, signo);\nsigaddset(&mask2, kSignoAlt);\nFileDescriptor fd1 = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask1, 0));\nFileDescriptor fd2 = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask2, 0));\n// Deliver the two signals.\nconst auto scoped_sigmask1 =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSigno));\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, signo));\nconst auto scoped_sigmask2 =\nASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSignoAlt));\n- ASSERT_THAT(tgkill(getpid(), gettid(), kSigno), SyscallSucceeds());\n+ ASSERT_THAT(tgkill(getpid(), gettid(), signo), SyscallSucceeds());\nASSERT_THAT(tgkill(getpid(), gettid(), kSignoAlt), SyscallSucceeds());\n// We should see the signals on the appropriate signalfds.\n@@ -98,7 +103,7 @@ TEST(Signalfd, MaskWorks) {\nEXPECT_EQ(rbuf2.ssi_signo, kSignoAlt);\nASSERT_THAT(read(fd1.get(), &rbuf1, sizeof(rbuf1)),\nSyscallSucceedsWithValue(sizeof(rbuf1)));\n- EXPECT_EQ(rbuf1.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf1.ssi_signo, signo);\n}\nTEST(Signalfd, Cloexec) {\n@@ -111,11 +116,12 @@ TEST(Signalfd, Cloexec) {\nEXPECT_THAT(fcntl(fd.get(), F_GETFD), SyscallSucceedsWithValue(FD_CLOEXEC));\n}\n-TEST(Signalfd, Blocking) {\n+TEST_P(SignalfdTest, Blocking) {\n+ int signo = GetParam();\n// Create the signalfd in blocking mode.\nsigset_t mask;\nsigemptyset(&mask);\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nFileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, 0));\n// Shared tid variable.\n@@ -136,7 +142,7 @@ TEST(Signalfd, Blocking) {\nstruct signalfd_siginfo rbuf;\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n});\n// Wait until blocked.\n@@ -149,20 +155,21 @@ TEST(Signalfd, Blocking) {\n//\n// See gvisor.dev/issue/139.\nif (IsRunningOnGvisor()) {\n- ASSERT_THAT(tgkill(getpid(), gettid(), kSigno), SyscallSucceeds());\n+ ASSERT_THAT(tgkill(getpid(), gettid(), signo), SyscallSucceeds());\n} else {\n- ASSERT_THAT(tgkill(getpid(), tid, kSigno), SyscallSucceeds());\n+ ASSERT_THAT(tgkill(getpid(), tid, signo), SyscallSucceeds());\n}\n// Ensure that it was received.\nt.Join();\n}\n-TEST(Signalfd, ThreadGroup) {\n+TEST_P(SignalfdTest, ThreadGroup) {\n+ int signo = GetParam();\n// Create the signalfd in blocking mode.\nsigset_t mask;\nsigemptyset(&mask);\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nFileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, 0));\n// Shared variable.\n@@ -176,7 +183,7 @@ TEST(Signalfd, ThreadGroup) {\nstruct signalfd_siginfo rbuf;\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n// Wait for the other thread.\nabsl::MutexLock ml(&mu);\n@@ -185,7 +192,7 @@ TEST(Signalfd, ThreadGroup) {\n});\n// Deliver the signal to the threadgroup.\n- ASSERT_THAT(kill(getpid(), kSigno), SyscallSucceeds());\n+ ASSERT_THAT(kill(getpid(), signo), SyscallSucceeds());\n// Wait for the first thread to process.\n{\n@@ -194,13 +201,13 @@ TEST(Signalfd, ThreadGroup) {\n}\n// Deliver to the thread group again (other thread still exists).\n- ASSERT_THAT(kill(getpid(), kSigno), SyscallSucceeds());\n+ ASSERT_THAT(kill(getpid(), signo), SyscallSucceeds());\n// Ensure that we can also receive it.\nstruct signalfd_siginfo rbuf;\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n// Mark the test as done.\n{\n@@ -212,11 +219,12 @@ TEST(Signalfd, ThreadGroup) {\nt.Join();\n}\n-TEST(Signalfd, Nonblock) {\n+TEST_P(SignalfdTest, Nonblock) {\n+ int signo = GetParam();\n// Create the signalfd in non-blocking mode.\nsigset_t mask;\nsigemptyset(&mask);\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nFileDescriptor fd =\nASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, SFD_NONBLOCK));\n@@ -227,20 +235,21 @@ TEST(Signalfd, Nonblock) {\n// Block and deliver the signal.\nconst auto scoped_sigmask =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSigno));\n- ASSERT_THAT(tgkill(getpid(), gettid(), kSigno), SyscallSucceeds());\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, signo));\n+ ASSERT_THAT(tgkill(getpid(), gettid(), signo), SyscallSucceeds());\n// Ensure that a read actually works.\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n// Should block again.\nEXPECT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallFailsWithErrno(EWOULDBLOCK));\n}\n-TEST(Signalfd, SetMask) {\n+TEST_P(SignalfdTest, SetMask) {\n+ int signo = GetParam();\n// Create the signalfd matching nothing.\nsigset_t mask;\nsigemptyset(&mask);\n@@ -249,8 +258,8 @@ TEST(Signalfd, SetMask) {\n// Block and deliver a signal.\nconst auto scoped_sigmask =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSigno));\n- ASSERT_THAT(tgkill(getpid(), gettid(), kSigno), SyscallSucceeds());\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, signo));\n+ ASSERT_THAT(tgkill(getpid(), gettid(), signo), SyscallSucceeds());\n// We should have nothing.\nstruct signalfd_siginfo rbuf;\n@@ -258,29 +267,30 @@ TEST(Signalfd, SetMask) {\nSyscallFailsWithErrno(EWOULDBLOCK));\n// Change the signal mask.\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nASSERT_THAT(signalfd(fd.get(), &mask, 0), SyscallSucceeds());\n// We should now have the signal.\nASSERT_THAT(read(fd.get(), &rbuf, sizeof(rbuf)),\nSyscallSucceedsWithValue(sizeof(rbuf)));\n- EXPECT_EQ(rbuf.ssi_signo, kSigno);\n+ EXPECT_EQ(rbuf.ssi_signo, signo);\n}\n-TEST(Signalfd, Poll) {\n+TEST_P(SignalfdTest, Poll) {\n+ int signo = GetParam();\n// Create the signalfd.\nsigset_t mask;\nsigemptyset(&mask);\n- sigaddset(&mask, kSigno);\n+ sigaddset(&mask, signo);\nFileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, 0));\n// Block the signal, and start a thread to deliver it.\nconst auto scoped_sigmask =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, kSigno));\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, signo));\npid_t orig_tid = gettid();\nScopedThread t([&] {\nabsl::SleepFor(absl::Seconds(5));\n- ASSERT_THAT(tgkill(getpid(), orig_tid, kSigno), SyscallSucceeds());\n+ ASSERT_THAT(tgkill(getpid(), orig_tid, signo), SyscallSucceeds());\n});\n// Start polling for the signal. We expect that it is not available at the\n@@ -297,19 +307,18 @@ TEST(Signalfd, Poll) {\nSyscallSucceedsWithValue(sizeof(rbuf)));\n}\n-TEST(Signalfd, KillStillKills) {\n- sigset_t mask;\n- sigemptyset(&mask);\n- sigaddset(&mask, SIGKILL);\n- FileDescriptor fd =\n- ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, SFD_CLOEXEC));\n-\n- // Just because there is a signalfd, we shouldn't see any change in behavior\n- // for unblockable signals. It's easier to test this with SIGKILL.\n- const auto scoped_sigmask =\n- ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, SIGKILL));\n- EXPECT_EXIT(tgkill(getpid(), gettid(), SIGKILL), KilledBySignal(SIGKILL), \"\");\n+std::string PrintSigno(::testing::TestParamInfo<int> info) {\n+ switch (info.param) {\n+ case kSigno:\n+ return \"kSigno\";\n+ case kSignoMax:\n+ return \"kSignoMax\";\n+ default:\n+ return absl::StrCat(info.param);\n+ }\n}\n+INSTANTIATE_TEST_SUITE_P(Signalfd, SignalfdTest,\n+ ::testing::Values(kSigno, kSignoMax), PrintSigno);\nTEST(Signalfd, Ppoll) {\nsigset_t mask;\n@@ -328,6 +337,20 @@ TEST(Signalfd, Ppoll) {\nSyscallSucceedsWithValue(0));\n}\n+TEST(Signalfd, KillStillKills) {\n+ sigset_t mask;\n+ sigemptyset(&mask);\n+ sigaddset(&mask, SIGKILL);\n+ FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(NewSignalFD(&mask, SFD_CLOEXEC));\n+\n+ // Just because there is a signalfd, we shouldn't see any change in behavior\n+ // for unblockable signals. It's easier to test this with SIGKILL.\n+ const auto scoped_sigmask =\n+ ASSERT_NO_ERRNO_AND_VALUE(ScopedSignalMask(SIG_BLOCK, SIGKILL));\n+ EXPECT_EXIT(tgkill(getpid(), gettid(), SIGKILL), KilledBySignal(SIGKILL), \"\");\n+}\n+\n} // namespace\n} // namespace testing\n@@ -340,6 +363,7 @@ int main(int argc, char** argv) {\nsigset_t set;\nsigemptyset(&set);\nsigaddset(&set, gvisor::testing::kSigno);\n+ sigaddset(&set, gvisor::testing::kSignoMax);\nsigaddset(&set, gvisor::testing::kSignoAlt);\nTEST_PCHECK(sigprocmask(SIG_BLOCK, &set, nullptr) == 0);\n" } ]
Go
Apache License 2.0
google/gvisor
Convert EventMask to uint64 It is used for signalfd where the maximum signal is 64. PiperOrigin-RevId: 290331008
259,972
17.01.2020 18:24:39
28,800
47d85257d3d015f0b9f7739c81af0ee9f510aaf5
Filter out received packets with a local source IP address. CERT Advisory CA-96.21 III. Solution advises that devices drop packets which could not have correctly arrived on the wire, such as receiving a packet where the source IP address is owned by the device that sent it. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -139,7 +139,8 @@ var Metrics = tcpip.Stats{\n},\nIP: tcpip.IPStats{\nPacketsReceived: mustCreateMetric(\"/netstack/ip/packets_received\", \"Total number of IP packets received from the link layer in nic.DeliverNetworkPacket.\"),\n- InvalidAddressesReceived: mustCreateMetric(\"/netstack/ip/invalid_addresses_received\", \"Total number of IP packets received with an unknown or invalid destination address.\"),\n+ InvalidDestinationAddressesReceived: mustCreateMetric(\"/netstack/ip/invalid_addresses_received\", \"Total number of IP packets received with an unknown or invalid destination address.\"),\n+ InvalidSourceAddressesReceived: mustCreateMetric(\"/netstack/ip/invalid_source_addresses_received\", \"Total number of IP packets received with an unknown or invalid source address.\"),\nPacketsDelivered: mustCreateMetric(\"/netstack/ip/packets_delivered\", \"Total number of incoming IP packets that are successfully delivered to the transport layer via HandlePacket.\"),\nPacketsSent: mustCreateMetric(\"/netstack/ip/packets_sent\", \"Total number of IP packets sent via WritePacket.\"),\nOutgoingPacketErrors: mustCreateMetric(\"/netstack/ip/outgoing_packet_errors\", \"Total number of IP packets which failed to write to a link-layer endpoint.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/stack.go", "new_path": "pkg/sentry/socket/netstack/stack.go", "diff": "@@ -152,7 +152,7 @@ func (s *Stack) Statistics(stat interface{}, arg string) error {\n0, // TODO(gvisor.dev/issue/969): Support Ip/DefaultTTL.\nip.PacketsReceived.Value(), // InReceives.\n0, // TODO(gvisor.dev/issue/969): Support Ip/InHdrErrors.\n- ip.InvalidAddressesReceived.Value(), // InAddrErrors.\n+ ip.InvalidDestinationAddressesReceived.Value(), // InAddrErrors.\n0, // TODO(gvisor.dev/issue/969): Support Ip/ForwDatagrams.\n0, // TODO(gvisor.dev/issue/969): Support Ip/InUnknownProtos.\n0, // TODO(gvisor.dev/issue/969): Support Ip/InDiscards.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -984,7 +984,7 @@ func handlePacket(protocol tcpip.NetworkProtocolNumber, dst, src tcpip.Address,\n// DeliverNetworkPacket finds the appropriate network protocol endpoint and\n// hands the packet over for further processing. This function is called when\n-// the NIC receives a packet from the physical interface.\n+// the NIC receives a packet from the link endpoint.\n// Note that the ownership of the slice backing vv is retained by the caller.\n// This rule applies only to the slice itself, not to the items of the slice;\n// the ownership of the items is not retained by the caller.\n@@ -1029,6 +1029,14 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\nsrc, dst := netProto.ParseAddresses(pkt.Data.First())\n+ if n.stack.handleLocal && !n.isLoopback() && n.getRef(protocol, src) != nil {\n+ // The source address is one of our own, so we never should have gotten a\n+ // packet like this unless handleLocal is false. Loopback also calls this\n+ // function even though the packets didn't come from the physical interface\n+ // so don't drop those.\n+ n.stack.stats.IP.InvalidSourceAddressesReceived.Increment()\n+ return\n+ }\nif ref := n.getRef(protocol, dst); ref != nil {\nhandlePacket(protocol, dst, src, linkEP.LinkAddress(), remote, ref, pkt)\nreturn\n@@ -1041,7 +1049,7 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\nif n.stack.Forwarding() {\nr, err := n.stack.FindRoute(0, \"\", dst, protocol, false /* multicastLoop */)\nif err != nil {\n- n.stack.stats.IP.InvalidAddressesReceived.Increment()\n+ n.stack.stats.IP.InvalidDestinationAddressesReceived.Increment()\nreturn\n}\ndefer r.Release()\n@@ -1079,7 +1087,7 @@ func (n *NIC) DeliverNetworkPacket(linkEP LinkEndpoint, remote, local tcpip.Link\n// If a packet socket handled the packet, don't treat it as invalid.\nif len(packetEPs) == 0 {\n- n.stack.stats.IP.InvalidAddressesReceived.Increment()\n+ n.stack.stats.IP.InvalidDestinationAddressesReceived.Increment()\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -903,9 +903,13 @@ type IPStats struct {\n// link layer in nic.DeliverNetworkPacket.\nPacketsReceived *StatCounter\n- // InvalidAddressesReceived is the total number of IP packets received\n- // with an unknown or invalid destination address.\n- InvalidAddressesReceived *StatCounter\n+ // InvalidDestinationAddressesReceived is the total number of IP packets\n+ // received with an unknown or invalid destination address.\n+ InvalidDestinationAddressesReceived *StatCounter\n+\n+ // InvalidSourceAddressesReceived is the total number of IP packets received\n+ // with a source address that should never have been received on the wire.\n+ InvalidSourceAddressesReceived *StatCounter\n// PacketsDelivered is the total number of incoming IP packets that\n// are successfully delivered to the transport layer via HandlePacket.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/udp/udp_test.go", "new_path": "pkg/tcpip/transport/udp/udp_test.go", "diff": "@@ -274,11 +274,16 @@ type testContext struct {\nfunc newDualTestContext(t *testing.T, mtu uint32) *testContext {\nt.Helper()\n-\n- s := stack.New(stack.Options{\n+ return newDualTestContextWithOptions(t, mtu, stack.Options{\nNetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\nTransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n})\n+}\n+\n+func newDualTestContextWithOptions(t *testing.T, mtu uint32, options stack.Options) *testContext {\n+ t.Helper()\n+\n+ s := stack.New(options)\nep := channel.New(256, mtu, \"\")\nwep := stack.LinkEndpoint(ep)\n@@ -763,6 +768,49 @@ func TestV6ReadOnV6(t *testing.T) {\ntestRead(c, unicastV6)\n}\n+// TestV4ReadSelfSource checks that packets coming from a local IP address are\n+// correctly dropped when handleLocal is true and not otherwise.\n+func TestV4ReadSelfSource(t *testing.T) {\n+ for _, tt := range []struct {\n+ name string\n+ handleLocal bool\n+ wantErr *tcpip.Error\n+ wantInvalidSource uint64\n+ }{\n+ {\"HandleLocal\", false, nil, 0},\n+ {\"NoHandleLocal\", true, tcpip.ErrWouldBlock, 1},\n+ } {\n+ t.Run(tt.name, func(t *testing.T) {\n+ c := newDualTestContextWithOptions(t, defaultMTU, stack.Options{\n+ NetworkProtocols: []stack.NetworkProtocol{ipv4.NewProtocol(), ipv6.NewProtocol()},\n+ TransportProtocols: []stack.TransportProtocol{udp.NewProtocol()},\n+ HandleLocal: tt.handleLocal,\n+ })\n+ defer c.cleanup()\n+\n+ c.createEndpointForFlow(unicastV4)\n+\n+ if err := c.ep.Bind(tcpip.FullAddress{Port: stackPort}); err != nil {\n+ t.Fatalf(\"Bind failed: %s\", err)\n+ }\n+\n+ payload := newPayload()\n+ h := unicastV4.header4Tuple(incoming)\n+ h.srcAddr = h.dstAddr\n+\n+ c.injectV4Packet(payload, &h, true /* valid */)\n+\n+ if got := c.s.Stats().IP.InvalidSourceAddressesReceived.Value(); got != tt.wantInvalidSource {\n+ t.Errorf(\"c.s.Stats().IP.InvalidSourceAddressesReceived got %d, want %d\", got, tt.wantInvalidSource)\n+ }\n+\n+ if _, _, err := c.ep.Read(nil); err != tt.wantErr {\n+ t.Errorf(\"c.ep.Read() got error %v, want %v\", err, tt.wantErr)\n+ }\n+ })\n+ }\n+}\n+\nfunc TestV4ReadOnV4(t *testing.T) {\nc := newDualTestContext(t, defaultMTU)\ndefer c.cleanup()\n" } ]
Go
Apache License 2.0
google/gvisor
Filter out received packets with a local source IP address. CERT Advisory CA-96.21 III. Solution advises that devices drop packets which could not have correctly arrived on the wire, such as receiving a packet where the source IP address is owned by the device that sent it. Fixes #1507 PiperOrigin-RevId: 290378240
259,974
20.12.2019 06:00:30
0
c0e39a8271198f10407009ec1994e5d9efac796c
Enable uname syscall support on arm64.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_utsname.go", "new_path": "pkg/sentry/syscalls/linux/sys_utsname.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-// +build amd64\n+// +build amd64 arm64\npackage linux\n@@ -35,7 +35,15 @@ func Uname(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Syscall\ncopy(u.Nodename[:], uts.HostName())\ncopy(u.Release[:], version.Release)\ncopy(u.Version[:], version.Version)\n- copy(u.Machine[:], \"x86_64\") // build tag above.\n+ // build tag above.\n+ switch t.SyscallTable().Arch {\n+ case arch.AMD64:\n+ copy(u.Machine[:], \"x86_64\")\n+ case arch.ARM64:\n+ copy(u.Machine[:], \"aarch64\")\n+ default:\n+ copy(u.Machine[:], \"unknown\")\n+ }\ncopy(u.Domainname[:], uts.DomainName())\n// Copy out the result.\n" } ]
Go
Apache License 2.0
google/gvisor
Enable uname syscall support on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I206f38416a64d7c6a8531d8eb305c6ea239616b8
259,860
21.01.2020 12:41:50
28,800
2ba6198851dc1e293295d7cadf8c0ae456b68beb
Add syscalls for lgetxattr, fgetxattr, lsetxattr, and fsetxattr. Note that these simply will use the same logic as getxattr and setxattr, which is not yet implemented for most filesystems.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64_amd64.go", "new_path": "pkg/sentry/syscalls/linux/linux64_amd64.go", "diff": "@@ -229,11 +229,11 @@ var AMD64 = &kernel.SyscallTable{\n186: syscalls.Supported(\"gettid\", Gettid),\n187: syscalls.Supported(\"readahead\", Readahead),\n188: syscalls.PartiallySupported(\"setxattr\", SetXattr, \"Only supported for tmpfs.\", nil),\n- 189: syscalls.Error(\"lsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n- 190: syscalls.Error(\"fsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n+ 189: syscalls.PartiallySupported(\"lsetxattr\", LSetXattr, \"Only supported for tmpfs.\", nil),\n+ 190: syscalls.PartiallySupported(\"fsetxattr\", FSetXattr, \"Only supported for tmpfs.\", nil),\n191: syscalls.PartiallySupported(\"getxattr\", GetXattr, \"Only supported for tmpfs.\", nil),\n- 192: syscalls.ErrorWithEvent(\"lgetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n- 193: syscalls.ErrorWithEvent(\"fgetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n+ 192: syscalls.PartiallySupported(\"lgetxattr\", LGetXattr, \"Only supported for tmpfs.\", nil),\n+ 193: syscalls.PartiallySupported(\"fgetxattr\", FGetXattr, \"Only supported for tmpfs.\", nil),\n194: syscalls.ErrorWithEvent(\"listxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n195: syscalls.ErrorWithEvent(\"llistxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n196: syscalls.ErrorWithEvent(\"flistxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/linux64_arm64.go", "new_path": "pkg/sentry/syscalls/linux/linux64_arm64.go", "diff": "@@ -42,11 +42,11 @@ var ARM64 = &kernel.SyscallTable{\n3: syscalls.PartiallySupported(\"io_cancel\", IoCancel, \"Generally supported with exceptions. User ring optimizations are not implemented.\", []string{\"gvisor.dev/issue/204\"}),\n4: syscalls.PartiallySupported(\"io_getevents\", IoGetevents, \"Generally supported with exceptions. User ring optimizations are not implemented.\", []string{\"gvisor.dev/issue/204\"}),\n5: syscalls.PartiallySupported(\"setxattr\", SetXattr, \"Only supported for tmpfs.\", nil),\n- 6: syscalls.Error(\"lsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n- 7: syscalls.Error(\"fsetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n+ 6: syscalls.PartiallySupported(\"lsetxattr\", LSetXattr, \"Only supported for tmpfs.\", nil),\n+ 7: syscalls.PartiallySupported(\"fsetxattr\", FSetXattr, \"Only supported for tmpfs.\", nil),\n8: syscalls.PartiallySupported(\"getxattr\", GetXattr, \"Only supported for tmpfs.\", nil),\n- 9: syscalls.ErrorWithEvent(\"lgetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n- 10: syscalls.ErrorWithEvent(\"fgetxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n+ 9: syscalls.PartiallySupported(\"lgetxattr\", LGetXattr, \"Only supported for tmpfs.\", nil),\n+ 10: syscalls.PartiallySupported(\"fgetxattr\", FGetXattr, \"Only supported for tmpfs.\", nil),\n11: syscalls.ErrorWithEvent(\"listxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n12: syscalls.ErrorWithEvent(\"llistxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n13: syscalls.ErrorWithEvent(\"flistxattr\", syserror.ENOTSUP, \"Requires filesystem support.\", nil),\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "new_path": "pkg/sentry/syscalls/linux/sys_xattr.go", "diff": "@@ -27,6 +27,40 @@ import (\n// GetXattr implements linux syscall getxattr(2).\nfunc GetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return getXattrFromPath(t, args, true)\n+}\n+\n+// LGetXattr implements linux syscall lgetxattr(2).\n+func LGetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return getXattrFromPath(t, args, false)\n+}\n+\n+// FGetXattr implements linux syscall fgetxattr(2).\n+func FGetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ fd := args[0].Int()\n+ nameAddr := args[1].Pointer()\n+ valueAddr := args[2].Pointer()\n+ size := uint64(args[3].SizeT())\n+\n+ // TODO(b/113957122): Return EBADF if the fd was opened with O_PATH.\n+ f := t.GetFile(fd)\n+ if f == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer f.DecRef()\n+\n+ n, value, err := getXattr(t, f.Dirent, nameAddr, size)\n+ if err != nil {\n+ return 0, nil, err\n+ }\n+\n+ if _, err := t.CopyOutBytes(valueAddr, []byte(value)); err != nil {\n+ return 0, nil, err\n+ }\n+ return uintptr(n), nil, nil\n+}\n+\n+func getXattrFromPath(t *kernel.Task, args arch.SyscallArguments, resolveSymlink bool) (uintptr, *kernel.SyscallControl, error) {\npathAddr := args[0].Pointer()\nnameAddr := args[1].Pointer()\nvalueAddr := args[2].Pointer()\n@@ -38,29 +72,17 @@ func GetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\nvalueLen := 0\n- err = fileOpOn(t, linux.AT_FDCWD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent, _ uint) error {\n- // If getxattr(2) is called with size 0, the size of the value will be\n- // returned successfully even if it is nonzero. In that case, we need to\n- // retrieve the entire attribute value so we can return the correct size.\n- requestedSize := size\n- if size == 0 || size > linux.XATTR_SIZE_MAX {\n- requestedSize = linux.XATTR_SIZE_MAX\n+ err = fileOpOn(t, linux.AT_FDCWD, path, resolveSymlink, func(root *fs.Dirent, d *fs.Dirent, _ uint) error {\n+ if dirPath && !fs.IsDir(d.Inode.StableAttr) {\n+ return syserror.ENOTDIR\n}\n- value, err := getXattr(t, d, dirPath, nameAddr, uint64(requestedSize))\n+ n, value, err := getXattr(t, d, nameAddr, size)\n+ valueLen = n\nif err != nil {\nreturn err\n}\n- valueLen = len(value)\n- if uint64(valueLen) > requestedSize {\n- return syserror.ERANGE\n- }\n-\n- // Skip copying out the attribute value if size is 0.\n- if size == 0 {\n- return nil\n- }\n_, err = t.CopyOutBytes(valueAddr, []byte(value))\nreturn err\n})\n@@ -71,29 +93,73 @@ func GetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\n}\n// getXattr implements getxattr(2) from the given *fs.Dirent.\n-func getXattr(t *kernel.Task, d *fs.Dirent, dirPath bool, nameAddr usermem.Addr, size uint64) (string, error) {\n- if dirPath && !fs.IsDir(d.Inode.StableAttr) {\n- return \"\", syserror.ENOTDIR\n- }\n-\n+func getXattr(t *kernel.Task, d *fs.Dirent, nameAddr usermem.Addr, size uint64) (int, string, error) {\nif err := checkXattrPermissions(t, d.Inode, fs.PermMask{Read: true}); err != nil {\n- return \"\", err\n+ return 0, \"\", err\n}\nname, err := copyInXattrName(t, nameAddr)\nif err != nil {\n- return \"\", err\n+ return 0, \"\", err\n}\nif !strings.HasPrefix(name, linux.XATTR_USER_PREFIX) {\n- return \"\", syserror.EOPNOTSUPP\n+ return 0, \"\", syserror.EOPNOTSUPP\n}\n- return d.Inode.GetXattr(t, name, size)\n+ // If getxattr(2) is called with size 0, the size of the value will be\n+ // returned successfully even if it is nonzero. In that case, we need to\n+ // retrieve the entire attribute value so we can return the correct size.\n+ requestedSize := size\n+ if size == 0 || size > linux.XATTR_SIZE_MAX {\n+ requestedSize = linux.XATTR_SIZE_MAX\n+ }\n+\n+ value, err := d.Inode.GetXattr(t, name, requestedSize)\n+ if err != nil {\n+ return 0, \"\", err\n+ }\n+ n := len(value)\n+ if uint64(n) > requestedSize {\n+ return 0, \"\", syserror.ERANGE\n+ }\n+\n+ // Don't copy out the attribute value if size is 0.\n+ if size == 0 {\n+ return n, \"\", nil\n+ }\n+ return n, value, nil\n}\n// SetXattr implements linux syscall setxattr(2).\nfunc SetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return setXattrFromPath(t, args, true)\n+}\n+\n+// LSetXattr implements linux syscall lsetxattr(2).\n+func LSetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ return setXattrFromPath(t, args, false)\n+}\n+\n+// FSetXattr implements linux syscall fsetxattr(2).\n+func FSetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n+ fd := args[0].Int()\n+ nameAddr := args[1].Pointer()\n+ valueAddr := args[2].Pointer()\n+ size := uint64(args[3].SizeT())\n+ flags := args[4].Uint()\n+\n+ // TODO(b/113957122): Return EBADF if the fd was opened with O_PATH.\n+ f := t.GetFile(fd)\n+ if f == nil {\n+ return 0, nil, syserror.EBADF\n+ }\n+ defer f.DecRef()\n+\n+ return 0, nil, setXattr(t, f.Dirent, nameAddr, valueAddr, uint64(size), flags)\n+}\n+\n+func setXattrFromPath(t *kernel.Task, args arch.SyscallArguments, resolveSymlink bool) (uintptr, *kernel.SyscallControl, error) {\npathAddr := args[0].Pointer()\nnameAddr := args[1].Pointer()\nvalueAddr := args[2].Pointer()\n@@ -105,19 +171,19 @@ func SetXattr(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.Sysc\nreturn 0, nil, err\n}\n- if flags&^(linux.XATTR_CREATE|linux.XATTR_REPLACE) != 0 {\n- return 0, nil, syserror.EINVAL\n+ return 0, nil, fileOpOn(t, linux.AT_FDCWD, path, resolveSymlink, func(root *fs.Dirent, d *fs.Dirent, _ uint) error {\n+ if dirPath && !fs.IsDir(d.Inode.StableAttr) {\n+ return syserror.ENOTDIR\n}\n- return 0, nil, fileOpOn(t, linux.AT_FDCWD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent, _ uint) error {\n- return setXattr(t, d, dirPath, nameAddr, valueAddr, uint64(size), flags)\n+ return setXattr(t, d, nameAddr, valueAddr, uint64(size), flags)\n})\n}\n// setXattr implements setxattr(2) from the given *fs.Dirent.\n-func setXattr(t *kernel.Task, d *fs.Dirent, dirPath bool, nameAddr, valueAddr usermem.Addr, size uint64, flags uint32) error {\n- if dirPath && !fs.IsDir(d.Inode.StableAttr) {\n- return syserror.ENOTDIR\n+func setXattr(t *kernel.Task, d *fs.Dirent, nameAddr, valueAddr usermem.Addr, size uint64, flags uint32) error {\n+ if flags&^(linux.XATTR_CREATE|linux.XATTR_REPLACE) != 0 {\n+ return syserror.EINVAL\n}\nif err := checkXattrPermissions(t, d.Inode, fs.PermMask{Write: true}); err != nil {\n@@ -133,7 +199,7 @@ func setXattr(t *kernel.Task, d *fs.Dirent, dirPath bool, nameAddr, valueAddr us\nreturn syserror.E2BIG\n}\nbuf := make([]byte, size)\n- if _, err = t.CopyInBytes(valueAddr, buf); err != nil {\n+ if _, err := t.CopyInBytes(valueAddr, buf); err != nil {\nreturn err\n}\nvalue := string(buf)\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/xattr.cc", "new_path": "test/syscalls/linux/xattr.cc", "diff": "#include \"gtest/gtest.h\"\n#include \"test/syscalls/linux/file_base.h\"\n#include \"test/util/capability_util.h\"\n+#include \"test/util/file_descriptor.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -414,6 +415,46 @@ TEST_F(XattrTest, GetxattrNonexistentName) {\nEXPECT_THAT(getxattr(path, name, nullptr, 0), SyscallFailsWithErrno(ENODATA));\n}\n+TEST_F(XattrTest, LGetSetxattrOnSymlink) {\n+ TempPath dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n+ TempPath link = ASSERT_NO_ERRNO_AND_VALUE(\n+ TempPath::CreateSymlinkTo(dir.path(), test_file_name_));\n+\n+ EXPECT_THAT(lsetxattr(link.path().c_str(), nullptr, nullptr, 0, 0),\n+ SyscallFailsWithErrno(EPERM));\n+ EXPECT_THAT(lgetxattr(link.path().c_str(), nullptr, nullptr, 0),\n+ SyscallFailsWithErrno(ENODATA));\n+}\n+\n+TEST_F(XattrTest, LGetSetxattrOnNonsymlink) {\n+ const char* path = test_file_name_.c_str();\n+ const char name[] = \"user.test\";\n+ int val = 1234;\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(lsetxattr(path, name, &val, size, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ int buf = 0;\n+ EXPECT_THAT(lgetxattr(path, name, &buf, size),\n+ SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, val);\n+}\n+\n+TEST_F(XattrTest, FGetSetxattr) {\n+ const FileDescriptor fd =\n+ ASSERT_NO_ERRNO_AND_VALUE(Open(test_file_name_.c_str(), 0));\n+ const char name[] = \"user.test\";\n+ int val = 1234;\n+ size_t size = sizeof(val);\n+ EXPECT_THAT(fsetxattr(fd.get(), name, &val, size, /*flags=*/0),\n+ SyscallSucceeds());\n+\n+ int buf = 0;\n+ EXPECT_THAT(fgetxattr(fd.get(), name, &buf, size),\n+ SyscallSucceedsWithValue(size));\n+ EXPECT_EQ(buf, val);\n+}\n+\n} // namespace\n} // namespace testing\n" } ]
Go
Apache License 2.0
google/gvisor
Add syscalls for lgetxattr, fgetxattr, lsetxattr, and fsetxattr. Note that these simply will use the same logic as getxattr and setxattr, which is not yet implemented for most filesystems. PiperOrigin-RevId: 290800960
259,992
21.01.2020 13:26:50
28,800
d46c397a1cd38f1e2aa5c864c1bb8594fb87bb63
Add line break to /proc/net files Some files were missing the last line break.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/proc/net.go", "new_path": "pkg/sentry/fs/proc/net.go", "diff": "@@ -52,17 +52,17 @@ func (p *proc) newNetDir(ctx context.Context, k *kernel.Kernel, msrc *fs.MountSo\n// implemented in netstack, if the file contains a\n// header the stub is just the header otherwise it is\n// an empty file.\n- \"arp\": newStaticProcInode(ctx, msrc, []byte(\"IP address HW type Flags HW address Mask Device\")),\n+ \"arp\": newStaticProcInode(ctx, msrc, []byte(\"IP address HW type Flags HW address Mask Device\\n\")),\n- \"netlink\": newStaticProcInode(ctx, msrc, []byte(\"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\")),\n- \"netstat\": newStaticProcInode(ctx, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\")),\n- \"packet\": newStaticProcInode(ctx, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\")),\n- \"protocols\": newStaticProcInode(ctx, msrc, []byte(\"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\")),\n+ \"netlink\": newStaticProcInode(ctx, msrc, []byte(\"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\\n\")),\n+ \"netstat\": newStaticProcInode(ctx, msrc, []byte(\"TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed EmbryonicRsts PruneCalled RcvPruned OfoPruned OutOfWindowIcmps LockDroppedIcmps ArpFilter TW TWRecycled TWKilled PAWSPassive PAWSActive PAWSEstab DelayedACKs DelayedACKLocked DelayedACKLost ListenOverflows ListenDrops TCPPrequeued TCPDirectCopyFromBacklog TCPDirectCopyFromPrequeue TCPPrequeueDropped TCPHPHits TCPHPHitsToUser TCPPureAcks TCPHPAcks TCPRenoRecovery TCPSackRecovery TCPSACKReneging TCPFACKReorder TCPSACKReorder TCPRenoReorder TCPTSReorder TCPFullUndo TCPPartialUndo TCPDSACKUndo TCPLossUndo TCPLostRetransmit TCPRenoFailures TCPSackFailures TCPLossFailures TCPFastRetrans TCPForwardRetrans TCPSlowStartRetrans TCPTimeouts TCPLossProbes TCPLossProbeRecovery TCPRenoRecoveryFail TCPSackRecoveryFail TCPSchedulerFailed TCPRcvCollapsed TCPDSACKOldSent TCPDSACKOfoSent TCPDSACKRecv TCPDSACKOfoRecv TCPAbortOnData TCPAbortOnClose TCPAbortOnMemory TCPAbortOnTimeout TCPAbortOnLinger TCPAbortFailed TCPMemoryPressures TCPSACKDiscard TCPDSACKIgnoredOld TCPDSACKIgnoredNoUndo TCPSpuriousRTOs TCPMD5NotFound TCPMD5Unexpected TCPMD5Failure TCPSackShifted TCPSackMerged TCPSackShiftFallback TCPBacklogDrop TCPMinTTLDrop TCPDeferAcceptDrop IPReversePathFilter TCPTimeWaitOverflow TCPReqQFullDoCookies TCPReqQFullDrop TCPRetransFail TCPRcvCoalesce TCPOFOQueue TCPOFODrop TCPOFOMerge TCPChallengeACK TCPSYNChallenge TCPFastOpenActive TCPFastOpenActiveFail TCPFastOpenPassive TCPFastOpenPassiveFail TCPFastOpenListenOverflow TCPFastOpenCookieReqd TCPSpuriousRtxHostQueues BusyPollRxPackets TCPAutoCorking TCPFromZeroWindowAdv TCPToZeroWindowAdv TCPWantZeroWindowAdv TCPSynRetrans TCPOrigDataSent TCPHystartTrainDetect TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\\n\")),\n+ \"packet\": newStaticProcInode(ctx, msrc, []byte(\"sk RefCnt Type Proto Iface R Rmem User Inode\\n\")),\n+ \"protocols\": newStaticProcInode(ctx, msrc, []byte(\"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\\n\")),\n// Linux sets psched values to: nsec per usec, psched\n// tick in ns, 1000000, high res timer ticks per sec\n// (ClockGetres returns 1ns resolution).\n\"psched\": newStaticProcInode(ctx, msrc, []byte(fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond)))),\n- \"ptype\": newStaticProcInode(ctx, msrc, []byte(\"Type Device Function\")),\n+ \"ptype\": newStaticProcInode(ctx, msrc, []byte(\"Type Device Function\\n\")),\n\"route\": seqfile.NewSeqFileInode(ctx, &netRoute{s: s}, msrc),\n\"tcp\": seqfile.NewSeqFileInode(ctx, &netTCP{k: k}, msrc),\n\"udp\": seqfile.NewSeqFileInode(ctx, &netUDP{k: k}, msrc),\n@@ -73,7 +73,7 @@ func (p *proc) newNetDir(ctx context.Context, k *kernel.Kernel, msrc *fs.MountSo\ncontents[\"if_inet6\"] = seqfile.NewSeqFileInode(ctx, &ifinet6{s: s}, msrc)\ncontents[\"ipv6_route\"] = newStaticProcInode(ctx, msrc, []byte(\"\"))\ncontents[\"tcp6\"] = seqfile.NewSeqFileInode(ctx, &netTCP6{k: k}, msrc)\n- contents[\"udp6\"] = newStaticProcInode(ctx, msrc, []byte(\" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"))\n+ contents[\"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}\nd := ramfs.NewDir(ctx, contents, fs.RootOwner, fs.FilePermsFromMode(0555))\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_net.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_net.go", "diff": "@@ -41,12 +41,12 @@ func newNetDir(root *auth.Credentials, inoGen InoGenerator, k *kernel.Kernel) *k\nvar contents map[string]*kernfs.Dentry\nif stack := k.NetworkStack(); stack != nil {\nconst (\n- arp = \"IP address HW type Flags HW address Mask Device\"\n- netlink = \"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\"\n- packet = \"sk RefCnt Type Proto Iface R Rmem User Inode\"\n- protocols = \"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\"\n- ptype = \"Type Device Function\"\n- upd6 = \" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\"\n+ arp = \"IP address HW type Flags HW address Mask Device\\n\"\n+ netlink = \"sk Eth Pid Groups Rmem Wmem Dump Locks Drops Inode\\n\"\n+ packet = \"sk RefCnt Type Proto Iface R Rmem User Inode\\n\"\n+ protocols = \"protocol size sockets memory press maxhdr slab module cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\\n\"\n+ ptype = \"Type Device Function\\n\"\n+ upd6 = \" sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\\n\"\n)\npsched := fmt.Sprintf(\"%08x %08x %08x %08x\\n\", uint64(time.Microsecond/time.Nanosecond), 64, 1000000, uint64(time.Second/time.Nanosecond))\n@@ -779,6 +779,6 @@ func (d *netStatData) Generate(ctx context.Context, buf *bytes.Buffer) error {\n\"TCPHystartTrainCwnd TCPHystartDelayDetect TCPHystartDelayCwnd \" +\n\"TCPACKSkippedSynRecv TCPACKSkippedPAWS TCPACKSkippedSeq \" +\n\"TCPACKSkippedFinWait2 TCPACKSkippedTimeWait TCPACKSkippedChallenge \" +\n- \"TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\")\n+ \"TCPWinProbe TCPKeepAlive TCPMTUPFail TCPMTUPSuccess\\n\")\nreturn nil\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add line break to /proc/net files Some files were missing the last line break. PiperOrigin-RevId: 290808898
259,928
21.01.2020 14:15:01
28,800
cbc0a92276b75e744511a43a9c0b78fc64946ec6
Correct todos referencing IPV6_RECVTCLASS Bug was revived because TODOs referenced the IP_RECVTOS bug instead of the IPV6_RECVTCLASS bug.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/udp_socket_test_cases.cc", "new_path": "test/syscalls/linux/udp_socket_test_cases.cc", "diff": "@@ -1349,7 +1349,7 @@ TEST_P(UdpSocketTest, TimestampIoctlPersistence) {\n// outgoing packets, and that a receiving socket with IP_RECVTOS or\n// IPV6_RECVTCLASS will create the corresponding control message.\nTEST_P(UdpSocketTest, SetAndReceiveTOS) {\n- // TODO(b/68320120): IPV6_RECVTCLASS not supported for netstack.\n+ // TODO(b/144868438): IPV6_RECVTCLASS not supported for netstack.\nSKIP_IF((GetParam() != AddressFamily::kIpv4) && IsRunningOnGvisor() &&\n!IsRunningWithHostinet());\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n@@ -1422,7 +1422,7 @@ TEST_P(UdpSocketTest, SetAndReceiveTOS) {\n// TOS byte on outgoing packets, and that a receiving socket with IP_RECVTOS or\n// IPV6_RECVTCLASS will create the corresponding control message.\nTEST_P(UdpSocketTest, SendAndReceiveTOS) {\n- // TODO(b/68320120): IPV6_RECVTCLASS not supported for netstack.\n+ // TODO(b/144868438): IPV6_RECVTCLASS not supported for netstack.\n// TODO(b/146661005): Setting TOS via cmsg not supported for netstack.\nSKIP_IF(IsRunningOnGvisor() && !IsRunningWithHostinet());\nASSERT_THAT(bind(s_, addr_[0], addrlen_), SyscallSucceeds());\n" } ]
Go
Apache License 2.0
google/gvisor
Correct todos referencing IPV6_RECVTCLASS Bug 68320120 was revived because TODOs referenced the IP_RECVTOS bug instead of the IPV6_RECVTCLASS bug. PiperOrigin-RevId: 290820178
259,891
21.01.2020 14:47:17
28,800
9143fcd7fd38243dd40f927dafaeb75f6ef8ef49
Add UDP matchers.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -340,3 +340,95 @@ func goString(cstring []byte) string {\n}\nreturn string(cstring)\n}\n+\n+// XTTCP holds data for matching TCP packets. It corresponds to struct xt_tcp\n+// in include/uapi/linux/netfilter/xt_tcpudp.h.\n+type XTTCP struct {\n+ // SourcePortStart specifies the inclusive start of the range of source\n+ // ports to which the matcher applies.\n+ SourcePortStart uint16\n+\n+ // SourcePortEnd specifies the inclusive end of the range of source ports\n+ // to which the matcher applies.\n+ SourcePortEnd uint16\n+\n+ // DestinationPortStart specifies the start of the destination port\n+ // range to which the matcher applies.\n+ DestinationPortStart uint16\n+\n+ // DestinationPortEnd specifies the start of the destination port\n+ // range to which the matcher applies.\n+ DestinationPortEnd uint16\n+\n+ // Option specifies that a particular TCP option must be set.\n+ Option uint8\n+\n+ // FlagMask masks the FlagCompare byte when comparing to the TCP flag\n+ // fields.\n+ FlagMask uint8\n+\n+ // FlagCompare is binary and-ed with the TCP flag fields.\n+ FlagCompare uint8\n+\n+ // InverseFlags flips the meaning of certain fields. See the\n+ // TX_TCP_INV_* flags.\n+ InverseFlags uint8\n+}\n+\n+// SizeOfXTTCP is the size of an XTTCP.\n+const SizeOfXTTCP = 12\n+\n+// Flags in XTTCP.InverseFlags. Corresponding constants are in\n+// include/uapi/linux/netfilter/xt_tcpudp.h.\n+const (\n+ // Invert the meaning of SourcePortStart/End.\n+ XT_TCP_INV_SRCPT = 0x01\n+ // Invert the meaning of DestinationPortStart/End.\n+ XT_TCP_INV_DSTPT = 0x02\n+ // Invert the meaning of FlagCompare.\n+ XT_TCP_INV_FLAGS = 0x04\n+ // Invert the meaning of Option.\n+ XT_TCP_INV_OPTION = 0x08\n+ // Enable all flags.\n+ XT_TCP_INV_MASK = 0x0F\n+)\n+\n+// XTUDP holds data for matching UDP packets. It corresponds to struct xt_udp\n+// in include/uapi/linux/netfilter/xt_tcpudp.h.\n+type XTUDP struct {\n+ // SourcePortStart specifies the inclusive start of the range of source\n+ // ports to which the matcher applies.\n+ SourcePortStart uint16\n+\n+ // SourcePortEnd specifies the inclusive end of the range of source ports\n+ // to which the matcher applies.\n+ SourcePortEnd uint16\n+\n+ // DestinationPortStart specifies the start of the destination port\n+ // range to which the matcher applies.\n+ DestinationPortStart uint16\n+\n+ // DestinationPortEnd specifies the start of the destination port\n+ // range to which the matcher applies.\n+ DestinationPortEnd uint16\n+\n+ // InverseFlags flips the meaning of certain fields. See the\n+ // TX_UDP_INV_* flags.\n+ InverseFlags uint8\n+\n+ _ uint8\n+}\n+\n+// SizeOfXTUDP is the size of an XTUDP.\n+const SizeOfXTUDP = 10\n+\n+// Flags in XTUDP.InverseFlags. Corresponding constants are in\n+// include/uapi/linux/netfilter/xt_tcpudp.h.\n+const (\n+ // Invert the meaning of SourcePortStart/End.\n+ XT_UDP_INV_SRCPT = 0x01\n+ // Invert the meaning of DestinationPortStart/End.\n+ XT_UDP_INV_DSTPT = 0x02\n+ // Enable all flags.\n+ XT_UDP_INV_MASK = 0x03\n+)\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -131,6 +131,7 @@ func FillDefaultIPTables(stack *stack.Stack) {\nstack.SetIPTables(ipt)\n}\n+// TODO: Return proto.\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@@ -318,10 +319,12 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n}\nvar entry linux.IPTEntry\nbuf := optVal[:linux.SizeOfIPTEntry]\n- optVal = optVal[linux.SizeOfIPTEntry:]\nbinary.Unmarshal(buf, usermem.ByteOrder, &entry)\n- if entry.TargetOffset != linux.SizeOfIPTEntry {\n- // TODO(gvisor.dev/issue/170): Support matchers.\n+ initialOptValLen := len(optVal)\n+ optVal = optVal[linux.SizeOfIPTEntry:]\n+\n+ if entry.TargetOffset < linux.SizeOfIPTEntry {\n+ log.Warningf(\"netfilter: entry has too-small target offset %d\", entry.TargetOffset)\nreturn syserr.ErrInvalidArgument\n}\n@@ -332,19 +335,41 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nreturn err\n}\n+ // TODO: Matchers (and maybe targets) can specify that they only work for certiain protocols, hooks, tables.\n+ // Get matchers.\n+ matchersSize := entry.TargetOffset - linux.SizeOfIPTEntry\n+ if len(optVal) < int(matchersSize) {\n+ log.Warningf(\"netfilter: entry doesn't have enough room for its matchers (only %d bytes remain)\", len(optVal))\n+ }\n+ matchers, err := parseMatchers(filter, optVal[:matchersSize])\n+ if err != nil {\n+ log.Warningf(\"netfilter: failed to parse matchers: %v\", err)\n+ return err\n+ }\n+ optVal = optVal[matchersSize:]\n+\n// Get the target of the rule.\n- target, consumed, err := parseTarget(optVal)\n+ targetSize := entry.NextOffset - entry.TargetOffset\n+ if len(optVal) < int(targetSize) {\n+ log.Warningf(\"netfilter: entry doesn't have enough room for its target (only %d bytes remain)\", len(optVal))\n+ }\n+ target, err := parseTarget(optVal[:targetSize])\nif err != nil {\nreturn err\n}\n- optVal = optVal[consumed:]\n+ optVal = optVal[targetSize:]\ntable.Rules = append(table.Rules, iptables.Rule{\nFilter: filter,\nTarget: target,\n+ Matchers: matchers,\n})\noffsets = append(offsets, offset)\n- offset += linux.SizeOfIPTEntry + consumed\n+ offset += uint32(entry.NextOffset)\n+\n+ if initialOptValLen-len(optVal) != int(entry.NextOffset) {\n+ log.Warningf(\"netfilter: entry NextOffset is %d, but entry took up %d bytes\", entry.NextOffset, initialOptValLen-len(optVal))\n+ }\n}\n// Go through the list of supported hooks for this table and, for each\n@@ -401,12 +426,105 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nreturn nil\n}\n-// parseTarget parses a target from the start of optVal and returns the target\n-// along with the number of bytes it occupies in optVal.\n-func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\n+// parseMatchers parses 0 or more matchers from optVal. optVal should contain\n+// only the matchers.\n+func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Matcher, *syserr.Error) {\n+ var matchers []iptables.Matcher\n+ for len(optVal) > 0 {\n+ log.Infof(\"parseMatchers: optVal has len %d\", len(optVal))\n+ // Get the XTEntryMatch.\n+ if len(optVal) < linux.SizeOfXTEntryMatch {\n+ log.Warningf(\"netfilter: optVal has insufficient size for entry match: %d\", len(optVal))\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ var match linux.XTEntryMatch\n+ buf := optVal[:linux.SizeOfXTEntryMatch]\n+ binary.Unmarshal(buf, usermem.ByteOrder, &match)\n+ log.Infof(\"parseMatchers: parsed entry match %q: %+v\", match.Name.String(), match)\n+\n+ // Check some invariants.\n+ if match.MatchSize < linux.SizeOfXTEntryMatch {\n+ log.Warningf(\"netfilter: match size is too small, must be at least %d\", linux.SizeOfXTEntryMatch)\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ if len(optVal) < int(match.MatchSize) {\n+ log.Warningf(\"netfilter: optVal has insufficient size for match: %d\", len(optVal))\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ buf = optVal[linux.SizeOfXTEntryMatch:match.MatchSize]\n+ var matcher iptables.Matcher\n+ var err error\n+ switch match.Name.String() {\n+ case \"tcp\":\n+ if len(buf) < linux.SizeOfXTTCP {\n+ log.Warningf(\"netfilter: optVal has insufficient size for TCP match: %d\", len(optVal))\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ var matchData linux.XTTCP\n+ // For alignment reasons, the match's total size may exceed what's\n+ // strictly necessary to hold matchData.\n+ binary.Unmarshal(buf[:linux.SizeOfXTUDP], usermem.ByteOrder, &matchData)\n+ log.Infof(\"parseMatchers: parsed XTTCP: %+v\", matchData)\n+ matcher, err = iptables.NewTCPMatcher(filter, iptables.TCPMatcherData{\n+ SourcePortStart: matchData.SourcePortStart,\n+ SourcePortEnd: matchData.SourcePortEnd,\n+ DestinationPortStart: matchData.DestinationPortStart,\n+ DestinationPortEnd: matchData.DestinationPortEnd,\n+ Option: matchData.Option,\n+ FlagMask: matchData.FlagMask,\n+ FlagCompare: matchData.FlagCompare,\n+ InverseFlags: matchData.InverseFlags,\n+ })\n+ if err != nil {\n+ log.Warningf(\"netfilter: failed to create TCP matcher: %v\", err)\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ case \"udp\":\n+ if len(buf) < linux.SizeOfXTUDP {\n+ log.Warningf(\"netfilter: optVal has insufficient size for UDP match: %d\", len(optVal))\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+ var matchData linux.XTUDP\n+ // For alignment reasons, the match's total size may exceed what's\n+ // strictly necessary to hold matchData.\n+ binary.Unmarshal(buf[:linux.SizeOfXTUDP], usermem.ByteOrder, &matchData)\n+ log.Infof(\"parseMatchers: parsed XTUDP: %+v\", matchData)\n+ matcher, err = iptables.NewUDPMatcher(filter, iptables.UDPMatcherData{\n+ SourcePortStart: matchData.SourcePortStart,\n+ SourcePortEnd: matchData.SourcePortEnd,\n+ DestinationPortStart: matchData.DestinationPortStart,\n+ DestinationPortEnd: matchData.DestinationPortEnd,\n+ InverseFlags: matchData.InverseFlags,\n+ })\n+ if err != nil {\n+ log.Warningf(\"netfilter: failed to create UDP matcher: %v\", err)\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ default:\n+ log.Warningf(\"netfilter: unsupported matcher with name %q\", match.Name.String())\n+ return nil, syserr.ErrInvalidArgument\n+ }\n+\n+ matchers = append(matchers, matcher)\n+\n+ // TODO: Support revision.\n+ // TODO: Support proto -- matchers usually specify which proto(s) they work with.\n+ optVal = optVal[match.MatchSize:]\n+ }\n+\n+ // TODO: Check that optVal is exhausted.\n+ return matchers, nil\n+}\n+\n+// parseTarget parses a target from optVal. optVal should contain only the\n+// target.\n+func parseTarget(optVal []byte) (iptables.Target, *syserr.Error) {\nif len(optVal) < linux.SizeOfXTEntryTarget {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\n- return nil, 0, syserr.ErrInvalidArgument\n+ return nil, syserr.ErrInvalidArgument\n}\nvar target linux.XTEntryTarget\nbuf := optVal[:linux.SizeOfXTEntryTarget]\n@@ -414,9 +532,9 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nswitch target.Name.String() {\ncase \"\":\n// Standard target.\n- if len(optVal) < linux.SizeOfXTStandardTarget {\n- log.Warningf(\"netfilter.SetEntries: optVal has insufficient size for standard target %d\", len(optVal))\n- return nil, 0, syserr.ErrInvalidArgument\n+ if len(optVal) != linux.SizeOfXTStandardTarget {\n+ log.Warningf(\"netfilter.SetEntries: optVal has wrong size for standard target %d\", len(optVal))\n+ return nil, syserr.ErrInvalidArgument\n}\nvar standardTarget linux.XTStandardTarget\nbuf = optVal[:linux.SizeOfXTStandardTarget]\n@@ -424,22 +542,22 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\nverdict, err := translateToStandardVerdict(standardTarget.Verdict)\nif err != nil {\n- return nil, 0, err\n+ return nil, err\n}\nswitch verdict {\ncase iptables.Accept:\n- return iptables.UnconditionalAcceptTarget{}, linux.SizeOfXTStandardTarget, nil\n+ return iptables.UnconditionalAcceptTarget{}, nil\ncase iptables.Drop:\n- return iptables.UnconditionalDropTarget{}, linux.SizeOfXTStandardTarget, nil\n+ return iptables.UnconditionalDropTarget{}, nil\ndefault:\npanic(fmt.Sprintf(\"Unknown verdict: %v\", verdict))\n}\ncase errorTargetName:\n// Error target.\n- if len(optVal) < linux.SizeOfXTErrorTarget {\n+ if len(optVal) != linux.SizeOfXTErrorTarget {\nlog.Infof(\"netfilter.SetEntries: optVal has insufficient size for error target %d\", len(optVal))\n- return nil, 0, syserr.ErrInvalidArgument\n+ return nil, syserr.ErrInvalidArgument\n}\nvar errorTarget linux.XTErrorTarget\nbuf = optVal[:linux.SizeOfXTErrorTarget]\n@@ -454,16 +572,16 @@ func parseTarget(optVal []byte) (iptables.Target, uint32, *syserr.Error) {\n// rules have an error with the name of the chain.\nswitch errorTarget.Name.String() {\ncase errorTargetName:\n- return iptables.ErrorTarget{}, linux.SizeOfXTErrorTarget, nil\n+ return iptables.ErrorTarget{}, nil\ndefault:\nlog.Infof(\"Unknown error target %q doesn't exist or isn't supported yet.\", errorTarget.Name.String())\n- return nil, 0, syserr.ErrInvalidArgument\n+ return nil, syserr.ErrInvalidArgument\n}\n}\n// Unknown target.\nlog.Infof(\"Unknown target %q doesn't exist or isn't supported yet.\", target.Name.String())\n- return nil, 0, syserr.ErrInvalidArgument\n+ return nil, syserr.ErrInvalidArgument\n}\nfunc filterFromIPTIP(iptip linux.IPTIP) (iptables.IPHeaderFilter, *syserr.Error) {\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/BUILD", "new_path": "pkg/tcpip/iptables/BUILD", "diff": "@@ -7,7 +7,9 @@ go_library(\nsrcs = [\n\"iptables.go\",\n\"targets.go\",\n+ \"tcp_matcher.go\",\n\"types.go\",\n+ \"udp_matcher.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/tcpip/iptables\",\nvisibility = [\"//visibility:public\"],\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/iptables.go", "new_path": "pkg/tcpip/iptables/iptables.go", "diff": "@@ -138,6 +138,8 @@ func EmptyFilterTable() Table {\n// Check runs pkt through the rules for hook. It returns true when the packet\n// should continue traversing the network stack and false when it should be\n// dropped.\n+//\n+// Precondition: pkt.NetworkHeader is set.\nfunc (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\n// TODO(gvisor.dev/issue/170): A lot of this is uncomplicated because\n// we're missing features. Jumps, the call stack, etc. aren't checked\n@@ -163,6 +165,7 @@ func (it *IPTables) Check(hook Hook, pkt tcpip.PacketBuffer) bool {\nreturn true\n}\n+// Precondition: pkt.NetworkHeader is set.\nfunc (it *IPTables) checkTable(hook Hook, pkt tcpip.PacketBuffer, tablename string) Verdict {\n// Start from ruleIdx and walk the list of rules until a rule gives us\n// a verdict.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/iptables/tcp_matcher.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package iptables\n+\n+import (\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+)\n+\n+type TCPMatcher struct {\n+ data TCPMatcherData\n+\n+ // tablename string\n+ // unsigned int matchsize;\n+ // unsigned int usersize;\n+ // #ifdef CONFIG_COMPAT\n+ // unsigned int compatsize;\n+ // #endif\n+ // unsigned int hooks;\n+ // unsigned short proto;\n+ // unsigned short family;\n+}\n+\n+// TODO: Delete?\n+// MatchCheckEntryParams\n+\n+type TCPMatcherData struct {\n+ // Filter IPHeaderFilter\n+\n+ SourcePortStart uint16\n+ SourcePortEnd uint16\n+ DestinationPortStart uint16\n+ DestinationPortEnd uint16\n+ Option uint8\n+ FlagMask uint8\n+ FlagCompare uint8\n+ InverseFlags uint8\n+}\n+\n+func NewTCPMatcher(filter IPHeaderFilter, data TCPMatcherData) (Matcher, error) {\n+ // TODO: We currently only support source port and destination port.\n+ log.Infof(\"Adding rule with TCPMatcherData: %+v\", data)\n+\n+ if data.Option != 0 ||\n+ data.FlagMask != 0 ||\n+ data.FlagCompare != 0 ||\n+ data.InverseFlags != 0 {\n+ return nil, fmt.Errorf(\"unsupported TCP matcher flags set\")\n+ }\n+\n+ if filter.Protocol != header.TCPProtocolNumber {\n+ log.Warningf(\"TCP matching is only valid for protocol %d.\", header.TCPProtocolNumber)\n+ }\n+\n+ return &TCPMatcher{data: data}, nil\n+}\n+\n+// TODO: Check xt_tcpudp.c. Need to check for same things (e.g. fragments).\n+func (tm *TCPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\n+ netHeader := header.IPv4(pkt.NetworkHeader)\n+\n+ // TODO: Do we check proto here or elsewhere? I think elsewhere (check\n+ // codesearch).\n+ if netHeader.TransportProtocol() != header.TCPProtocolNumber {\n+ return false, false\n+ }\n+\n+ // We dont't match fragments.\n+ if frag := netHeader.FragmentOffset(); frag != 0 {\n+ if frag == 1 {\n+ log.Warningf(\"Dropping TCP packet: malicious packet with fragment with fragment offest of 1.\")\n+ return false, true\n+ }\n+ return false, false\n+ }\n+\n+ // Now we need the transport header. However, this may not have been set\n+ // yet.\n+ // TODO\n+ var tcpHeader header.TCP\n+ if pkt.TransportHeader != nil {\n+ tcpHeader = header.TCP(pkt.TransportHeader)\n+ } else {\n+ // The TCP header hasn't been parsed yet. We have to do it here.\n+ if len(pkt.Data.First()) < header.TCPMinimumSize {\n+ // There's no valid TCP header here, so we hotdrop the\n+ // packet.\n+ // TODO: Stats.\n+ log.Warningf(\"Dropping TCP packet: size to small.\")\n+ return false, true\n+ }\n+ tcpHeader = header.TCP(pkt.Data.First())\n+ }\n+\n+ // Check whether the source and destination ports are within the\n+ // matching range.\n+ sourcePort := tcpHeader.SourcePort()\n+ destinationPort := tcpHeader.DestinationPort()\n+ if sourcePort < tm.data.SourcePortStart || tm.data.SourcePortEnd < sourcePort {\n+ return false, false\n+ }\n+ if destinationPort < tm.data.DestinationPortStart || tm.data.DestinationPortEnd < destinationPort {\n+ return false, false\n+ }\n+\n+ return true, false\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -169,12 +169,29 @@ type IPHeaderFilter struct {\nProtocol tcpip.TransportProtocolNumber\n}\n+// TODO: Should these be able to marshal/unmarshal themselves?\n+// TODO: Something has to map the name to the matcher.\n// A Matcher is the interface for matching packets.\ntype Matcher interface {\n// Match returns whether the packet matches and whether the packet\n// should be \"hotdropped\", i.e. dropped immediately. This is usually\n// used for suspicious packets.\n+ //\n+ // Precondition: packet.NetworkHeader is set.\nMatch(hook Hook, packet tcpip.PacketBuffer, interfaceName string) (matches bool, hotdrop bool)\n+\n+ // TODO: Make this typesafe by having each Matcher have their own, typed CheckEntry?\n+ // CheckEntry(params MatchCheckEntryParams) bool\n+}\n+\n+// TODO: Unused?\n+type MatchCheckEntryParams struct {\n+ Table string // TODO: Tables should be an enum...\n+ Filter IPHeaderFilter\n+ Info interface{} // TODO: Type unsafe.\n+ // HookMask uint8\n+ // Family uint8\n+ // NFTCompat bool\n}\n// A Target is the interface for taking an action for a packet.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/tcpip/iptables/udp_matcher.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package iptables\n+\n+import (\n+ \"fmt\"\n+ \"runtime/debug\"\n+\n+ \"gvisor.dev/gvisor/pkg/log\"\n+ \"gvisor.dev/gvisor/pkg/tcpip\"\n+ \"gvisor.dev/gvisor/pkg/tcpip/header\"\n+)\n+\n+type UDPMatcher struct {\n+ data UDPMatcherData\n+\n+ // tablename string\n+ // unsigned int matchsize;\n+ // unsigned int usersize;\n+ // #ifdef CONFIG_COMPAT\n+ // unsigned int compatsize;\n+ // #endif\n+ // unsigned int hooks;\n+ // unsigned short proto;\n+ // unsigned short family;\n+}\n+\n+// TODO: Delete?\n+// MatchCheckEntryParams\n+\n+type UDPMatcherData struct {\n+ // Filter IPHeaderFilter\n+\n+ SourcePortStart uint16\n+ SourcePortEnd uint16\n+ DestinationPortStart uint16\n+ DestinationPortEnd uint16\n+ InverseFlags uint8\n+}\n+\n+func NewUDPMatcher(filter IPHeaderFilter, data UDPMatcherData) (Matcher, error) {\n+ // TODO: We currently only support source port and destination port.\n+ log.Infof(\"Adding rule with UDPMatcherData: %+v\", data)\n+\n+ if data.InverseFlags != 0 {\n+ return nil, fmt.Errorf(\"unsupported UDP matcher flags set\")\n+ }\n+\n+ if filter.Protocol != header.UDPProtocolNumber {\n+ log.Warningf(\"UDP matching is only valid for protocol %d.\", header.UDPProtocolNumber)\n+ }\n+\n+ return &UDPMatcher{data: data}, nil\n+}\n+\n+// TODO: Check xt_tcpudp.c. Need to check for same things (e.g. fragments).\n+func (tm *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\n+ log.Infof(\"UDPMatcher called from: %s\", string(debug.Stack()))\n+ netHeader := header.IPv4(pkt.NetworkHeader)\n+\n+ // TODO: Do we check proto here or elsewhere? I think elsewhere (check\n+ // codesearch).\n+ if netHeader.TransportProtocol() != header.UDPProtocolNumber {\n+ log.Infof(\"UDPMatcher: wrong protocol number\")\n+ return false, false\n+ }\n+\n+ // We dont't match fragments.\n+ if frag := netHeader.FragmentOffset(); frag != 0 {\n+ log.Infof(\"UDPMatcher: it's a fragment\")\n+ if frag == 1 {\n+ return false, true\n+ }\n+ log.Warningf(\"Dropping UDP packet: malicious fragmented packet.\")\n+ return false, false\n+ }\n+\n+ // Now we need the transport header. However, this may not have been set\n+ // yet.\n+ // TODO\n+ var udpHeader header.UDP\n+ if pkt.TransportHeader != nil {\n+ log.Infof(\"UDPMatcher: transport header is not nil\")\n+ udpHeader = header.UDP(pkt.TransportHeader)\n+ } else {\n+ log.Infof(\"UDPMatcher: transport header is nil\")\n+ log.Infof(\"UDPMatcher: is network header nil: %t\", pkt.NetworkHeader == nil)\n+ // The UDP header hasn't been parsed yet. We have to do it here.\n+ if len(pkt.Data.First()) < header.UDPMinimumSize {\n+ // There's no valid UDP header here, so we hotdrop the\n+ // packet.\n+ // TODO: Stats.\n+ log.Warningf(\"Dropping UDP packet: size to small.\")\n+ return false, true\n+ }\n+ udpHeader = header.UDP(pkt.Data.First())\n+ }\n+\n+ // Check whether the source and destination ports are within the\n+ // matching range.\n+ sourcePort := udpHeader.SourcePort()\n+ destinationPort := udpHeader.DestinationPort()\n+ log.Infof(\"UDPMatcher: sport and dport are %d and %d. sports and dport start and end are (%d, %d) and (%d, %d)\",\n+ udpHeader.SourcePort(), udpHeader.DestinationPort(),\n+ tm.data.SourcePortStart, tm.data.SourcePortEnd,\n+ tm.data.DestinationPortStart, tm.data.DestinationPortEnd)\n+ if sourcePort < tm.data.SourcePortStart || tm.data.SourcePortEnd < sourcePort {\n+ return false, false\n+ }\n+ if destinationPort < tm.data.DestinationPortStart || tm.data.DestinationPortEnd < destinationPort {\n+ return false, false\n+ }\n+\n+ return true, false\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/network/ipv4/ipv4.go", "new_path": "pkg/tcpip/network/ipv4/ipv4.go", "diff": "@@ -353,6 +353,11 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt tcpip.PacketBuffer) {\n}\npkt.NetworkHeader = headerView[:h.HeaderLength()]\n+ hlen := int(h.HeaderLength())\n+ tlen := int(h.TotalLength())\n+ pkt.Data.TrimFront(hlen)\n+ pkt.Data.CapLength(tlen - hlen)\n+\n// iptables filtering. All packets that reach here are intended for\n// this machine and will not be forwarded.\nipt := e.stack.IPTables()\n@@ -361,11 +366,6 @@ func (e *endpoint) HandlePacket(r *stack.Route, pkt tcpip.PacketBuffer) {\nreturn\n}\n- hlen := int(h.HeaderLength())\n- tlen := int(h.TotalLength())\n- pkt.Data.TrimFront(hlen)\n- pkt.Data.CapLength(tlen - hlen)\n-\nmore := (h.Flags() & header.IPv4FlagMoreFragments) != 0\nif more || h.FragmentOffset() != 0 {\nif pkt.Data.Size() == 0 {\n" }, { "change_type": "MODIFY", "old_path": "test/iptables/filter_input.go", "new_path": "test/iptables/filter_input.go", "diff": "package iptables\nimport (\n+ \"errors\"\n\"fmt\"\n\"net\"\n\"time\"\n@@ -248,3 +249,48 @@ func (FilterInputDropAll) ContainerAction(ip net.IP) error {\nfunc (FilterInputDropAll) LocalAction(ip net.IP) error {\nreturn sendUDPLoop(ip, dropPort, sendloopDuration)\n}\n+\n+// FilterInputMultiUDPRules verifies that multiple UDP rules are applied\n+// correctly. This has the added benefit of testing whether we're serializing\n+// rules correctly -- if we do it incorrectly, the iptables tool will\n+// misunderstand and save the wrong tables.\n+type FilterInputMultiUDPRules struct{}\n+\n+func (FilterInputMultiUDPRules) Name() string {\n+ return \"FilterInputMultiUDPRules\"\n+}\n+\n+func (FilterInputMultiUDPRules) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err != nil {\n+ return err\n+ }\n+ // if err := filterTable(\"-A\", \"INPUT\", \"-p\", \"udp\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", acceptPort), \"-j\", \"ACCEPT\"); err != nil {\n+ // return err\n+ // }\n+ return filterTable(\"-L\")\n+}\n+\n+func (FilterInputMultiUDPRules) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n+\n+// FilterInputRequireProtocolUDP checks that \"-m udp\" requires \"-p udp\" to be\n+// specified.\n+type FilterInputRequireProtocolUDP struct{}\n+\n+func (FilterInputRequireProtocolUDP) Name() string {\n+ return \"FilterInputRequireProtocolUDP\"\n+}\n+\n+func (FilterInputRequireProtocolUDP) ContainerAction(ip net.IP) error {\n+ if err := filterTable(\"-A\", \"INPUT\", \"-m\", \"udp\", \"--destination-port\", fmt.Sprintf(\"%d\", dropPort), \"-j\", \"DROP\"); err == nil {\n+ return errors.New(\"expected iptables to fail with out \\\"-p udp\\\", but succeeded\")\n+ }\n+ return nil\n+}\n+\n+func (FilterInputRequireProtocolUDP) LocalAction(ip net.IP) error {\n+ // No-op.\n+ return nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Add UDP matchers.
259,891
21.01.2020 14:51:28
28,800
2661101ad470548cb15dce0afc694296668d780a
Removed TCP work (saved in ipt-tcp-match).
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/netfilter.go", "new_path": "pkg/abi/linux/netfilter.go", "diff": "@@ -341,58 +341,6 @@ func goString(cstring []byte) string {\nreturn string(cstring)\n}\n-// XTTCP holds data for matching TCP packets. It corresponds to struct xt_tcp\n-// in include/uapi/linux/netfilter/xt_tcpudp.h.\n-type XTTCP struct {\n- // SourcePortStart specifies the inclusive start of the range of source\n- // ports to which the matcher applies.\n- SourcePortStart uint16\n-\n- // SourcePortEnd specifies the inclusive end of the range of source ports\n- // to which the matcher applies.\n- SourcePortEnd uint16\n-\n- // DestinationPortStart specifies the start of the destination port\n- // range to which the matcher applies.\n- DestinationPortStart uint16\n-\n- // DestinationPortEnd specifies the start of the destination port\n- // range to which the matcher applies.\n- DestinationPortEnd uint16\n-\n- // Option specifies that a particular TCP option must be set.\n- Option uint8\n-\n- // FlagMask masks the FlagCompare byte when comparing to the TCP flag\n- // fields.\n- FlagMask uint8\n-\n- // FlagCompare is binary and-ed with the TCP flag fields.\n- FlagCompare uint8\n-\n- // InverseFlags flips the meaning of certain fields. See the\n- // TX_TCP_INV_* flags.\n- InverseFlags uint8\n-}\n-\n-// SizeOfXTTCP is the size of an XTTCP.\n-const SizeOfXTTCP = 12\n-\n-// Flags in XTTCP.InverseFlags. Corresponding constants are in\n-// include/uapi/linux/netfilter/xt_tcpudp.h.\n-const (\n- // Invert the meaning of SourcePortStart/End.\n- XT_TCP_INV_SRCPT = 0x01\n- // Invert the meaning of DestinationPortStart/End.\n- XT_TCP_INV_DSTPT = 0x02\n- // Invert the meaning of FlagCompare.\n- XT_TCP_INV_FLAGS = 0x04\n- // Invert the meaning of Option.\n- XT_TCP_INV_OPTION = 0x08\n- // Enable all flags.\n- XT_TCP_INV_MASK = 0x0F\n-)\n-\n// XTUDP holds data for matching UDP packets. It corresponds to struct xt_udp\n// in include/uapi/linux/netfilter/xt_tcpudp.h.\ntype XTUDP struct {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -131,7 +131,6 @@ func FillDefaultIPTables(stack *stack.Stack) {\nstack.SetIPTables(ipt)\n}\n-// TODO: Return proto.\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@@ -456,31 +455,6 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\nvar matcher iptables.Matcher\nvar err error\nswitch match.Name.String() {\n- case \"tcp\":\n- if len(buf) < linux.SizeOfXTTCP {\n- log.Warningf(\"netfilter: optVal has insufficient size for TCP match: %d\", len(optVal))\n- return nil, syserr.ErrInvalidArgument\n- }\n- var matchData linux.XTTCP\n- // For alignment reasons, the match's total size may exceed what's\n- // strictly necessary to hold matchData.\n- binary.Unmarshal(buf[:linux.SizeOfXTUDP], usermem.ByteOrder, &matchData)\n- log.Infof(\"parseMatchers: parsed XTTCP: %+v\", matchData)\n- matcher, err = iptables.NewTCPMatcher(filter, iptables.TCPMatcherData{\n- SourcePortStart: matchData.SourcePortStart,\n- SourcePortEnd: matchData.SourcePortEnd,\n- DestinationPortStart: matchData.DestinationPortStart,\n- DestinationPortEnd: matchData.DestinationPortEnd,\n- Option: matchData.Option,\n- FlagMask: matchData.FlagMask,\n- FlagCompare: matchData.FlagCompare,\n- InverseFlags: matchData.InverseFlags,\n- })\n- if err != nil {\n- log.Warningf(\"netfilter: failed to create TCP matcher: %v\", err)\n- return nil, syserr.ErrInvalidArgument\n- }\n-\ncase \"udp\":\nif len(buf) < linux.SizeOfXTUDP {\nlog.Warningf(\"netfilter: optVal has insufficient size for UDP match: %d\", len(optVal))\n" }, { "change_type": "DELETE", "old_path": "pkg/tcpip/iptables/tcp_matcher.go", "new_path": null, "diff": "-// Copyright 2020 The gVisor Authors.\n-//\n-// Licensed under the Apache License, Version 2.0 (the \"License\");\n-// you may not use this file except in compliance with the License.\n-// You may obtain a copy of the License at\n-//\n-// http://www.apache.org/licenses/LICENSE-2.0\n-//\n-// Unless required by applicable law or agreed to in writing, software\n-// distributed under the License is distributed on an \"AS IS\" BASIS,\n-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-// See the License for the specific language governing permissions and\n-// limitations under the License.\n-\n-package iptables\n-\n-import (\n- \"fmt\"\n-\n- \"gvisor.dev/gvisor/pkg/log\"\n- \"gvisor.dev/gvisor/pkg/tcpip\"\n- \"gvisor.dev/gvisor/pkg/tcpip/header\"\n-)\n-\n-type TCPMatcher struct {\n- data TCPMatcherData\n-\n- // tablename string\n- // unsigned int matchsize;\n- // unsigned int usersize;\n- // #ifdef CONFIG_COMPAT\n- // unsigned int compatsize;\n- // #endif\n- // unsigned int hooks;\n- // unsigned short proto;\n- // unsigned short family;\n-}\n-\n-// TODO: Delete?\n-// MatchCheckEntryParams\n-\n-type TCPMatcherData struct {\n- // Filter IPHeaderFilter\n-\n- SourcePortStart uint16\n- SourcePortEnd uint16\n- DestinationPortStart uint16\n- DestinationPortEnd uint16\n- Option uint8\n- FlagMask uint8\n- FlagCompare uint8\n- InverseFlags uint8\n-}\n-\n-func NewTCPMatcher(filter IPHeaderFilter, data TCPMatcherData) (Matcher, error) {\n- // TODO: We currently only support source port and destination port.\n- log.Infof(\"Adding rule with TCPMatcherData: %+v\", data)\n-\n- if data.Option != 0 ||\n- data.FlagMask != 0 ||\n- data.FlagCompare != 0 ||\n- data.InverseFlags != 0 {\n- return nil, fmt.Errorf(\"unsupported TCP matcher flags set\")\n- }\n-\n- if filter.Protocol != header.TCPProtocolNumber {\n- log.Warningf(\"TCP matching is only valid for protocol %d.\", header.TCPProtocolNumber)\n- }\n-\n- return &TCPMatcher{data: data}, nil\n-}\n-\n-// TODO: Check xt_tcpudp.c. Need to check for same things (e.g. fragments).\n-func (tm *TCPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\n- netHeader := header.IPv4(pkt.NetworkHeader)\n-\n- // TODO: Do we check proto here or elsewhere? I think elsewhere (check\n- // codesearch).\n- if netHeader.TransportProtocol() != header.TCPProtocolNumber {\n- return false, false\n- }\n-\n- // We dont't match fragments.\n- if frag := netHeader.FragmentOffset(); frag != 0 {\n- if frag == 1 {\n- log.Warningf(\"Dropping TCP packet: malicious packet with fragment with fragment offest of 1.\")\n- return false, true\n- }\n- return false, false\n- }\n-\n- // Now we need the transport header. However, this may not have been set\n- // yet.\n- // TODO\n- var tcpHeader header.TCP\n- if pkt.TransportHeader != nil {\n- tcpHeader = header.TCP(pkt.TransportHeader)\n- } else {\n- // The TCP header hasn't been parsed yet. We have to do it here.\n- if len(pkt.Data.First()) < header.TCPMinimumSize {\n- // There's no valid TCP header here, so we hotdrop the\n- // packet.\n- // TODO: Stats.\n- log.Warningf(\"Dropping TCP packet: size to small.\")\n- return false, true\n- }\n- tcpHeader = header.TCP(pkt.Data.First())\n- }\n-\n- // Check whether the source and destination ports are within the\n- // matching range.\n- sourcePort := tcpHeader.SourcePort()\n- destinationPort := tcpHeader.DestinationPort()\n- if sourcePort < tm.data.SourcePortStart || tm.data.SourcePortEnd < sourcePort {\n- return false, false\n- }\n- if destinationPort < tm.data.DestinationPortStart || tm.data.DestinationPortEnd < destinationPort {\n- return false, false\n- }\n-\n- return true, false\n-}\n" } ]
Go
Apache License 2.0
google/gvisor
Removed TCP work (saved in ipt-tcp-match).
259,985
21.01.2020 14:25:14
28,800
ad1968ed5665c7541d6920edbd7c7492b7db3046
Implement sysfs.
[ { "change_type": "MODIFY", "old_path": "pkg/abi/linux/file.go", "new_path": "pkg/abi/linux/file.go", "diff": "@@ -180,6 +180,19 @@ const (\nDT_WHT = 14\n)\n+// DirentType are the friendly strings for linux_dirent64.d_type.\n+var DirentType = abi.ValueSet{\n+ DT_UNKNOWN: \"DT_UNKNOWN\",\n+ DT_FIFO: \"DT_FIFO\",\n+ DT_CHR: \"DT_CHR\",\n+ DT_DIR: \"DT_DIR\",\n+ DT_BLK: \"DT_BLK\",\n+ DT_REG: \"DT_REG\",\n+ DT_LNK: \"DT_LNK\",\n+ DT_SOCK: \"DT_SOCK\",\n+ DT_WHT: \"DT_WHT\",\n+}\n+\n// Values for preadv2/pwritev2.\nconst (\n// Note: gVisor does not implement the RWF_HIPRI feature, but the flag is\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/BUILD", "new_path": "pkg/sentry/fsimpl/kernfs/BUILD", "diff": "@@ -51,13 +51,12 @@ go_test(\ndeps = [\n\":kernfs\",\n\"//pkg/abi/linux\",\n- \"//pkg/fspath\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/context/contexttest\",\n+ \"//pkg/sentry/fsimpl/testutil\",\n\"//pkg/sentry/kernel/auth\",\n\"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n- \"//pkg/sync\",\n\"//pkg/syserror\",\n\"@com_github_google_go-cmp//cmp:go_default_library\",\n],\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "diff": "@@ -17,20 +17,17 @@ package kernfs_test\nimport (\n\"bytes\"\n\"fmt\"\n- \"io\"\n- \"runtime\"\n\"testing\"\n\"github.com/google/go-cmp/cmp\"\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n- \"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n\"gvisor.dev/gvisor/pkg/sentry/context/contexttest\"\n\"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n\"gvisor.dev/gvisor/pkg/sentry/vfs\"\n- \"gvisor.dev/gvisor/pkg/sync\"\n\"gvisor.dev/gvisor/pkg/syserror\"\n)\n@@ -41,21 +38,11 @@ const staticFileContent = \"This is sample content for a static test file.\"\n// filesystem. See newTestSystem.\ntype RootDentryFn func(*auth.Credentials, *filesystem) *kernfs.Dentry\n-// TestSystem represents the context for a single test.\n-type TestSystem struct {\n- t *testing.T\n- ctx context.Context\n- creds *auth.Credentials\n- vfs *vfs.VirtualFilesystem\n- mns *vfs.MountNamespace\n- root vfs.VirtualDentry\n-}\n-\n// newTestSystem sets up a minimal environment for running a test, including an\n// instance of a test filesystem. Tests can control the contents of the\n// filesystem by providing an appropriate rootFn, which should return a\n// pre-populated root dentry.\n-func newTestSystem(t *testing.T, rootFn RootDentryFn) *TestSystem {\n+func newTestSystem(t *testing.T, rootFn RootDentryFn) *testutil.System {\nctx := contexttest.Context(t)\ncreds := auth.CredentialsFromContext(ctx)\nv := vfs.New()\n@@ -66,57 +53,7 @@ func newTestSystem(t *testing.T, rootFn RootDentryFn) *TestSystem {\nif err != nil {\nt.Fatalf(\"Failed to create testfs root mount: %v\", err)\n}\n-\n- s := &TestSystem{\n- t: t,\n- ctx: ctx,\n- creds: creds,\n- vfs: v,\n- mns: mns,\n- root: mns.Root(),\n- }\n- runtime.SetFinalizer(s, func(s *TestSystem) { s.root.DecRef() })\n- return s\n-}\n-\n-// PathOpAtRoot constructs a vfs.PathOperation for a path from the\n-// root of the test filesystem.\n-//\n-// Precondition: path should be relative path.\n-func (s *TestSystem) PathOpAtRoot(path string) vfs.PathOperation {\n- return vfs.PathOperation{\n- Root: s.root,\n- Start: s.root,\n- Path: fspath.Parse(path),\n- }\n-}\n-\n-// GetDentryOrDie attempts to resolve a dentry referred to by the\n-// provided path operation. If unsuccessful, the test fails.\n-func (s *TestSystem) GetDentryOrDie(pop vfs.PathOperation) vfs.VirtualDentry {\n- vd, err := s.vfs.GetDentryAt(s.ctx, s.creds, &pop, &vfs.GetDentryOptions{})\n- if err != nil {\n- s.t.Fatalf(\"GetDentryAt(pop:%+v) failed: %v\", pop, err)\n- }\n- return vd\n-}\n-\n-func (s *TestSystem) ReadToEnd(fd *vfs.FileDescription) (string, error) {\n- buf := make([]byte, usermem.PageSize)\n- bufIOSeq := usermem.BytesIOSequence(buf)\n- opts := vfs.ReadOptions{}\n-\n- var content bytes.Buffer\n- for {\n- n, err := fd.Impl().Read(s.ctx, bufIOSeq, opts)\n- if n == 0 || err != nil {\n- if err == io.EOF {\n- err = nil\n- }\n- return content.String(), err\n- }\n- content.Write(buf[:n])\n- }\n+ return testutil.NewSystem(ctx, t, v, mns)\n}\ntype fsType struct {\n@@ -260,6 +197,7 @@ func TestBasic(t *testing.T) {\n\"file1\": fs.newFile(creds, staticFileContent),\n})\n})\n+ defer sys.Destroy()\nsys.GetDentryOrDie(sys.PathOpAtRoot(\"file1\")).DecRef()\n}\n@@ -269,9 +207,10 @@ func TestMkdirGetDentry(t *testing.T) {\n\"dir1\": fs.newDir(creds, 0755, nil),\n})\n})\n+ defer sys.Destroy()\npop := sys.PathOpAtRoot(\"dir1/a new directory\")\n- if err := sys.vfs.MkdirAt(sys.ctx, sys.creds, &pop, &vfs.MkdirOptions{Mode: 0755}); err != nil {\n+ if err := sys.VFS.MkdirAt(sys.Ctx, sys.Creds, &pop, &vfs.MkdirOptions{Mode: 0755}); err != nil {\nt.Fatalf(\"MkdirAt for PathOperation %+v failed: %v\", pop, err)\n}\nsys.GetDentryOrDie(pop).DecRef()\n@@ -283,20 +222,21 @@ func TestReadStaticFile(t *testing.T) {\n\"file1\": fs.newFile(creds, staticFileContent),\n})\n})\n+ defer sys.Destroy()\npop := sys.PathOpAtRoot(\"file1\")\n- fd, err := sys.vfs.OpenAt(sys.ctx, sys.creds, &pop, &vfs.OpenOptions{})\n+ fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\nif err != nil {\n- sys.t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n+ t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n}\ndefer fd.DecRef()\ncontent, err := sys.ReadToEnd(fd)\nif err != nil {\n- sys.t.Fatalf(\"Read failed: %v\", err)\n+ t.Fatalf(\"Read failed: %v\", err)\n}\nif diff := cmp.Diff(staticFileContent, content); diff != \"\" {\n- sys.t.Fatalf(\"Read returned unexpected data:\\n--- want\\n+++ got\\n%v\", diff)\n+ t.Fatalf(\"Read returned unexpected data:\\n--- want\\n+++ got\\n%v\", diff)\n}\n}\n@@ -306,83 +246,44 @@ func TestCreateNewFileInStaticDir(t *testing.T) {\n\"dir1\": fs.newDir(creds, 0755, nil),\n})\n})\n+ defer sys.Destroy()\npop := sys.PathOpAtRoot(\"dir1/newfile\")\nopts := &vfs.OpenOptions{Flags: linux.O_CREAT | linux.O_EXCL, Mode: defaultMode}\n- fd, err := sys.vfs.OpenAt(sys.ctx, sys.creds, &pop, opts)\n+ fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, opts)\nif err != nil {\n- sys.t.Fatalf(\"OpenAt(pop:%+v, opts:%+v) failed: %v\", pop, opts, err)\n+ t.Fatalf(\"OpenAt(pop:%+v, opts:%+v) failed: %v\", pop, opts, err)\n}\n// Close the file. The file should persist.\nfd.DecRef()\n- fd, err = sys.vfs.OpenAt(sys.ctx, sys.creds, &pop, &vfs.OpenOptions{})\n+ fd, err = sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\nif err != nil {\n- sys.t.Fatalf(\"OpenAt(pop:%+v) = %+v failed: %v\", pop, fd, err)\n+ t.Fatalf(\"OpenAt(pop:%+v) = %+v failed: %v\", pop, fd, err)\n}\nfd.DecRef()\n}\n-// direntCollector provides an implementation for vfs.IterDirentsCallback for\n-// testing. It simply iterates to the end of a given directory FD and collects\n-// all dirents emitted by the callback.\n-type direntCollector struct {\n- mu sync.Mutex\n- dirents map[string]vfs.Dirent\n-}\n-\n-// Handle implements vfs.IterDirentsCallback.Handle.\n-func (d *direntCollector) Handle(dirent vfs.Dirent) bool {\n- d.mu.Lock()\n- if d.dirents == nil {\n- d.dirents = make(map[string]vfs.Dirent)\n- }\n- d.dirents[dirent.Name] = dirent\n- d.mu.Unlock()\n- return true\n-}\n-\n-// count returns the number of dirents currently in the collector.\n-func (d *direntCollector) count() int {\n- d.mu.Lock()\n- defer d.mu.Unlock()\n- return len(d.dirents)\n-}\n-\n-// contains checks whether the collector has a dirent with the given name and\n-// type.\n-func (d *direntCollector) contains(name string, typ uint8) error {\n- d.mu.Lock()\n- defer d.mu.Unlock()\n- dirent, ok := d.dirents[name]\n- if !ok {\n- return fmt.Errorf(\"No dirent named %q found\", name)\n- }\n- if dirent.Type != typ {\n- return fmt.Errorf(\"Dirent named %q found, but was expecting type %d, got: %+v\", name, typ, dirent)\n- }\n- return nil\n-}\n-\nfunc TestDirFDReadWrite(t *testing.T) {\nsys := newTestSystem(t, func(creds *auth.Credentials, fs *filesystem) *kernfs.Dentry {\nreturn fs.newReadonlyDir(creds, 0755, nil)\n})\n+ defer sys.Destroy()\npop := sys.PathOpAtRoot(\"/\")\n- fd, err := sys.vfs.OpenAt(sys.ctx, sys.creds, &pop, &vfs.OpenOptions{})\n+ fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\nif err != nil {\n- sys.t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n+ t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n}\ndefer fd.DecRef()\n// Read/Write should fail for directory FDs.\n- if _, err := fd.Read(sys.ctx, usermem.BytesIOSequence([]byte{}), vfs.ReadOptions{}); err != syserror.EISDIR {\n- sys.t.Fatalf(\"Read for directory FD failed with unexpected error: %v\", err)\n+ if _, err := fd.Read(sys.Ctx, usermem.BytesIOSequence([]byte{}), vfs.ReadOptions{}); err != syserror.EISDIR {\n+ t.Fatalf(\"Read for directory FD failed with unexpected error: %v\", err)\n}\n- if _, err := fd.Write(sys.ctx, usermem.BytesIOSequence([]byte{}), vfs.WriteOptions{}); err != syserror.EISDIR {\n- sys.t.Fatalf(\"Wrire for directory FD failed with unexpected error: %v\", err)\n+ if _, err := fd.Write(sys.Ctx, usermem.BytesIOSequence([]byte{}), vfs.WriteOptions{}); err != syserror.EISDIR {\n+ t.Fatalf(\"Write for directory FD failed with unexpected error: %v\", err)\n}\n}\n@@ -397,30 +298,12 @@ func TestDirFDIterDirents(t *testing.T) {\n\"file1\": fs.newFile(creds, staticFileContent),\n})\n})\n+ defer sys.Destroy()\npop := sys.PathOpAtRoot(\"/\")\n- fd, err := sys.vfs.OpenAt(sys.ctx, sys.creds, &pop, &vfs.OpenOptions{})\n- if err != nil {\n- sys.t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n- }\n- defer fd.DecRef()\n-\n- collector := &direntCollector{}\n- if err := fd.IterDirents(sys.ctx, collector); err != nil {\n- sys.t.Fatalf(\"IterDirent failed: %v\", err)\n- }\n-\n- // Root directory should contain \".\", \"..\" and 3 children:\n- if collector.count() != 5 {\n- sys.t.Fatalf(\"IterDirent returned too many dirents\")\n- }\n- for _, dirName := range []string{\".\", \"..\", \"dir1\", \"dir2\"} {\n- if err := collector.contains(dirName, linux.DT_DIR); err != nil {\n- sys.t.Fatalf(\"IterDirent had unexpected results: %v\", err)\n- }\n- }\n- if err := collector.contains(\"file1\", linux.DT_REG); err != nil {\n- sys.t.Fatalf(\"IterDirent had unexpected results: %v\", err)\n- }\n-\n+ sys.AssertDirectoryContains(&pop, map[string]testutil.DirentType{\n+ \"dir1\": linux.DT_DIR,\n+ \"dir2\": linux.DT_DIR,\n+ \"file1\": linux.DT_REG,\n+ })\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/BUILD", "new_path": "pkg/sentry/fsimpl/proc/BUILD", "diff": "@@ -44,30 +44,19 @@ go_test(\nname = \"proc_test\",\nsize = \"small\",\nsrcs = [\n- \"boot_test.go\",\n\"tasks_sys_test.go\",\n\"tasks_test.go\",\n],\nembed = [\":proc\"],\ndeps = [\n\"//pkg/abi/linux\",\n- \"//pkg/cpuid\",\n\"//pkg/fspath\",\n- \"//pkg/memutil\",\n\"//pkg/sentry/context\",\n\"//pkg/sentry/context/contexttest\",\n- \"//pkg/sentry/fs\",\n+ \"//pkg/sentry/fsimpl/testutil\",\n\"//pkg/sentry/inet\",\n\"//pkg/sentry/kernel\",\n\"//pkg/sentry/kernel/auth\",\n- \"//pkg/sentry/kernel/sched\",\n- \"//pkg/sentry/limits\",\n- \"//pkg/sentry/loader\",\n- \"//pkg/sentry/pgalloc\",\n- \"//pkg/sentry/platform\",\n- \"//pkg/sentry/platform/kvm\",\n- \"//pkg/sentry/platform/ptrace\",\n- \"//pkg/sentry/time\",\n\"//pkg/sentry/usermem\",\n\"//pkg/sentry/vfs\",\n\"//pkg/syserror\",\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "new_path": "pkg/sentry/fsimpl/proc/tasks_test.go", "diff": "@@ -24,6 +24,7 @@ import (\n\"gvisor.dev/gvisor/pkg/abi/linux\"\n\"gvisor.dev/gvisor/pkg/fspath\"\n\"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel\"\n\"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n\"gvisor.dev/gvisor/pkg/sentry/usermem\"\n@@ -134,7 +135,7 @@ func checkFiles(gots []vfs.Dirent, wants map[string]vfs.Dirent) ([]vfs.Dirent, e\n}\nfunc setup() (context.Context, *vfs.VirtualFilesystem, vfs.VirtualDentry, error) {\n- k, err := boot()\n+ k, err := testutil.Boot()\nif err != nil {\nreturn nil, nil, vfs.VirtualDentry{}, fmt.Errorf(\"creating kernel: %v\", err)\n}\n@@ -206,7 +207,7 @@ func TestTasks(t *testing.T) {\nvar tasks []*kernel.Task\nfor i := 0; i < 5; i++ {\ntc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n- task, err := createTask(ctx, fmt.Sprintf(\"name-%d\", i), tc)\n+ task, err := testutil.CreateTask(ctx, fmt.Sprintf(\"name-%d\", i), tc)\nif err != nil {\nt.Fatalf(\"CreateTask(): %v\", err)\n}\n@@ -298,7 +299,7 @@ func TestTasksOffset(t *testing.T) {\nk := kernel.KernelFromContext(ctx)\nfor i := 0; i < 3; i++ {\ntc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n- if _, err := createTask(ctx, fmt.Sprintf(\"name-%d\", i), tc); err != nil {\n+ if _, err := testutil.CreateTask(ctx, fmt.Sprintf(\"name-%d\", i), tc); err != nil {\nt.Fatalf(\"CreateTask(): %v\", err)\n}\n}\n@@ -417,7 +418,7 @@ func TestTask(t *testing.T) {\nk := kernel.KernelFromContext(ctx)\ntc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n- _, err = createTask(ctx, \"name\", tc)\n+ _, err = testutil.CreateTask(ctx, \"name\", tc)\nif err != nil {\nt.Fatalf(\"CreateTask(): %v\", err)\n}\n@@ -458,7 +459,7 @@ func TestProcSelf(t *testing.T) {\nk := kernel.KernelFromContext(ctx)\ntc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n- task, err := createTask(ctx, \"name\", tc)\n+ task, err := testutil.CreateTask(ctx, \"name\", tc)\nif err != nil {\nt.Fatalf(\"CreateTask(): %v\", err)\n}\n@@ -555,7 +556,7 @@ func TestTree(t *testing.T) {\nvar tasks []*kernel.Task\nfor i := 0; i < 5; i++ {\ntc := k.NewThreadGroup(nil, k.RootPIDNamespace(), kernel.NewSignalHandlers(), linux.SIGCHLD, k.GlobalInit().Limits())\n- task, err := createTask(uberCtx, fmt.Sprintf(\"name-%d\", i), tc)\n+ task, err := testutil.CreateTask(uberCtx, fmt.Sprintf(\"name-%d\", i), tc)\nif err != nil {\nt.Fatalf(\"CreateTask(): %v\", err)\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/sys/BUILD", "diff": "+load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\n+load(\"@io_bazel_rules_go//go:def.bzl\", \"go_test\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"sys\",\n+ srcs = [\n+ \"sys.go\",\n+ ],\n+ importpath = \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\",\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/sentry/context\",\n+ \"//pkg/sentry/fsimpl/kernfs\",\n+ \"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/syserror\",\n+ ],\n+)\n+\n+go_test(\n+ name = \"sys_test\",\n+ srcs = [\"sys_test.go\"],\n+ deps = [\n+ \":sys\",\n+ \"//pkg/abi/linux\",\n+ \"//pkg/sentry/fsimpl/testutil\",\n+ \"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/vfs\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/sys/sys.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 sys implements sysfs.\n+package sys\n+\n+import (\n+ \"bytes\"\n+ \"fmt\"\n+\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/kernfs\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/syserror\"\n+)\n+\n+// FilesystemType implements vfs.FilesystemType.\n+type FilesystemType struct{}\n+\n+// filesystem implements vfs.FilesystemImpl.\n+type filesystem struct {\n+ kernfs.Filesystem\n+}\n+\n+// GetFilesystem implements vfs.FilesystemType.GetFilesystem.\n+func (FilesystemType) GetFilesystem(ctx context.Context, vfsObj *vfs.VirtualFilesystem, creds *auth.Credentials, source string, opts vfs.GetFilesystemOptions) (*vfs.Filesystem, *vfs.Dentry, error) {\n+ fs := &filesystem{}\n+ fs.Filesystem.Init(vfsObj)\n+ k := kernel.KernelFromContext(ctx)\n+ maxCPUCores := k.ApplicationCores()\n+ defaultSysDirMode := linux.FileMode(0755)\n+\n+ root := fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n+ \"block\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"bus\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"class\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n+ \"power_supply\": fs.newDir(creds, defaultSysDirMode, nil),\n+ }),\n+ \"dev\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"devices\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n+ \"system\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n+ \"cpu\": fs.newDir(creds, defaultSysDirMode, map[string]*kernfs.Dentry{\n+ \"online\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ \"possible\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ \"present\": fs.newCPUFile(creds, maxCPUCores, linux.FileMode(0444)),\n+ }),\n+ }),\n+ }),\n+ \"firmware\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"fs\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"kernel\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"module\": fs.newDir(creds, defaultSysDirMode, nil),\n+ \"power\": fs.newDir(creds, defaultSysDirMode, nil),\n+ })\n+ return fs.VFSFilesystem(), root.VFSDentry(), nil\n+}\n+\n+// dir implements kernfs.Inode.\n+type dir struct {\n+ kernfs.InodeAttrs\n+ kernfs.InodeNoDynamicLookup\n+ kernfs.InodeNotSymlink\n+ kernfs.InodeDirectoryNoNewChildren\n+\n+ kernfs.OrderedChildren\n+ dentry kernfs.Dentry\n+}\n+\n+func (fs *filesystem) newDir(creds *auth.Credentials, mode linux.FileMode, contents map[string]*kernfs.Dentry) *kernfs.Dentry {\n+ d := &dir{}\n+ d.InodeAttrs.Init(creds, fs.NextIno(), linux.ModeDirectory|0755)\n+ d.OrderedChildren.Init(kernfs.OrderedChildrenOptions{})\n+ d.dentry.Init(d)\n+\n+ d.IncLinks(d.OrderedChildren.Populate(&d.dentry, contents))\n+\n+ return &d.dentry\n+}\n+\n+// SetStat implements kernfs.Inode.SetStat.\n+func (d *dir) SetStat(fs *vfs.Filesystem, opts vfs.SetStatOptions) error {\n+ return syserror.EPERM\n+}\n+\n+// Open implements kernfs.Inode.Open.\n+func (d *dir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*vfs.FileDescription, error) {\n+ fd := &kernfs.GenericDirectoryFD{}\n+ fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, flags)\n+ return fd.VFSFileDescription(), nil\n+}\n+\n+// cpuFile implements kernfs.Inode.\n+type cpuFile struct {\n+ kernfs.DynamicBytesFile\n+ maxCores uint\n+}\n+\n+// Generate implements vfs.DynamicBytesSource.Generate.\n+func (c *cpuFile) Generate(ctx context.Context, buf *bytes.Buffer) error {\n+ fmt.Fprintf(buf, \"0-%d\", c.maxCores-1)\n+ return nil\n+}\n+\n+func (fs *filesystem) newCPUFile(creds *auth.Credentials, maxCores uint, mode linux.FileMode) *kernfs.Dentry {\n+ c := &cpuFile{maxCores: maxCores}\n+ c.DynamicBytesFile.Init(creds, fs.NextIno(), c, mode)\n+ d := &kernfs.Dentry{}\n+ d.Init(c)\n+ return d\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/sys/sys_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 sys_test\n+\n+import (\n+ \"fmt\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/sys\"\n+ \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+func newTestSystem(t *testing.T) *testutil.System {\n+ k, err := testutil.Boot()\n+ if err != nil {\n+ t.Fatalf(\"Failed to create test kernel: %v\", err)\n+ }\n+ ctx := k.SupervisorContext()\n+ creds := auth.CredentialsFromContext(ctx)\n+ v := vfs.New()\n+ v.MustRegisterFilesystemType(\"sysfs\", sys.FilesystemType{}, &vfs.RegisterFilesystemTypeOptions{\n+ AllowUserMount: true,\n+ })\n+\n+ mns, err := v.NewMountNamespace(ctx, creds, \"\", \"sysfs\", &vfs.GetFilesystemOptions{})\n+ if err != nil {\n+ t.Fatalf(\"Failed to create new mount namespace: %v\", err)\n+ }\n+ return testutil.NewSystem(ctx, t, v, mns)\n+}\n+\n+func TestReadCPUFile(t *testing.T) {\n+ s := newTestSystem(t)\n+ defer s.Destroy()\n+ k := kernel.KernelFromContext(s.Ctx)\n+ maxCPUCores := k.ApplicationCores()\n+\n+ expected := fmt.Sprintf(\"0-%d\", maxCPUCores-1)\n+\n+ for _, fname := range []string{\"online\", \"possible\", \"present\"} {\n+ pop := s.PathOpAtRoot(fmt.Sprintf(\"devices/system/cpu/%s\", fname))\n+ fd, err := s.VFS.OpenAt(s.Ctx, s.Creds, &pop, &vfs.OpenOptions{})\n+ if err != nil {\n+ t.Fatalf(\"OpenAt(pop:%+v) = %+v failed: %v\", pop, fd, err)\n+ }\n+ defer fd.DecRef()\n+ content, err := s.ReadToEnd(fd)\n+ if err != nil {\n+ t.Fatalf(\"Read failed: %v\", err)\n+ }\n+ if diff := cmp.Diff(expected, content); diff != \"\" {\n+ t.Fatalf(\"Read returned unexpected data:\\n--- want\\n+++ got\\n%v\", diff)\n+ }\n+ }\n+}\n+\n+func TestSysRootContainsExpectedEntries(t *testing.T) {\n+ s := newTestSystem(t)\n+ defer s.Destroy()\n+ pop := s.PathOpAtRoot(\"/\")\n+ s.AssertDirectoryContains(&pop, map[string]testutil.DirentType{\n+ \"block\": linux.DT_DIR,\n+ \"bus\": linux.DT_DIR,\n+ \"class\": linux.DT_DIR,\n+ \"dev\": linux.DT_DIR,\n+ \"devices\": linux.DT_DIR,\n+ \"firmware\": linux.DT_DIR,\n+ \"fs\": linux.DT_DIR,\n+ \"kernel\": linux.DT_DIR,\n+ \"module\": linux.DT_DIR,\n+ \"power\": linux.DT_DIR,\n+ })\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/testutil/BUILD", "diff": "+load(\"//tools/go_stateify:defs.bzl\", \"go_library\")\n+\n+package(licenses = [\"notice\"])\n+\n+go_library(\n+ name = \"testutil\",\n+ testonly = 1,\n+ srcs = [\n+ \"kernel.go\",\n+ \"testutil.go\",\n+ ],\n+ importpath = \"gvisor.dev/gvisor/pkg/sentry/fsimpl/testutil\",\n+ visibility = [\"//pkg/sentry:internal\"],\n+ deps = [\n+ \"//pkg/abi/linux\",\n+ \"//pkg/cpuid\",\n+ \"//pkg/fspath\",\n+ \"//pkg/memutil\",\n+ \"//pkg/sentry/context\",\n+ \"//pkg/sentry/fs\",\n+ \"//pkg/sentry/kernel\",\n+ \"//pkg/sentry/kernel/auth\",\n+ \"//pkg/sentry/kernel/sched\",\n+ \"//pkg/sentry/limits\",\n+ \"//pkg/sentry/loader\",\n+ \"//pkg/sentry/pgalloc\",\n+ \"//pkg/sentry/platform\",\n+ \"//pkg/sentry/platform/kvm\",\n+ \"//pkg/sentry/platform/ptrace\",\n+ \"//pkg/sentry/time\",\n+ \"//pkg/sentry/usermem\",\n+ \"//pkg/sentry/vfs\",\n+ \"//pkg/sync\",\n+ \"@com_github_google_go-cmp//cmp:go_default_library\",\n+ ],\n+)\n" }, { "change_type": "RENAME", "old_path": "pkg/sentry/fsimpl/proc/boot_test.go", "new_path": "pkg/sentry/fsimpl/testutil/kernel.go", "diff": "// See the License for the specific language governing permissions and\n// limitations under the License.\n-package proc\n+package testutil\nimport (\n\"flag\"\n@@ -43,8 +43,8 @@ var (\nplatformFlag = flag.String(\"platform\", \"ptrace\", \"specify which platform to use\")\n)\n-// boot initializes a new bare bones kernel for test.\n-func boot() (*kernel.Kernel, error) {\n+// Boot initializes a new bare bones kernel for test.\n+func Boot() (*kernel.Kernel, error) {\nplatformCtr, err := platform.Lookup(*platformFlag)\nif err != nil {\nreturn nil, fmt.Errorf(\"platform not found: %v\", err)\n@@ -117,8 +117,8 @@ func boot() (*kernel.Kernel, error) {\nreturn k, nil\n}\n-// createTask creates a new bare bones task for tests.\n-func createTask(ctx context.Context, name string, tc *kernel.ThreadGroup) (*kernel.Task, error) {\n+// CreateTask creates a new bare bones task for tests.\n+func CreateTask(ctx context.Context, name string, tc *kernel.ThreadGroup) (*kernel.Task, error) {\nk := kernel.KernelFromContext(ctx)\nconfig := &kernel.TaskConfig{\nKernel: k,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/testutil/testutil.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 testutil provides common test utilities for kernfs-based\n+// filesystems.\n+package testutil\n+\n+import (\n+ \"fmt\"\n+ \"io\"\n+ \"strings\"\n+ \"testing\"\n+\n+ \"github.com/google/go-cmp/cmp\"\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/fspath\"\n+ \"gvisor.dev/gvisor/pkg/sentry/context\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/usermem\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+ \"gvisor.dev/gvisor/pkg/sync\"\n+)\n+\n+// System represents the context for a single test.\n+//\n+// Test systems must be explicitly destroyed with System.Destroy.\n+type System struct {\n+ t *testing.T\n+ Ctx context.Context\n+ Creds *auth.Credentials\n+ VFS *vfs.VirtualFilesystem\n+ mns *vfs.MountNamespace\n+ root vfs.VirtualDentry\n+}\n+\n+// NewSystem constructs a System.\n+//\n+// Precondition: Caller must hold a reference on mns, whose ownership\n+// is transferred to the new System.\n+func NewSystem(ctx context.Context, t *testing.T, v *vfs.VirtualFilesystem, mns *vfs.MountNamespace) *System {\n+ s := &System{\n+ t: t,\n+ Ctx: ctx,\n+ Creds: auth.CredentialsFromContext(ctx),\n+ VFS: v,\n+ mns: mns,\n+ root: mns.Root(),\n+ }\n+ return s\n+}\n+\n+// Destroy release resources associated with a test system.\n+func (s *System) Destroy() {\n+ s.root.DecRef()\n+ s.mns.DecRef(s.VFS) // Reference on mns passed to NewSystem.\n+}\n+\n+// ReadToEnd reads the contents of fd until EOF to a string.\n+func (s *System) ReadToEnd(fd *vfs.FileDescription) (string, error) {\n+ buf := make([]byte, usermem.PageSize)\n+ bufIOSeq := usermem.BytesIOSequence(buf)\n+ opts := vfs.ReadOptions{}\n+\n+ var content strings.Builder\n+ for {\n+ n, err := fd.Read(s.Ctx, bufIOSeq, opts)\n+ if n == 0 || err != nil {\n+ if err == io.EOF {\n+ err = nil\n+ }\n+ return content.String(), err\n+ }\n+ content.Write(buf[:n])\n+ }\n+}\n+\n+// PathOpAtRoot constructs a PathOperation with the given path from\n+// the root of the filesystem.\n+func (s *System) PathOpAtRoot(path string) vfs.PathOperation {\n+ return vfs.PathOperation{\n+ Root: s.root,\n+ Start: s.root,\n+ Path: fspath.Parse(path),\n+ }\n+}\n+\n+// GetDentryOrDie attempts to resolve a dentry referred to by the\n+// provided path operation. If unsuccessful, the test fails.\n+func (s *System) GetDentryOrDie(pop vfs.PathOperation) vfs.VirtualDentry {\n+ vd, err := s.VFS.GetDentryAt(s.Ctx, s.Creds, &pop, &vfs.GetDentryOptions{})\n+ if err != nil {\n+ s.t.Fatalf(\"GetDentryAt(pop:%+v) failed: %v\", pop, err)\n+ }\n+ return vd\n+}\n+\n+// DirentType is an alias for values for linux_dirent64.d_type.\n+type DirentType = uint8\n+\n+// AssertDirectoryContains verifies that a directory at pop contains the entries\n+// specified. AssertDirectoryContains implicitly checks for \".\" and \"..\", these\n+// need not be included in entries.\n+func (s *System) AssertDirectoryContains(pop *vfs.PathOperation, entries map[string]DirentType) {\n+ // Also implicitly check for \".\" and \"..\".\n+ entries[\".\"] = linux.DT_DIR\n+ entries[\"..\"] = linux.DT_DIR\n+\n+ fd, err := s.VFS.OpenAt(s.Ctx, s.Creds, pop, &vfs.OpenOptions{Flags: linux.O_RDONLY})\n+ if err != nil {\n+ s.t.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n+ }\n+ defer fd.DecRef()\n+\n+ collector := &DirentCollector{}\n+ if err := fd.IterDirents(s.Ctx, collector); err != nil {\n+ s.t.Fatalf(\"IterDirent failed: %v\", err)\n+ }\n+\n+ collectedEntries := make(map[string]DirentType)\n+ for _, dirent := range collector.dirents {\n+ collectedEntries[dirent.Name] = dirent.Type\n+ }\n+ if diff := cmp.Diff(entries, collectedEntries); diff != \"\" {\n+ s.t.Fatalf(\"IterDirent had unexpected results:\\n--- want\\n+++ got\\n%v\", diff)\n+ }\n+}\n+\n+// DirentCollector provides an implementation for vfs.IterDirentsCallback for\n+// testing. It simply iterates to the end of a given directory FD and collects\n+// all dirents emitted by the callback.\n+type DirentCollector struct {\n+ mu sync.Mutex\n+ dirents map[string]vfs.Dirent\n+}\n+\n+// Handle implements vfs.IterDirentsCallback.Handle.\n+func (d *DirentCollector) Handle(dirent vfs.Dirent) bool {\n+ d.mu.Lock()\n+ if d.dirents == nil {\n+ d.dirents = make(map[string]vfs.Dirent)\n+ }\n+ d.dirents[dirent.Name] = dirent\n+ d.mu.Unlock()\n+ return true\n+}\n+\n+// Count returns the number of dirents currently in the collector.\n+func (d *DirentCollector) Count() int {\n+ d.mu.Lock()\n+ defer d.mu.Unlock()\n+ return len(d.dirents)\n+}\n+\n+// Contains checks whether the collector has a dirent with the given name and\n+// type.\n+func (d *DirentCollector) Contains(name string, typ uint8) error {\n+ d.mu.Lock()\n+ defer d.mu.Unlock()\n+ dirent, ok := d.dirents[name]\n+ if !ok {\n+ return fmt.Errorf(\"No dirent named %q found\", name)\n+ }\n+ if dirent.Type != typ {\n+ return fmt.Errorf(\"Dirent named %q found, but was expecting type %s, got: %+v\", name, linux.DirentType.Parse(uint64(typ)), dirent)\n+ }\n+ return nil\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
Implement sysfs. PiperOrigin-RevId: 290822487
260,023
21.01.2020 14:47:04
28,800
7e6fbc6afe797752efe066a8aa86f9eca973f3a4
Add a new TCP stat for current open connections. Such a stat accounts for all connections that are currently established and not yet transitioned to close state. Also fix bug in double increment of CurrentEstablished stat. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netstack/netstack.go", "new_path": "pkg/sentry/socket/netstack/netstack.go", "diff": "@@ -150,7 +150,8 @@ var Metrics = tcpip.Stats{\nTCP: tcpip.TCPStats{\nActiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/active_connection_openings\", \"Number of connections opened successfully via Connect.\"),\nPassiveConnectionOpenings: mustCreateMetric(\"/netstack/tcp/passive_connection_openings\", \"Number of connections opened successfully via Listen.\"),\n- CurrentEstablished: mustCreateMetric(\"/netstack/tcp/current_established\", \"Number of connections in either ESTABLISHED or CLOSE-WAIT state now.\"),\n+ CurrentEstablished: mustCreateMetric(\"/netstack/tcp/current_established\", \"Number of connections in ESTABLISHED state now.\"),\n+ CurrentConnected: mustCreateMetric(\"/netstack/tcp/current_open\", \"Number of connections that are in connected state.\"),\nEstablishedResets: mustCreateMetric(\"/netstack/tcp/established_resets\", \"Number of times TCP connections have made a direct transition to the CLOSED state from either the ESTABLISHED state or the CLOSE-WAIT state\"),\nEstablishedClosed: mustCreateMetric(\"/netstack/tcp/established_closed\", \"number of times established TCP connections made a transition to CLOSED state.\"),\nEstablishedTimedout: mustCreateMetric(\"/netstack/tcp/established_timedout\", \"Number of times an established connection was reset because of keep-alive time out.\"),\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/tcpip.go", "new_path": "pkg/tcpip/tcpip.go", "diff": "@@ -938,9 +938,13 @@ type TCPStats struct {\nPassiveConnectionOpenings *StatCounter\n// CurrentEstablished is the number of TCP connections for which the\n- // current state is either ESTABLISHED or CLOSE-WAIT.\n+ // current state is ESTABLISHED.\nCurrentEstablished *StatCounter\n+ // CurrentConnected is the number of TCP connections that\n+ // are in connected state.\n+ CurrentConnected *StatCounter\n+\n// EstablishedResets is the number of times TCP connections have made\n// a direct transition to the CLOSED state from either the\n// ESTABLISHED state or the CLOSE-WAIT state.\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/accept.go", "new_path": "pkg/tcpip/transport/tcp/accept.go", "diff": "@@ -562,7 +562,6 @@ func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {\n// Switch state to connected.\n// We do not use transitionToStateEstablishedLocked here as there is\n// no handshake state available when doing a SYN cookie based accept.\n- n.stack.Stats().TCP.CurrentEstablished.Increment()\nn.isConnectNotified = true\nn.setEndpointState(StateEstablished)\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/connect.go", "new_path": "pkg/tcpip/transport/tcp/connect.go", "diff": "@@ -934,6 +934,7 @@ func (e *endpoint) transitionToStateCloseLocked() {\n// Mark the endpoint as fully closed for reads/writes.\ne.cleanupLocked()\ne.setEndpointState(StateClose)\n+ e.stack.Stats().TCP.CurrentConnected.Decrement()\ne.stack.Stats().TCP.EstablishedClosed.Increment()\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/endpoint.go", "new_path": "pkg/tcpip/transport/tcp/endpoint.go", "diff": "@@ -594,6 +594,7 @@ func (e *endpoint) setEndpointState(state EndpointState) {\nswitch state {\ncase StateEstablished:\ne.stack.Stats().TCP.CurrentEstablished.Increment()\n+ e.stack.Stats().TCP.CurrentConnected.Increment()\ncase StateError:\nfallthrough\ncase StateClose:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/transport/tcp/tcp_test.go", "new_path": "pkg/tcpip/transport/tcp/tcp_test.go", "diff": "@@ -470,6 +470,89 @@ func TestConnectResetAfterClose(t *testing.T) {\n}\n}\n+// TestCurrentConnectedIncrement tests increment of the current\n+// established and connected counters.\n+func TestCurrentConnectedIncrement(t *testing.T) {\n+ c := context.New(t, defaultMTU)\n+ defer c.Cleanup()\n+\n+ // Set TCPTimeWaitTimeout to 1 seconds so that sockets are marked closed\n+ // after 1 second in TIME_WAIT state.\n+ tcpTimeWaitTimeout := 1 * time.Second\n+ if err := c.Stack().SetTransportProtocolOption(tcp.ProtocolNumber, tcpip.TCPTimeWaitTimeoutOption(tcpTimeWaitTimeout)); err != nil {\n+ t.Fatalf(\"c.stack.SetTransportProtocolOption(tcp, tcpip.TCPTimeWaitTimeout(%d) failed: %s\", tcpTimeWaitTimeout, err)\n+ }\n+\n+ c.CreateConnected(789, 30000, -1 /* epRcvBuf */)\n+ ep := c.EP\n+ c.EP = nil\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 1 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 1\", got)\n+ }\n+ gotConnected := c.Stack().Stats().TCP.CurrentConnected.Value()\n+ if gotConnected != 1 {\n+ t.Errorf(\"got stats.TCP.CurrentConnected.Value() = %v, want = 1\", gotConnected)\n+ }\n+\n+ ep.Close()\n+\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.SeqNum(uint32(c.IRS)+1),\n+ checker.AckNum(790),\n+ checker.TCPFlags(header.TCPFlagAck|header.TCPFlagFin),\n+ ),\n+ )\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagAck,\n+ SeqNum: 790,\n+ AckNum: c.IRS.Add(2),\n+ RcvWnd: 30000,\n+ })\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n+ if got := c.Stack().Stats().TCP.CurrentConnected.Value(); got != gotConnected {\n+ t.Errorf(\"got stats.TCP.CurrentConnected.Value() = %v, want = %v\", got, gotConnected)\n+ }\n+\n+ // Ack and send FIN as well.\n+ c.SendPacket(nil, &context.Headers{\n+ SrcPort: context.TestPort,\n+ DstPort: c.Port,\n+ Flags: header.TCPFlagAck | header.TCPFlagFin,\n+ SeqNum: 790,\n+ AckNum: c.IRS.Add(2),\n+ RcvWnd: 30000,\n+ })\n+\n+ // Check that the stack acks the FIN.\n+ checker.IPv4(t, c.GetPacket(),\n+ checker.PayloadLen(header.TCPMinimumSize),\n+ checker.TCP(\n+ checker.DstPort(context.TestPort),\n+ checker.SeqNum(uint32(c.IRS)+2),\n+ checker.AckNum(791),\n+ checker.TCPFlags(header.TCPFlagAck),\n+ ),\n+ )\n+\n+ // Wait for the TIME-WAIT state to transition to CLOSED.\n+ time.Sleep(1 * time.Second)\n+\n+ if got := c.Stack().Stats().TCP.CurrentEstablished.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentEstablished.Value() = %v, want = 0\", got)\n+ }\n+ if got := c.Stack().Stats().TCP.CurrentConnected.Value(); got != 0 {\n+ t.Errorf(\"got stats.TCP.CurrentConnected.Value() = %v, want = 0\", got)\n+ }\n+}\n+\n// TestClosingWithEnqueuedSegments tests handling of still enqueued segments\n// when the endpoint transitions to StateClose. The in-flight segments would be\n// re-enqueued to a any listening endpoint.\n" } ]
Go
Apache License 2.0
google/gvisor
Add a new TCP stat for current open connections. Such a stat accounts for all connections that are currently established and not yet transitioned to close state. Also fix bug in double increment of CurrentEstablished stat. Fixes #1579 PiperOrigin-RevId: 290827365
259,891
21.01.2020 16:51:17
28,800
538053538dfb378aa8bc512d484ea305177e617b
Adding serialization.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -196,7 +196,9 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\n}\nfunc marshalMatcher(matcher iptables.Matcher) []byte {\n- switch matcher.(type) {\n+ switch m := matcher.(type) {\n+ case *iptables.UDPMatcher:\n+ return marshalUDPMatcher(m)\ndefault:\n// TODO(gvisor.dev/issue/170): We don't support any matchers\n// yet, so any call to marshalMatcher will panic.\n@@ -204,6 +206,31 @@ func marshalMatcher(matcher iptables.Matcher) []byte {\n}\n}\n+func marshalUDPMatcher(matcher *iptables.UDPMatcher) []byte {\n+ type udpMatch struct {\n+ linux.XTEntryMatch\n+ linux.XTUDP\n+ }\n+ linuxMatcher := udpMatch{\n+ XTEntryMatch: linux.XTEntryMatch{\n+ MatchSize: linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP,\n+ // Name: \"udp\",\n+ },\n+ XTUDP: linux.XTUDP{\n+ SourcePortStart: matcher.Data.SourcePortStart,\n+ SourcePortEnd: matcher.Data.SourcePortEnd,\n+ DestinationPortStart: matcher.Data.DestinationPortStart,\n+ DestinationPortEnd: matcher.Data.DestinationPortEnd,\n+ InverseFlags: matcher.Data.InverseFlags,\n+ },\n+ }\n+ copy(linuxMatcher.Name[:], \"udp\")\n+\n+ var buf [linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP]byte\n+ binary.Marshal(buf[:], usermem.ByteOrder, linuxMatcher)\n+ return buf[:]\n+}\n+\nfunc marshalTarget(target iptables.Target) []byte {\nswitch target.(type) {\ncase iptables.UnconditionalAcceptTarget:\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/udp_matcher.go", "new_path": "pkg/tcpip/iptables/udp_matcher.go", "diff": "@@ -24,7 +24,7 @@ import (\n)\ntype UDPMatcher struct {\n- data UDPMatcherData\n+ Data UDPMatcherData\n// tablename string\n// unsigned int matchsize;\n@@ -62,11 +62,11 @@ func NewUDPMatcher(filter IPHeaderFilter, data UDPMatcherData) (Matcher, error)\nlog.Warningf(\"UDP matching is only valid for protocol %d.\", header.UDPProtocolNumber)\n}\n- return &UDPMatcher{data: data}, nil\n+ return &UDPMatcher{Data: data}, nil\n}\n// TODO: Check xt_tcpudp.c. Need to check for same things (e.g. fragments).\n-func (tm *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\n+func (um *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName string) (bool, bool) {\nlog.Infof(\"UDPMatcher called from: %s\", string(debug.Stack()))\nnetHeader := header.IPv4(pkt.NetworkHeader)\n@@ -114,12 +114,12 @@ func (tm *UDPMatcher) Match(hook Hook, pkt tcpip.PacketBuffer, interfaceName str\ndestinationPort := udpHeader.DestinationPort()\nlog.Infof(\"UDPMatcher: sport and dport are %d and %d. sports and dport start and end are (%d, %d) and (%d, %d)\",\nudpHeader.SourcePort(), udpHeader.DestinationPort(),\n- tm.data.SourcePortStart, tm.data.SourcePortEnd,\n- tm.data.DestinationPortStart, tm.data.DestinationPortEnd)\n- if sourcePort < tm.data.SourcePortStart || tm.data.SourcePortEnd < sourcePort {\n+ um.Data.SourcePortStart, um.Data.SourcePortEnd,\n+ um.Data.DestinationPortStart, um.Data.DestinationPortEnd)\n+ if sourcePort < um.Data.SourcePortStart || um.Data.SourcePortEnd < sourcePort {\nreturn false, false\n}\n- if destinationPort < tm.data.DestinationPortStart || tm.data.DestinationPortEnd < destinationPort {\n+ if destinationPort < um.Data.DestinationPortStart || um.Data.DestinationPortEnd < destinationPort {\nreturn false, false\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Adding serialization.
259,854
21.01.2020 16:59:24
28,800
1effdc091b441c4b1ada4327c1422cd360f80f98
TMutex based on sync.Mutex. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sync/BUILD", "new_path": "pkg/sync/BUILD", "diff": "@@ -38,6 +38,7 @@ go_library(\n\"race_unsafe.go\",\n\"seqcount.go\",\n\"syncutil.go\",\n+ \"tmutex_unsafe.go\",\n],\nimportpath = \"gvisor.dev/gvisor/pkg/sync\",\n)\n@@ -48,6 +49,7 @@ go_test(\nsrcs = [\n\"downgradable_rwmutex_test.go\",\n\"seqcount_test.go\",\n+ \"tmutex_test.go\",\n],\nembed = [\":sync\"],\n)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sync/tmutex_test.go", "diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Use of this source code is governed by a BSD-style\n+// license that can be found in the LICENSE file.\n+\n+package sync\n+\n+import (\n+ \"sync\"\n+ \"testing\"\n+ \"unsafe\"\n+)\n+\n+// TestStructSize verifies that syncMutex's size hasn't drifted from the\n+// standard library's version.\n+//\n+// The correctness of this package relies on these remaining in sync.\n+func TestStructSize(t *testing.T) {\n+ const (\n+ got = unsafe.Sizeof(syncMutex{})\n+ want = unsafe.Sizeof(sync.Mutex{})\n+ )\n+ if got != want {\n+ t.Errorf(\"got sizeof(syncMutex) = %d, want = sizeof(sync.Mutex) = %d\", got, want)\n+ }\n+}\n+\n+// TestFieldValues verifies that the semantics of syncMutex.state from the\n+// standard library's implementation.\n+//\n+// The correctness of this package relies on these remaining in sync.\n+func TestFieldValues(t *testing.T) {\n+ var m TMutex\n+ m.Lock()\n+ if got := *m.state(); got != mutexLocked {\n+ t.Errorf(\"got locked sync.Mutex.state = %d, want = %d\", got, mutexLocked)\n+ }\n+ m.Unlock()\n+ if got := *m.state(); got != mutexUnlocked {\n+ t.Errorf(\"got unlocked sync.Mutex.state = %d, want = %d\", got, mutexUnlocked)\n+ }\n+}\n+\n+func TestDoubleTryLock(t *testing.T) {\n+ var m TMutex\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock\")\n+ }\n+ if m.TryLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestTryLockAfterLock(t *testing.T) {\n+ var m TMutex\n+ m.Lock()\n+ if m.TryLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestTryLockUnlock(t *testing.T) {\n+ var m TMutex\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock\")\n+ }\n+ m.Unlock()\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock after unlock\")\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sync/tmutex_unsafe.go", "diff": "+// Copyright 2019 The gVisor Authors.\n+//\n+// Use of this source code is governed by a BSD-style\n+// license that can be found in the LICENSE file.\n+\n+// +build go1.13\n+// +build !go1.15\n+\n+// When updating the build constraint (above), check that syncMutex matches the\n+// standard library sync.Mutex definition.\n+\n+package sync\n+\n+import (\n+ \"sync\"\n+ \"sync/atomic\"\n+ \"unsafe\"\n+)\n+\n+// TMutex is a try lock.\n+type TMutex struct {\n+ sync.Mutex\n+}\n+\n+type syncMutex struct {\n+ state int32\n+ sema uint32\n+}\n+\n+func (m *TMutex) state() *int32 {\n+ return &(*syncMutex)(unsafe.Pointer(&m.Mutex)).state\n+}\n+\n+const (\n+ mutexUnlocked = 0\n+ mutexLocked = 1\n+)\n+\n+// TryLock tries to aquire the mutex. It returns true if it succeeds and false\n+// otherwise. TryLock does not block.\n+func (m *TMutex) TryLock() bool {\n+ if atomic.CompareAndSwapInt32(m.state(), mutexUnlocked, mutexLocked) {\n+ if RaceEnabled {\n+ RaceAcquire(unsafe.Pointer(&m.Mutex))\n+ }\n+ return true\n+ }\n+ return false\n+}\n" } ]
Go
Apache License 2.0
google/gvisor
TMutex based on sync.Mutex. Updates #231 PiperOrigin-RevId: 290854399
259,854
21.01.2020 18:34:24
28,800
d0e75f2bef4e16356693987db6ae6bbdce749618
Add trylock support to DowngradableRWMutex. Updates
[ { "change_type": "MODIFY", "old_path": "pkg/sync/downgradable_rwmutex_test.go", "new_path": "pkg/sync/downgradable_rwmutex_test.go", "diff": "@@ -148,3 +148,58 @@ func TestDowngradableRWMutex(t *testing.T) {\nHammerDowngradableRWMutex(10, 10, n)\nHammerDowngradableRWMutex(10, 5, n)\n}\n+\n+func TestRWDoubleTryLock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock\")\n+ }\n+ if m.TryLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestRWTryLockAfterLock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ m.Lock()\n+ if m.TryLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestRWTryLockUnlock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock\")\n+ }\n+ m.Unlock()\n+ if !m.TryLock() {\n+ t.Fatal(\"failed to aquire lock after unlock\")\n+ }\n+}\n+\n+func TestTryRLockAfterLock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ m.Lock()\n+ if m.TryRLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestTryLockAfterRLock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ m.RLock()\n+ if m.TryLock() {\n+ t.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n+ }\n+}\n+\n+func TestDoubleTryRLock(t *testing.T) {\n+ var m DowngradableRWMutex\n+ if !m.TryRLock() {\n+ t.Fatal(\"failed to aquire lock\")\n+ }\n+ if !m.TryRLock() {\n+ t.Fatal(\"failed to read aquire read locked lock\")\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/downgradable_rwmutex_unsafe.go", "new_path": "pkg/sync/downgradable_rwmutex_unsafe.go", "diff": "package sync\nimport (\n- \"sync\"\n\"sync/atomic\"\n\"unsafe\"\n)\n@@ -30,10 +29,10 @@ func runtimeSemacquire(s *uint32)\n//go:linkname runtimeSemrelease sync.runtime_Semrelease\nfunc runtimeSemrelease(s *uint32, handoff bool, skipframes int)\n-// DowngradableRWMutex is identical to sync.RWMutex, but adds the DowngradeLock\n-// method.\n+// DowngradableRWMutex is identical to sync.RWMutex, but adds the DowngradeLock,\n+// TryLock and TryRLock methods.\ntype DowngradableRWMutex struct {\n- w sync.Mutex // held if there are pending writers\n+ w TMutex // held if there are pending writers\nwriterSem uint32 // semaphore for writers to wait for completing readers\nreaderSem uint32 // semaphore for readers to wait for completing writers\nreaderCount int32 // number of pending readers\n@@ -42,6 +41,31 @@ type DowngradableRWMutex struct {\nconst rwmutexMaxReaders = 1 << 30\n+// TryRLock locks rw for reading. It returns true if it succeeds and false\n+// otherwise. It does not block.\n+func (rw *DowngradableRWMutex) TryRLock() bool {\n+ if RaceEnabled {\n+ RaceDisable()\n+ }\n+ for {\n+ rc := atomic.LoadInt32(&rw.readerCount)\n+ if rc < 0 {\n+ if RaceEnabled {\n+ RaceEnable()\n+ }\n+ return false\n+ }\n+ if !atomic.CompareAndSwapInt32(&rw.readerCount, rc, rc+1) {\n+ continue\n+ }\n+ if RaceEnabled {\n+ RaceEnable()\n+ RaceAcquire(unsafe.Pointer(&rw.readerSem))\n+ }\n+ return true\n+ }\n+}\n+\n// RLock locks rw for reading.\nfunc (rw *DowngradableRWMutex) RLock() {\nif RaceEnabled {\n@@ -78,6 +102,34 @@ func (rw *DowngradableRWMutex) RUnlock() {\n}\n}\n+// TryLock locks rw for writing. It returns true if it succeeds and false\n+// otherwise. It does not block.\n+func (rw *DowngradableRWMutex) TryLock() bool {\n+ if RaceEnabled {\n+ RaceDisable()\n+ }\n+ // First, resolve competition with other writers.\n+ if !rw.w.TryLock() {\n+ if RaceEnabled {\n+ RaceEnable()\n+ }\n+ return false\n+ }\n+ // Only proceed if there are no readers.\n+ if !atomic.CompareAndSwapInt32(&rw.readerCount, 0, -rwmutexMaxReaders) {\n+ rw.w.Unlock()\n+ if RaceEnabled {\n+ RaceEnable()\n+ }\n+ return false\n+ }\n+ if RaceEnabled {\n+ RaceEnable()\n+ RaceAcquire(unsafe.Pointer(&rw.writerSem))\n+ }\n+ return true\n+}\n+\n// Lock locks rw for writing.\nfunc (rw *DowngradableRWMutex) Lock() {\nif RaceEnabled {\n" } ]
Go
Apache License 2.0
google/gvisor
Add trylock support to DowngradableRWMutex. Updates #231 PiperOrigin-RevId: 290868875
259,854
21.01.2020 19:23:26
28,800
6a59e7f510a7b12f8b3bd768dfe569033ef07d30
Rename DowngradableRWMutex to RWmutex. Also renames TMutex to Mutex. These custom mutexes aren't any worse than the standard library versions (same code), so having both seems redundant.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fs/overlay.go", "new_path": "pkg/sentry/fs/overlay.go", "diff": "@@ -198,7 +198,7 @@ type overlayEntry struct {\nupper *Inode\n// dirCacheMu protects dirCache.\n- dirCacheMu sync.DowngradableRWMutex `state:\"nosave\"`\n+ dirCacheMu sync.RWMutex `state:\"nosave\"`\n// dirCache is cache of DentAttrs from upper and lower Inodes.\ndirCache *SortedDentryMap\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/mm/mm.go", "new_path": "pkg/sentry/mm/mm.go", "diff": "@@ -80,7 +80,7 @@ type MemoryManager struct {\nusers int32\n// mappingMu is analogous to Linux's struct mm_struct::mmap_sem.\n- mappingMu sync.DowngradableRWMutex `state:\"nosave\"`\n+ mappingMu sync.RWMutex `state:\"nosave\"`\n// vmas stores virtual memory areas. Since vmas are stored by value,\n// clients should usually use vmaIterator.ValuePtr() instead of\n@@ -123,7 +123,7 @@ type MemoryManager struct {\n// activeMu is loosely analogous to Linux's struct\n// mm_struct::page_table_lock.\n- activeMu sync.DowngradableRWMutex `state:\"nosave\"`\n+ activeMu sync.RWMutex `state:\"nosave\"`\n// pmas stores platform mapping areas used to implement vmas. Since pmas\n// are stored by value, clients should usually use pmaIterator.ValuePtr()\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/aliases.go", "new_path": "pkg/sync/aliases.go", "diff": "@@ -11,12 +11,6 @@ import (\n// Aliases of standard library types.\ntype (\n- // Mutex is an alias of sync.Mutex.\n- Mutex = sync.Mutex\n-\n- // RWMutex is an alias of sync.RWMutex.\n- RWMutex = sync.RWMutex\n-\n// Cond is an alias of sync.Cond.\nCond = sync.Cond\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/downgradable_rwmutex_test.go", "new_path": "pkg/sync/downgradable_rwmutex_test.go", "diff": "@@ -18,7 +18,7 @@ import (\n\"testing\"\n)\n-func parallelReader(m *DowngradableRWMutex, clocked, cunlock, cdone chan bool) {\n+func parallelReader(m *RWMutex, clocked, cunlock, cdone chan bool) {\nm.RLock()\nclocked <- true\n<-cunlock\n@@ -28,7 +28,7 @@ func parallelReader(m *DowngradableRWMutex, clocked, cunlock, cdone chan bool) {\nfunc doTestParallelReaders(numReaders, gomaxprocs int) {\nruntime.GOMAXPROCS(gomaxprocs)\n- var m DowngradableRWMutex\n+ var m RWMutex\nclocked := make(chan bool)\ncunlock := make(chan bool)\ncdone := make(chan bool)\n@@ -55,7 +55,7 @@ func TestParallelReaders(t *testing.T) {\ndoTestParallelReaders(4, 2)\n}\n-func reader(rwm *DowngradableRWMutex, numIterations int, activity *int32, cdone chan bool) {\n+func reader(rwm *RWMutex, numIterations int, activity *int32, cdone chan bool) {\nfor i := 0; i < numIterations; i++ {\nrwm.RLock()\nn := atomic.AddInt32(activity, 1)\n@@ -70,7 +70,7 @@ func reader(rwm *DowngradableRWMutex, numIterations int, activity *int32, cdone\ncdone <- true\n}\n-func writer(rwm *DowngradableRWMutex, numIterations int, activity *int32, cdone chan bool) {\n+func writer(rwm *RWMutex, numIterations int, activity *int32, cdone chan bool) {\nfor i := 0; i < numIterations; i++ {\nrwm.Lock()\nn := atomic.AddInt32(activity, 10000)\n@@ -85,7 +85,7 @@ func writer(rwm *DowngradableRWMutex, numIterations int, activity *int32, cdone\ncdone <- true\n}\n-func downgradingWriter(rwm *DowngradableRWMutex, numIterations int, activity *int32, cdone chan bool) {\n+func downgradingWriter(rwm *RWMutex, numIterations int, activity *int32, cdone chan bool) {\nfor i := 0; i < numIterations; i++ {\nrwm.Lock()\nn := atomic.AddInt32(activity, 10000)\n@@ -112,7 +112,7 @@ func HammerDowngradableRWMutex(gomaxprocs, numReaders, numIterations int) {\nruntime.GOMAXPROCS(gomaxprocs)\n// Number of active readers + 10000 * number of active writers.\nvar activity int32\n- var rwm DowngradableRWMutex\n+ var rwm RWMutex\ncdone := make(chan bool)\ngo writer(&rwm, numIterations, &activity, cdone)\ngo downgradingWriter(&rwm, numIterations, &activity, cdone)\n@@ -150,56 +150,56 @@ func TestDowngradableRWMutex(t *testing.T) {\n}\nfunc TestRWDoubleTryLock(t *testing.T) {\n- var m DowngradableRWMutex\n- if !m.TryLock() {\n+ var rwm RWMutex\n+ if !rwm.TryLock() {\nt.Fatal(\"failed to aquire lock\")\n}\n- if m.TryLock() {\n+ if rwm.TryLock() {\nt.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n}\n}\nfunc TestRWTryLockAfterLock(t *testing.T) {\n- var m DowngradableRWMutex\n- m.Lock()\n- if m.TryLock() {\n+ var rwm RWMutex\n+ rwm.Lock()\n+ if rwm.TryLock() {\nt.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n}\n}\nfunc TestRWTryLockUnlock(t *testing.T) {\n- var m DowngradableRWMutex\n- if !m.TryLock() {\n+ var rwm RWMutex\n+ if !rwm.TryLock() {\nt.Fatal(\"failed to aquire lock\")\n}\n- m.Unlock()\n- if !m.TryLock() {\n+ rwm.Unlock()\n+ if !rwm.TryLock() {\nt.Fatal(\"failed to aquire lock after unlock\")\n}\n}\nfunc TestTryRLockAfterLock(t *testing.T) {\n- var m DowngradableRWMutex\n- m.Lock()\n- if m.TryRLock() {\n+ var rwm RWMutex\n+ rwm.Lock()\n+ if rwm.TryRLock() {\nt.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n}\n}\nfunc TestTryLockAfterRLock(t *testing.T) {\n- var m DowngradableRWMutex\n- m.RLock()\n- if m.TryLock() {\n+ var rwm RWMutex\n+ rwm.RLock()\n+ if rwm.TryLock() {\nt.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n}\n}\nfunc TestDoubleTryRLock(t *testing.T) {\n- var m DowngradableRWMutex\n- if !m.TryRLock() {\n+ var rwm RWMutex\n+ if !rwm.TryRLock() {\nt.Fatal(\"failed to aquire lock\")\n}\n- if !m.TryRLock() {\n+ if !rwm.TryRLock() {\nt.Fatal(\"failed to read aquire read locked lock\")\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/downgradable_rwmutex_unsafe.go", "new_path": "pkg/sync/downgradable_rwmutex_unsafe.go", "diff": "@@ -29,10 +29,10 @@ func runtimeSemacquire(s *uint32)\n//go:linkname runtimeSemrelease sync.runtime_Semrelease\nfunc runtimeSemrelease(s *uint32, handoff bool, skipframes int)\n-// DowngradableRWMutex is identical to sync.RWMutex, but adds the DowngradeLock,\n+// RWMutex is identical to sync.RWMutex, but adds the DowngradeLock,\n// TryLock and TryRLock methods.\n-type DowngradableRWMutex struct {\n- w TMutex // held if there are pending writers\n+type RWMutex struct {\n+ w Mutex // held if there are pending writers\nwriterSem uint32 // semaphore for writers to wait for completing readers\nreaderSem uint32 // semaphore for readers to wait for completing writers\nreaderCount int32 // number of pending readers\n@@ -43,7 +43,7 @@ const rwmutexMaxReaders = 1 << 30\n// TryRLock locks rw for reading. It returns true if it succeeds and false\n// otherwise. It does not block.\n-func (rw *DowngradableRWMutex) TryRLock() bool {\n+func (rw *RWMutex) TryRLock() bool {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -67,7 +67,7 @@ func (rw *DowngradableRWMutex) TryRLock() bool {\n}\n// RLock locks rw for reading.\n-func (rw *DowngradableRWMutex) RLock() {\n+func (rw *RWMutex) RLock() {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -82,14 +82,14 @@ func (rw *DowngradableRWMutex) RLock() {\n}\n// RUnlock undoes a single RLock call.\n-func (rw *DowngradableRWMutex) RUnlock() {\n+func (rw *RWMutex) RUnlock() {\nif RaceEnabled {\nRaceReleaseMerge(unsafe.Pointer(&rw.writerSem))\nRaceDisable()\n}\nif r := atomic.AddInt32(&rw.readerCount, -1); r < 0 {\nif r+1 == 0 || r+1 == -rwmutexMaxReaders {\n- panic(\"RUnlock of unlocked DowngradableRWMutex\")\n+ panic(\"RUnlock of unlocked RWMutex\")\n}\n// A writer is pending.\nif atomic.AddInt32(&rw.readerWait, -1) == 0 {\n@@ -104,7 +104,7 @@ func (rw *DowngradableRWMutex) RUnlock() {\n// TryLock locks rw for writing. It returns true if it succeeds and false\n// otherwise. It does not block.\n-func (rw *DowngradableRWMutex) TryLock() bool {\n+func (rw *RWMutex) TryLock() bool {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -131,7 +131,7 @@ func (rw *DowngradableRWMutex) TryLock() bool {\n}\n// Lock locks rw for writing.\n-func (rw *DowngradableRWMutex) Lock() {\n+func (rw *RWMutex) Lock() {\nif RaceEnabled {\nRaceDisable()\n}\n@@ -150,7 +150,7 @@ func (rw *DowngradableRWMutex) Lock() {\n}\n// Unlock unlocks rw for writing.\n-func (rw *DowngradableRWMutex) Unlock() {\n+func (rw *RWMutex) Unlock() {\nif RaceEnabled {\nRaceRelease(unsafe.Pointer(&rw.writerSem))\nRaceRelease(unsafe.Pointer(&rw.readerSem))\n@@ -159,7 +159,7 @@ func (rw *DowngradableRWMutex) Unlock() {\n// Announce to readers there is no active writer.\nr := atomic.AddInt32(&rw.readerCount, rwmutexMaxReaders)\nif r >= rwmutexMaxReaders {\n- panic(\"Unlock of unlocked DowngradableRWMutex\")\n+ panic(\"Unlock of unlocked RWMutex\")\n}\n// Unblock blocked readers, if any.\nfor i := 0; i < int(r); i++ {\n@@ -173,7 +173,7 @@ func (rw *DowngradableRWMutex) Unlock() {\n}\n// DowngradeLock atomically unlocks rw for writing and locks it for reading.\n-func (rw *DowngradableRWMutex) DowngradeLock() {\n+func (rw *RWMutex) DowngradeLock() {\nif RaceEnabled {\nRaceRelease(unsafe.Pointer(&rw.readerSem))\nRaceDisable()\n@@ -181,7 +181,7 @@ func (rw *DowngradableRWMutex) DowngradeLock() {\n// Announce to readers there is no active writer and one additional reader.\nr := atomic.AddInt32(&rw.readerCount, rwmutexMaxReaders+1)\nif r >= rwmutexMaxReaders+1 {\n- panic(\"DowngradeLock of unlocked DowngradableRWMutex\")\n+ panic(\"DowngradeLock of unlocked RWMutex\")\n}\n// Unblock blocked readers, if any. Note that this loop starts as 1 since r\n// includes this goroutine.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/tmutex_test.go", "new_path": "pkg/sync/tmutex_test.go", "diff": "@@ -30,7 +30,7 @@ func TestStructSize(t *testing.T) {\n//\n// The correctness of this package relies on these remaining in sync.\nfunc TestFieldValues(t *testing.T) {\n- var m TMutex\n+ var m Mutex\nm.Lock()\nif got := *m.state(); got != mutexLocked {\nt.Errorf(\"got locked sync.Mutex.state = %d, want = %d\", got, mutexLocked)\n@@ -42,7 +42,7 @@ func TestFieldValues(t *testing.T) {\n}\nfunc TestDoubleTryLock(t *testing.T) {\n- var m TMutex\n+ var m Mutex\nif !m.TryLock() {\nt.Fatal(\"failed to aquire lock\")\n}\n@@ -52,7 +52,7 @@ func TestDoubleTryLock(t *testing.T) {\n}\nfunc TestTryLockAfterLock(t *testing.T) {\n- var m TMutex\n+ var m Mutex\nm.Lock()\nif m.TryLock() {\nt.Fatal(\"unexpectedly succeeded in aquiring locked mutex\")\n@@ -60,7 +60,7 @@ func TestTryLockAfterLock(t *testing.T) {\n}\nfunc TestTryLockUnlock(t *testing.T) {\n- var m TMutex\n+ var m Mutex\nif !m.TryLock() {\nt.Fatal(\"failed to aquire lock\")\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sync/tmutex_unsafe.go", "new_path": "pkg/sync/tmutex_unsafe.go", "diff": "@@ -17,8 +17,8 @@ import (\n\"unsafe\"\n)\n-// TMutex is a try lock.\n-type TMutex struct {\n+// Mutex is a try lock.\n+type Mutex struct {\nsync.Mutex\n}\n@@ -27,7 +27,7 @@ type syncMutex struct {\nsema uint32\n}\n-func (m *TMutex) state() *int32 {\n+func (m *Mutex) state() *int32 {\nreturn &(*syncMutex)(unsafe.Pointer(&m.Mutex)).state\n}\n@@ -38,7 +38,7 @@ const (\n// TryLock tries to aquire the mutex. It returns true if it succeeds and false\n// otherwise. TryLock does not block.\n-func (m *TMutex) TryLock() bool {\n+func (m *Mutex) TryLock() bool {\nif atomic.CompareAndSwapInt32(m.state(), mutexUnlocked, mutexLocked) {\nif RaceEnabled {\nRaceAcquire(unsafe.Pointer(&m.Mutex))\n" } ]
Go
Apache License 2.0
google/gvisor
Rename DowngradableRWMutex to RWmutex. Also renames TMutex to Mutex. These custom mutexes aren't any worse than the standard library versions (same code), so having both seems redundant. PiperOrigin-RevId: 290873587
259,974
22.01.2020 05:51:57
0
d59a3cc959cb14b0bed14b62e33ee4178b89b346
Enable fault() syscall test on arm64.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fault.cc", "new_path": "test/syscalls/linux/fault.cc", "diff": "@@ -37,6 +37,9 @@ int GetPcFromUcontext(ucontext_t* uc, uintptr_t* pc) {\n#elif defined(__i386__)\n*pc = uc->uc_mcontext.gregs[REG_EIP];\nreturn 1;\n+#elif defined(__aarch64__)\n+ *pc = uc->uc_mcontext.pc;\n+ return 1;\n#else\nreturn 0;\n#endif\n" } ]
Go
Apache License 2.0
google/gvisor
Enable fault() syscall test on arm64. Signed-off-by: Haibo Xu <[email protected]> Change-Id: I9b2b2e0d84946c10cf136abeef6c60642fa3b6ec
259,884
22.01.2020 11:31:11
-32,400
639b25ed4b66ba7c80e20d698bc32b2b40ba350f
Fix typo: 'hte' -> 'the'
[ { "change_type": "MODIFY", "old_path": "content/docs/tutorials/cni.md", "new_path": "content/docs/tutorials/cni.md", "diff": "@@ -93,7 +93,7 @@ sudo ip netns add ${CNI_CONTAINERID}\nNext, run the bridge and loopback plugins to apply the configuration that was\ncreated earlier to the namespace. Each plugin outputs some JSON indicating the\n-results of executing hte plugin. For example, The bridge plugin's response\n+results of executing the plugin. For example, The bridge plugin's response\nincludes the IP address assigned to the ethernet device created in the network\nnamespace. Take note of the IP address for use later.\n" } ]
Go
Apache License 2.0
google/gvisor
Fix typo: 'hte' -> 'the'
259,891
22.01.2020 10:23:44
28,800
747137c120bca27aeb259817d30ef60e01521621
Address GitHub comments.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/iptables/types.go", "new_path": "pkg/tcpip/iptables/types.go", "diff": "@@ -153,7 +153,7 @@ func (table *Table) SetMetadata(metadata interface{}) {\n// packets this rule applies to. If there are no matchers in the rule, it\n// applies to any packet.\ntype Rule struct {\n- // IPHeaderFilter holds basic IP filtering fields common to every rule.\n+ // Filter holds basic IP filtering fields common to every rule.\nFilter IPHeaderFilter\n// Matchers is the list of matchers for this rule.\n" } ]
Go
Apache License 2.0
google/gvisor
Address GitHub comments.
259,885
22.01.2020 12:27:16
28,800
5ab1213a6c405071546c783d6d93b4e9af52842e
Move VFS2 handling of FD readability/writability to vfs.FileDescription.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/ext/inode.go", "new_path": "pkg/sentry/fsimpl/ext/inode.go", "diff": "@@ -157,7 +157,9 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nswitch in.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\n+ if err := fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\nreturn &fd.vfsfd, nil\ncase *directory:\n// Can't open directories writably. This check is not necessary for a read\n@@ -166,7 +168,9 @@ func (in *inode) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*v\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\n+ if err := fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\nreturn &fd.vfsfd, nil\ncase *symlink:\nif flags&linux.O_PATH == 0 {\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "new_path": "pkg/sentry/fsimpl/kernfs/dynamic_bytes_file.go", "diff": "@@ -55,7 +55,9 @@ func (f *DynamicBytesFile) Init(creds *auth.Credentials, ino uint64, data vfs.Dy\n// Open implements Inode.Open.\nfunc (f *DynamicBytesFile) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*vfs.FileDescription, error) {\nfd := &DynamicBytesFD{}\n- fd.Init(rp.Mount(), vfsd, f.data, flags)\n+ if err := fd.Init(rp.Mount(), vfsd, f.data, flags); err != nil {\n+ return nil, err\n+ }\nreturn &fd.vfsfd, nil\n}\n@@ -80,10 +82,13 @@ type DynamicBytesFD struct {\n}\n// Init initializes a DynamicBytesFD.\n-func (fd *DynamicBytesFD) Init(m *vfs.Mount, d *vfs.Dentry, data vfs.DynamicBytesSource, flags uint32) {\n+func (fd *DynamicBytesFD) Init(m *vfs.Mount, d *vfs.Dentry, data vfs.DynamicBytesSource, flags uint32) error {\n+ if err := fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{}); err != nil {\n+ return err\n+ }\nfd.inode = d.Impl().(*Dentry).inode\nfd.SetDataSource(data)\n- fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n+ return nil\n}\n// Seek implements vfs.FileDescriptionImpl.Seek.\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go", "new_path": "pkg/sentry/fsimpl/kernfs/fd_impl_util.go", "diff": "@@ -43,9 +43,16 @@ type GenericDirectoryFD struct {\n}\n// Init initializes a GenericDirectoryFD.\n-func (fd *GenericDirectoryFD) Init(m *vfs.Mount, d *vfs.Dentry, children *OrderedChildren, flags uint32) {\n+func (fd *GenericDirectoryFD) Init(m *vfs.Mount, d *vfs.Dentry, children *OrderedChildren, flags uint32) error {\n+ if vfs.AccessTypesForOpenFlags(flags)&vfs.MayWrite != 0 {\n+ // Can't open directories for writing.\n+ return syserror.EISDIR\n+ }\n+ if err := fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{}); err != nil {\n+ return err\n+ }\nfd.children = children\n- fd.vfsfd.Init(fd, flags, m, d, &vfs.FileDescriptionOptions{})\n+ return nil\n}\n// VFSFileDescription returns a pointer to the vfs.FileDescription representing\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "new_path": "pkg/sentry/fsimpl/kernfs/kernfs_test.go", "diff": "@@ -115,7 +115,9 @@ func (fs *filesystem) newReadonlyDir(creds *auth.Credentials, mode linux.FileMod\nfunc (d *readonlyDir) Open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*vfs.FileDescription, error) {\nfd := &kernfs.GenericDirectoryFD{}\n- fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, flags)\n+ if err := fd.Init(rp.Mount(), vfsd, &d.OrderedChildren, flags); err != nil {\n+ return nil, err\n+ }\nreturn fd.VFSFileDescription(), nil\n}\n@@ -225,7 +227,9 @@ func TestReadStaticFile(t *testing.T) {\ndefer sys.Destroy()\npop := sys.PathOpAtRoot(\"file1\")\n- fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\n+ fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ })\nif err != nil {\nt.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n}\n@@ -258,7 +262,9 @@ func TestCreateNewFileInStaticDir(t *testing.T) {\n// Close the file. The file should persist.\nfd.DecRef()\n- fd, err = sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\n+ fd, err = sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ })\nif err != nil {\nt.Fatalf(\"OpenAt(pop:%+v) = %+v failed: %v\", pop, fd, err)\n}\n@@ -272,7 +278,9 @@ func TestDirFDReadWrite(t *testing.T) {\ndefer sys.Destroy()\npop := sys.PathOpAtRoot(\"/\")\n- fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{})\n+ fd, err := sys.VFS.OpenAt(sys.Ctx, sys.Creds, &pop, &vfs.OpenOptions{\n+ Flags: linux.O_RDONLY,\n+ })\nif err != nil {\nt.Fatalf(\"OpenAt for PathOperation %+v failed: %v\", pop, err)\n}\n@@ -282,7 +290,7 @@ func TestDirFDReadWrite(t *testing.T) {\nif _, err := fd.Read(sys.Ctx, usermem.BytesIOSequence([]byte{}), vfs.ReadOptions{}); err != syserror.EISDIR {\nt.Fatalf(\"Read for directory FD failed with unexpected error: %v\", err)\n}\n- if _, err := fd.Write(sys.Ctx, usermem.BytesIOSequence([]byte{}), vfs.WriteOptions{}); err != syserror.EISDIR {\n+ if _, err := fd.Write(sys.Ctx, usermem.BytesIOSequence([]byte{}), vfs.WriteOptions{}); err != syserror.EBADF {\nt.Fatalf(\"Write for directory FD failed with unexpected error: %v\", err)\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -337,19 +337,12 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\nreturn nil, err\n}\n}\n- mnt := rp.Mount()\nswitch impl := d.inode.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- fd.readable = vfs.MayReadFileWithOpenFlags(flags)\n- fd.writable = vfs.MayWriteFileWithOpenFlags(flags)\n- if fd.writable {\n- if err := mnt.CheckBeginWrite(); err != nil {\n+ if err := fd.vfsfd.Init(&fd, flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\nreturn nil, err\n}\n- // mnt.EndWrite() is called by regularFileFD.Release().\n- }\n- fd.vfsfd.Init(&fd, flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{})\nif flags&linux.O_TRUNC != 0 {\nimpl.mu.Lock()\nimpl.data.Truncate(0, impl.memFile)\n@@ -363,7 +356,9 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- fd.vfsfd.Init(&fd, flags, mnt, &d.vfsd, &vfs.FileDescriptionOptions{})\n+ if err := fd.vfsfd.Init(&fd, flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ return nil, err\n+ }\nreturn &fd.vfsfd, nil\ncase *symlink:\n// Can't open symlinks without O_PATH (which is unimplemented).\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "new_path": "pkg/sentry/fsimpl/tmpfs/named_pipe.go", "diff": "@@ -50,11 +50,10 @@ type namedPipeFD struct {\nfunc newNamedPipeFD(ctx context.Context, np *namedPipe, rp *vfs.ResolvingPath, vfsd *vfs.Dentry, flags uint32) (*vfs.FileDescription, error) {\nvar err error\nvar fd namedPipeFD\n- fd.VFSPipeFD, err = np.pipe.NewVFSPipeFD(ctx, rp, vfsd, &fd.vfsfd, flags)\n+ fd.VFSPipeFD, err = np.pipe.NewVFSPipeFD(ctx, vfsd, &fd.vfsfd, flags)\nif err != nil {\nreturn nil, err\n}\n- mnt := rp.Mount()\n- fd.vfsfd.Init(&fd, flags, mnt, vfsd, &vfs.FileDescriptionOptions{})\n+ fd.vfsfd.Init(&fd, flags, rp.Mount(), vfsd, &vfs.FileDescriptionOptions{})\nreturn &fd.vfsfd, nil\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "new_path": "pkg/sentry/fsimpl/tmpfs/regular_file.go", "diff": "@@ -101,10 +101,6 @@ func (rf *regularFile) truncate(size uint64) (bool, error) {\ntype regularFileFD struct {\nfileDescription\n- // These are immutable.\n- readable bool\n- writable bool\n-\n// off is the file offset. off is accessed using atomic memory operations.\n// offMu serializes operations that may mutate off.\noff int64\n@@ -113,16 +109,11 @@ type regularFileFD struct {\n// Release implements vfs.FileDescriptionImpl.Release.\nfunc (fd *regularFileFD) Release() {\n- if fd.writable {\n- fd.vfsfd.VirtualDentry().Mount().EndWrite()\n- }\n+ // noop\n}\n// PRead implements vfs.FileDescriptionImpl.PRead.\nfunc (fd *regularFileFD) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts vfs.ReadOptions) (int64, error) {\n- if !fd.readable {\n- return 0, syserror.EINVAL\n- }\nif offset < 0 {\nreturn 0, syserror.EINVAL\n}\n@@ -147,9 +138,6 @@ func (fd *regularFileFD) Read(ctx context.Context, dst usermem.IOSequence, opts\n// PWrite implements vfs.FileDescriptionImpl.PWrite.\nfunc (fd *regularFileFD) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts vfs.WriteOptions) (int64, error) {\n- if !fd.writable {\n- return 0, syserror.EINVAL\n- }\nif offset < 0 {\nreturn 0, syserror.EINVAL\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/kernel/pipe/vfs.go", "new_path": "pkg/sentry/kernel/pipe/vfs.go", "diff": "@@ -66,7 +66,7 @@ func NewVFSPipe(sizeBytes, atomicIOBytes int64) *VFSPipe {\n// for read and write will succeed both in blocking and nonblocking mode. POSIX\n// leaves this behavior undefined. This can be used to open a FIFO for writing\n// while there are no readers available.\" - fifo(7)\n-func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, rp *vfs.ResolvingPath, vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\n+func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\nvp.mu.Lock()\ndefer vp.mu.Unlock()\n@@ -76,7 +76,7 @@ func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, rp *vfs.ResolvingPath, vfsd\nreturn nil, syserror.EINVAL\n}\n- vfd, err := vp.open(rp, vfsd, vfsfd, flags)\n+ vfd, err := vp.open(vfsd, vfsfd, flags)\nif err != nil {\nreturn nil, err\n}\n@@ -118,19 +118,13 @@ func (vp *VFSPipe) NewVFSPipeFD(ctx context.Context, rp *vfs.ResolvingPath, vfsd\n}\n// Preconditions: vp.mu must be held.\n-func (vp *VFSPipe) open(rp *vfs.ResolvingPath, vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\n+func (vp *VFSPipe) open(vfsd *vfs.Dentry, vfsfd *vfs.FileDescription, flags uint32) (*VFSPipeFD, error) {\nvar fd VFSPipeFD\nfd.flags = flags\nfd.readable = vfs.MayReadFileWithOpenFlags(flags)\nfd.writable = vfs.MayWriteFileWithOpenFlags(flags)\nfd.vfsfd = vfsfd\nfd.pipe = &vp.pipe\n- if fd.writable {\n- // The corresponding Mount.EndWrite() is in VFSPipe.Release().\n- if err := rp.Mount().CheckBeginWrite(); err != nil {\n- return nil, err\n- }\n- }\nswitch {\ncase fd.readable && fd.writable:\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/file_description.go", "new_path": "pkg/sentry/vfs/file_description.go", "diff": "@@ -49,8 +49,23 @@ type FileDescription struct {\n// A reference is held on vd. vd is immutable.\nvd VirtualDentry\n+ // opts contains options passed to FileDescription.Init(). opts is\n+ // immutable.\nopts FileDescriptionOptions\n+ // readable is MayReadFileWithOpenFlags(statusFlags). readable is\n+ // immutable.\n+ //\n+ // readable is analogous to Linux's FMODE_READ.\n+ readable bool\n+\n+ // writable is MayWriteFileWithOpenFlags(statusFlags). If writable is true,\n+ // the FileDescription holds a write count on vd.mount. writable is\n+ // immutable.\n+ //\n+ // writable is analogous to Linux's FMODE_WRITE.\n+ writable bool\n+\n// impl is the FileDescriptionImpl associated with this Filesystem. impl is\n// immutable. This should be the last field in FileDescription.\nimpl FileDescriptionImpl\n@@ -77,10 +92,17 @@ type FileDescriptionOptions struct {\nUseDentryMetadata bool\n}\n-// Init must be called before first use of fd. It takes references on mnt and\n-// d. statusFlags is the initial file description status flags, which is\n-// usually the full set of flags passed to open(2).\n-func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) {\n+// Init must be called before first use of fd. If it succeeds, it takes\n+// references on mnt and d. statusFlags is the initial file description status\n+// flags, which is usually the full set of flags passed to open(2).\n+func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mnt *Mount, d *Dentry, opts *FileDescriptionOptions) error {\n+ writable := MayWriteFileWithOpenFlags(statusFlags)\n+ if writable {\n+ if err := mnt.CheckBeginWrite(); err != nil {\n+ return err\n+ }\n+ }\n+\nfd.refs = 1\nfd.statusFlags = statusFlags | linux.O_LARGEFILE\nfd.vd = VirtualDentry{\n@@ -89,7 +111,10 @@ func (fd *FileDescription) Init(impl FileDescriptionImpl, statusFlags uint32, mn\n}\nfd.vd.IncRef()\nfd.opts = *opts\n+ fd.readable = MayReadFileWithOpenFlags(statusFlags)\n+ fd.writable = writable\nfd.impl = impl\n+ return nil\n}\n// IncRef increments fd's reference count.\n@@ -117,6 +142,9 @@ func (fd *FileDescription) TryIncRef() bool {\nfunc (fd *FileDescription) DecRef() {\nif refs := atomic.AddInt64(&fd.refs, -1); refs == 0 {\nfd.impl.Release()\n+ if fd.writable {\n+ fd.vd.mount.EndWrite()\n+ }\nfd.vd.DecRef()\n} else if refs < 0 {\npanic(\"FileDescription.DecRef() called without holding a reference\")\n@@ -194,6 +222,16 @@ func (fd *FileDescription) SetStatusFlags(ctx context.Context, creds *auth.Crede\nreturn nil\n}\n+// IsReadable returns true if fd was opened for reading.\n+func (fd *FileDescription) IsReadable() bool {\n+ return fd.readable\n+}\n+\n+// IsWritable returns true if fd was opened for writing.\n+func (fd *FileDescription) IsWritable() bool {\n+ return fd.writable\n+}\n+\n// Impl returns the FileDescriptionImpl associated with fd.\nfunc (fd *FileDescription) Impl() FileDescriptionImpl {\nreturn fd.impl\n@@ -241,6 +279,8 @@ type FileDescriptionImpl interface {\n// Errors:\n//\n// - If opts.Flags specifies unsupported options, PRead returns EOPNOTSUPP.\n+ //\n+ // Preconditions: The FileDescription was opened for reading.\nPRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts ReadOptions) (int64, error)\n// Read is similar to PRead, but does not specify an offset.\n@@ -254,6 +294,8 @@ type FileDescriptionImpl interface {\n// Errors:\n//\n// - If opts.Flags specifies unsupported options, Read returns EOPNOTSUPP.\n+ //\n+ // Preconditions: The FileDescription was opened for reading.\nRead(ctx context.Context, dst usermem.IOSequence, opts ReadOptions) (int64, error)\n// PWrite writes src to the file, starting at the given offset, and returns\n@@ -268,6 +310,8 @@ type FileDescriptionImpl interface {\n//\n// - If opts.Flags specifies unsupported options, PWrite returns\n// EOPNOTSUPP.\n+ //\n+ // Preconditions: The FileDescription was opened for writing.\nPWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts WriteOptions) (int64, error)\n// Write is similar to PWrite, but does not specify an offset, which is\n@@ -281,6 +325,8 @@ type FileDescriptionImpl interface {\n// Errors:\n//\n// - If opts.Flags specifies unsupported options, Write returns EOPNOTSUPP.\n+ //\n+ // Preconditions: The FileDescription was opened for writing.\nWrite(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error)\n// IterDirents invokes cb on each entry in the directory represented by the\n@@ -411,11 +457,17 @@ func (fd *FileDescription) StatFS(ctx context.Context) (linux.Statfs, error) {\n// offset, and returns the number of bytes read. PRead is permitted to return\n// partial reads with a nil error.\nfunc (fd *FileDescription) PRead(ctx context.Context, dst usermem.IOSequence, offset int64, opts ReadOptions) (int64, error) {\n+ if !fd.readable {\n+ return 0, syserror.EBADF\n+ }\nreturn fd.impl.PRead(ctx, dst, offset, opts)\n}\n// Read is similar to PRead, but does not specify an offset.\nfunc (fd *FileDescription) Read(ctx context.Context, dst usermem.IOSequence, opts ReadOptions) (int64, error) {\n+ if !fd.readable {\n+ return 0, syserror.EBADF\n+ }\nreturn fd.impl.Read(ctx, dst, opts)\n}\n@@ -423,11 +475,17 @@ func (fd *FileDescription) Read(ctx context.Context, dst usermem.IOSequence, opt\n// offset, and returns the number of bytes written. PWrite is permitted to\n// return partial writes with a nil error.\nfunc (fd *FileDescription) PWrite(ctx context.Context, src usermem.IOSequence, offset int64, opts WriteOptions) (int64, error) {\n+ if !fd.writable {\n+ return 0, syserror.EBADF\n+ }\nreturn fd.impl.PWrite(ctx, src, offset, opts)\n}\n// Write is similar to PWrite, but does not specify an offset.\nfunc (fd *FileDescription) Write(ctx context.Context, src usermem.IOSequence, opts WriteOptions) (int64, error) {\n+ if !fd.writable {\n+ return 0, syserror.EBADF\n+ }\nreturn fd.impl.Write(ctx, src, opts)\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/permissions.go", "new_path": "pkg/sentry/vfs/permissions.go", "diff": "@@ -94,14 +94,13 @@ func GenericCheckPermissions(creds *auth.Credentials, ats AccessTypes, isDir boo\n// the set of accesses permitted for the opened file:\n//\n// - O_TRUNC causes MayWrite to be set in the returned AccessTypes (since it\n-// mutates the file), but does not permit the opened to write to the file\n+// mutates the file), but does not permit writing to the open file description\n// thereafter.\n//\n// - \"Linux reserves the special, nonstandard access mode 3 (binary 11) in\n// flags to mean: check for read and write permission on the file and return a\n// file descriptor that can't be used for reading or writing.\" - open(2). Thus\n-// AccessTypesForOpenFlags returns MayRead|MayWrite in this case, but\n-// filesystems are responsible for ensuring that access is denied.\n+// AccessTypesForOpenFlags returns MayRead|MayWrite in this case.\n//\n// Use May{Read,Write}FileWithOpenFlags() for these checks instead.\nfunc AccessTypesForOpenFlags(flags uint32) AccessTypes {\n" } ]
Go
Apache License 2.0
google/gvisor
Move VFS2 handling of FD readability/writability to vfs.FileDescription. PiperOrigin-RevId: 291006713
259,974
22.01.2020 06:22:18
0
49e84b10e5ed7f94e6cbe003b9f7268e8235bb08
Unify the kOLargeFile definition in syscall tests.
[ { "change_type": "MODIFY", "old_path": "test/syscalls/linux/fcntl.cc", "new_path": "test/syscalls/linux/fcntl.cc", "diff": "#include \"test/syscalls/linux/socket_test_util.h\"\n#include \"test/util/cleanup.h\"\n#include \"test/util/eventfd_util.h\"\n+#include \"test/util/fs_util.h\"\n#include \"test/util/multiprocess_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/save_util.h\"\n@@ -55,10 +56,6 @@ ABSL_FLAG(int32_t, socket_fd, -1,\nnamespace gvisor {\nnamespace testing {\n-// O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0\n-// because \"it isn't needed\", even though Linux can return it via F_GETFL.\n-constexpr int kOLargeFile = 00100000;\n-\nclass FcntlLockTest : public ::testing::Test {\npublic:\nvoid SetUp() override {\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/pipe.cc", "new_path": "test/syscalls/linux/pipe.cc", "diff": "#include \"absl/time/clock.h\"\n#include \"absl/time/time.h\"\n#include \"test/util/file_descriptor.h\"\n+#include \"test/util/fs_util.h\"\n#include \"test/util/posix_error.h\"\n#include \"test/util/temp_path.h\"\n#include \"test/util/test_util.h\"\n@@ -144,11 +145,10 @@ TEST_P(PipeTest, Flags) {\nif (IsNamedPipe()) {\n// May be stubbed to zero; define locally.\n- constexpr int kLargefile = 0100000;\nEXPECT_THAT(fcntl(rfd_.get(), F_GETFL),\n- SyscallSucceedsWithValue(kLargefile | O_RDONLY));\n+ SyscallSucceedsWithValue(kOLargeFile | O_RDONLY));\nEXPECT_THAT(fcntl(wfd_.get(), F_GETFL),\n- SyscallSucceedsWithValue(kLargefile | O_WRONLY));\n+ SyscallSucceedsWithValue(kOLargeFile | O_WRONLY));\n} else {\nEXPECT_THAT(fcntl(rfd_.get(), F_GETFL), SyscallSucceedsWithValue(O_RDONLY));\nEXPECT_THAT(fcntl(wfd_.get(), F_GETFL), SyscallSucceedsWithValue(O_WRONLY));\n" }, { "change_type": "MODIFY", "old_path": "test/syscalls/linux/proc.cc", "new_path": "test/syscalls/linux/proc.cc", "diff": "@@ -100,18 +100,6 @@ namespace {\n#define SUID_DUMP_ROOT 2\n#endif /* SUID_DUMP_ROOT */\n-// O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0\n-// because \"it isn't needed\", even though Linux can return it via F_GETFL.\n-#if defined(__x86_64__) || defined(__i386__)\n-constexpr int kOLargeFile = 00100000;\n-#elif __aarch64__\n-// The value originate from the Linux\n-// kernel's arch/arm64/include/uapi/asm/fcntl.h.\n-constexpr int kOLargeFile = 00400000;\n-#else\n-#error \"Unknown architecture\"\n-#endif\n-\n#if defined(__x86_64__) || defined(__i386__)\n// This list of \"required\" fields is taken from reading the file\n// arch/x86/kernel/cpu/proc.c and seeing which fields will be unconditionally\n" }, { "change_type": "MODIFY", "old_path": "test/util/fs_util.h", "new_path": "test/util/fs_util.h", "diff": "namespace gvisor {\nnamespace testing {\n+\n+// O_LARGEFILE as defined by Linux. glibc tries to be clever by setting it to 0\n+// because \"it isn't needed\", even though Linux can return it via F_GETFL.\n+#if defined(__x86_64__)\n+constexpr int kOLargeFile = 00100000;\n+#elif defined(__aarch64__)\n+constexpr int kOLargeFile = 00400000;\n+#else\n+#error \"Unknown architecture\"\n+#endif\n+\n// Returns a status or the current working directory.\nPosixErrorOr<std::string> GetCWD();\n" } ]
Go
Apache License 2.0
google/gvisor
Unify the kOLargeFile definition in syscall tests. Signed-off-by: Haibo Xu <[email protected]> Change-Id: Id9d6ae98305a4057d55d622ea4c3ac2228fea212
259,847
23.01.2020 10:58:18
28,800
98e83c444fa58669d45ecf162cf4bf48dce790d1
Try running kythe build on RBE. Also add our RBE project/instance to the --config=remote defaults.
[ { "change_type": "MODIFY", "old_path": ".bazelrc", "new_path": ".bazelrc", "diff": "@@ -20,6 +20,13 @@ build --stamp --workspace_status_command tools/workspace_status.sh\n# Enable remote execution so actions are performed on the remote systems.\nbuild:remote --remote_executor=grpcs://remotebuildexecution.googleapis.com\n+build:remote --project_id=gvisor-rbe\n+build:remote --remote_instance_name=projects/gvisor-rbe/instances/default_instance\n+# Enable authentication. This will pick up application default credentials by\n+# default. You can use --google_credentials=some_file.json to use a service\n+# account credential instead.\n+build:remote --google_default_credentials=true\n+build:remote --auth_scope=\"https://www.googleapis.com/auth/cloud-source-tools\"\n# Add a custom platform and toolchain that builds in a privileged docker\n# container, which is required by our syscall tests.\n@@ -27,25 +34,12 @@ build:remote --host_platform=//test:rbe_ubuntu1604\nbuild:remote --extra_toolchains=//test:cc-toolchain-clang-x86_64-default\nbuild:remote --extra_execution_platforms=//test:rbe_ubuntu1604\nbuild:remote --platforms=//test:rbe_ubuntu1604\n-\n-# Use default image for crosstool toolchain.\nbuild:remote --crosstool_top=@rbe_default//cc:toolchain\n-\n-# Default parallelism and timeout for remote jobs.\nbuild:remote --jobs=50\nbuild:remote --remote_timeout=3600\n-\n# RBE requires a strong hash function, such as SHA256.\nstartup --host_jvm_args=-Dbazel.DigestFunction=SHA256\n-# Enable authentication. This will pick up application default credentials by\n-# default. You can use --google_credentials=some_file.json to use a service\n-# account credential instead.\n-build:remote --google_default_credentials=true\n-\n-# Auth scope needed for authentication with RBE.\n-build:remote --auth_scope=\"https://www.googleapis.com/auth/cloud-source-tools\"\n-\n# Set flags for uploading to BES in order to view results in the Bazel Build\n# Results UI.\nbuild:results --bes_backend=\"buildeventservice.googleapis.com\"\n" }, { "change_type": "MODIFY", "old_path": "kokoro/kythe/generate_xrefs.sh", "new_path": "kokoro/kythe/generate_xrefs.sh", "diff": "@@ -25,7 +25,7 @@ bazel version\npython3 -V\n-readonly KYTHE_VERSION='v0.0.37'\n+readonly KYTHE_VERSION='v0.0.39'\nreadonly WORKDIR=\"$(mktemp -d)\"\nreadonly KYTHE_DIR=\"${WORKDIR}/kythe-${KYTHE_VERSION}\"\nif [[ -n \"$KOKORO_GIT_COMMIT\" ]]; then\n@@ -47,6 +47,7 @@ bazel \\\n--override_repository kythe_release=\"${KYTHE_DIR}\" \\\n--define=kythe_corpus=gvisor.dev \\\n--cxxopt=-std=c++17 \\\n+ --config=remote \\\n//...\n\"${KYTHE_DIR}/tools/kzip\" merge \\\n" }, { "change_type": "MODIFY", "old_path": "scripts/common_bazel.sh", "new_path": "scripts/common_bazel.sh", "diff": "@@ -32,18 +32,11 @@ declare -r BAZEL_FLAGS=(\n\"--keep_going\"\n\"--verbose_failures=true\"\n)\n-if [[ -v KOKORO_BAZEL_AUTH_CREDENTIAL ]] || [[ -v RBE_PROJECT_ID ]]; then\n- declare -r RBE_PROJECT_ID=\"${RBE_PROJECT_ID:-gvisor-rbe}\"\n- declare -r BAZEL_RBE_FLAGS=(\n- \"--config=remote\"\n- \"--project_id=${RBE_PROJECT_ID}\"\n- \"--remote_instance_name=projects/${RBE_PROJECT_ID}/instances/default_instance\"\n- )\n-fi\nif [[ -v KOKORO_BAZEL_AUTH_CREDENTIAL ]]; then\ndeclare -r BAZEL_RBE_AUTH_FLAGS=(\n\"--auth_credentials=${KOKORO_BAZEL_AUTH_CREDENTIAL}\"\n)\n+ declare -r BAZEL_RBE_FLAGS=(\"--config=remote\")\nfi\n# Wrap bazel.\n" } ]
Go
Apache License 2.0
google/gvisor
Try running kythe build on RBE. Also add our RBE project/instance to the --config=remote defaults. PiperOrigin-RevId: 291201426
259,881
23.01.2020 11:47:30
28,800
7a79715504e92be9fc9aebc12fbd65aa46049054
Check for EINTR from KVM_CREATE_VM The kernel may return EINTR from: kvm_create_vm kvm_init_mmu_notifier mmu_notifier_register do_mmu_notifier_register mm_take_all_locks Go 1.14's preemptive scheduling signals make hitting this much more likely.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/platform/kvm/kvm.go", "new_path": "pkg/sentry/platform/kvm/kvm.go", "diff": "@@ -62,10 +62,20 @@ func New(deviceFile *os.File) (*KVM, error) {\n}\n// Create a new VM fd.\n- vm, _, errno := syscall.RawSyscall(syscall.SYS_IOCTL, fd, _KVM_CREATE_VM, 0)\n+ var (\n+ vm uintptr\n+ errno syscall.Errno\n+ )\n+ for {\n+ vm, _, errno = syscall.Syscall(syscall.SYS_IOCTL, fd, _KVM_CREATE_VM, 0)\n+ if errno == syscall.EINTR {\n+ continue\n+ }\nif errno != 0 {\nreturn nil, fmt.Errorf(\"creating VM: %v\", errno)\n}\n+ break\n+ }\n// We are done with the device file.\ndeviceFile.Close()\n" } ]
Go
Apache License 2.0
google/gvisor
Check for EINTR from KVM_CREATE_VM The kernel may return EINTR from: kvm_create_vm kvm_init_mmu_notifier mmu_notifier_register do_mmu_notifier_register mm_take_all_locks Go 1.14's preemptive scheduling signals make hitting this much more likely. PiperOrigin-RevId: 291212669
259,847
24.01.2020 11:44:31
28,800
24cfbf4b981a76e46cab47650ef514835990b72e
Fix corpus_name to match our ingestion config[1].
[ { "change_type": "MODIFY", "old_path": "kokoro/kythe/generate_xrefs.sh", "new_path": "kokoro/kythe/generate_xrefs.sh", "diff": "set -ex\n-# Install the latest version of Bazel. The default on Kokoro images is out of\n-# date.\nif command -v use_bazel.sh >/dev/null; then\nuse_bazel.sh latest\nfi\n@@ -45,7 +43,7 @@ bazel \\\n--bazelrc=\"${KYTHE_DIR}/extractors.bazelrc\" \\\nbuild \\\n--override_repository kythe_release=\"${KYTHE_DIR}\" \\\n- --define=kythe_corpus=gvisor.dev \\\n+ --define=kythe_corpus=github.com/google/gvisor \\\n--cxxopt=-std=c++17 \\\n--config=remote \\\n--auth_credentials=\"${KOKORO_BAZEL_AUTH_CREDENTIAL}\" \\\n" } ]
Go
Apache License 2.0
google/gvisor
Fix corpus_name to match our ingestion config[1]. PiperOrigin-RevId: 291412676
259,885
24.01.2020 12:53:29
28,800
d135b5abf6eafa92d2745dc98d48ef39d2f90e75
Add anonymous device number allocation to VFS2. Note that in VFS2, filesystem device numbers are per-vfs.FilesystemImpl rather than global, avoiding the need for a "registry" type to handle save/restore. (This is more consistent with Linux anyway: compare e.g. mm/shmem.c:shmem_mount() => fs/super.c:mount_nodev() => (indirectly) set_anon_super().)
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/device.go", "new_path": "pkg/sentry/vfs/device.go", "diff": "@@ -98,3 +98,32 @@ func (vfs *VirtualFilesystem) OpenDeviceSpecialFile(ctx context.Context, mnt *Mo\n}\nreturn rd.dev.Open(ctx, mnt, d, *opts)\n}\n+\n+// GetAnonBlockDevMinor allocates and returns an unused minor device number for\n+// an \"anonymous\" block device with major number 0.\n+func (vfs *VirtualFilesystem) GetAnonBlockDevMinor() (uint32, error) {\n+ vfs.anonBlockDevMinorMu.Lock()\n+ defer vfs.anonBlockDevMinorMu.Unlock()\n+ minor := vfs.anonBlockDevMinorNext\n+ const maxDevMinor = (1 << 20) - 1\n+ for minor < maxDevMinor {\n+ if _, ok := vfs.anonBlockDevMinor[minor]; !ok {\n+ vfs.anonBlockDevMinor[minor] = struct{}{}\n+ vfs.anonBlockDevMinorNext = minor + 1\n+ return minor, nil\n+ }\n+ minor++\n+ }\n+ return 0, syserror.EMFILE\n+}\n+\n+// PutAnonBlockDevMinor deallocates a minor device number returned by a\n+// previous call to GetAnonBlockDevMinor.\n+func (vfs *VirtualFilesystem) PutAnonBlockDevMinor(minor uint32) {\n+ vfs.anonBlockDevMinorMu.Lock()\n+ defer vfs.anonBlockDevMinorMu.Unlock()\n+ delete(vfs.anonBlockDevMinor, minor)\n+ if minor < vfs.anonBlockDevMinorNext {\n+ vfs.anonBlockDevMinorNext = minor\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/vfs/vfs.go", "new_path": "pkg/sentry/vfs/vfs.go", "diff": "@@ -80,6 +80,14 @@ type VirtualFilesystem struct {\ndevicesMu sync.RWMutex\ndevices map[devTuple]*registeredDevice\n+ // anonBlockDevMinor contains all allocated anonymous block device minor\n+ // numbers. anonBlockDevMinorNext is a lower bound for the smallest\n+ // unallocated anonymous block device number. anonBlockDevMinorNext and\n+ // anonBlockDevMinor are protected by anonBlockDevMinorMu.\n+ anonBlockDevMinorMu sync.Mutex\n+ anonBlockDevMinorNext uint32\n+ anonBlockDevMinor map[uint32]struct{}\n+\n// fsTypes contains all registered FilesystemTypes. fsTypes is protected by\n// fsTypesMu.\nfsTypesMu sync.RWMutex\n@@ -96,6 +104,8 @@ func New() *VirtualFilesystem {\nvfs := &VirtualFilesystem{\nmountpoints: make(map[*Dentry]map[*Mount]struct{}),\ndevices: make(map[devTuple]*registeredDevice),\n+ anonBlockDevMinorNext: 1,\n+ anonBlockDevMinor: make(map[uint32]struct{}),\nfsTypes: make(map[string]*registeredFilesystemType),\nfilesystems: make(map[*Filesystem]struct{}),\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add anonymous device number allocation to VFS2. Note that in VFS2, filesystem device numbers are per-vfs.FilesystemImpl rather than global, avoiding the need for a "registry" type to handle save/restore. (This is more consistent with Linux anyway: compare e.g. mm/shmem.c:shmem_mount() => fs/super.c:mount_nodev() => (indirectly) set_anon_super().) PiperOrigin-RevId: 291425193
260,004
24.01.2020 13:02:01
28,800
878bda6e19a0d55525ea6b1600f3413e0c5d6a84
Lock the NIC when checking if an address is tentative
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/stack/nic.go", "new_path": "pkg/tcpip/stack/nic.go", "diff": "@@ -1208,6 +1208,9 @@ func (n *NIC) Stack() *Stack {\n// false. It will only return true if the address is associated with the NIC\n// AND it is tentative.\nfunc (n *NIC) isAddrTentative(addr tcpip.Address) bool {\n+ n.mu.RLock()\n+ defer n.mu.RUnlock()\n+\nref, ok := n.mu.endpoints[NetworkEndpointID{addr}]\nif !ok {\nreturn false\n" } ]
Go
Apache License 2.0
google/gvisor
Lock the NIC when checking if an address is tentative PiperOrigin-RevId: 291426657
259,885
24.01.2020 17:06:30
28,800
18a7e1309decb9bc09879e337adbc00f81d420c5
Add support for device special files to VFS2 tmpfs.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "new_path": "pkg/sentry/fsimpl/tmpfs/BUILD", "diff": "@@ -20,6 +20,7 @@ go_library(\nname = \"tmpfs\",\nsrcs = [\n\"dentry_list.go\",\n+ \"device_file.go\",\n\"directory.go\",\n\"filesystem.go\",\n\"named_pipe.go\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "pkg/sentry/fsimpl/tmpfs/device_file.go", "diff": "+// Copyright 2020 The gVisor Authors.\n+//\n+// Licensed under the Apache License, Version 2.0 (the \"License\");\n+// you may not use this file except in compliance with the License.\n+// You may obtain a copy of the License at\n+//\n+// http://www.apache.org/licenses/LICENSE-2.0\n+//\n+// Unless required by applicable law or agreed to in writing, software\n+// distributed under the License is distributed on an \"AS IS\" BASIS,\n+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+// See the License for the specific language governing permissions and\n+// limitations under the License.\n+\n+package tmpfs\n+\n+import (\n+ \"gvisor.dev/gvisor/pkg/abi/linux\"\n+ \"gvisor.dev/gvisor/pkg/sentry/kernel/auth\"\n+ \"gvisor.dev/gvisor/pkg/sentry/vfs\"\n+)\n+\n+type deviceFile struct {\n+ inode inode\n+ kind vfs.DeviceKind\n+ major uint32\n+ minor uint32\n+}\n+\n+func (fs *filesystem) newDeviceFile(creds *auth.Credentials, mode linux.FileMode, kind vfs.DeviceKind, major, minor uint32) *inode {\n+ file := &deviceFile{\n+ kind: kind,\n+ major: major,\n+ minor: minor,\n+ }\n+ file.inode.init(file, fs, creds, mode)\n+ file.inode.nlink = 1 // from parent directory\n+ return &file.inode\n+}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "new_path": "pkg/sentry/fsimpl/tmpfs/filesystem.go", "diff": "@@ -228,23 +228,26 @@ func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts v\n// MknodAt implements vfs.FilesystemImpl.MknodAt.\nfunc (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {\nreturn fs.doCreateAt(rp, false /* dir */, func(parent *dentry, name string) error {\n+ var childInode *inode\nswitch opts.Mode.FileType() {\ncase 0, linux.S_IFREG:\n- child := fs.newDentry(fs.newRegularFile(rp.Credentials(), opts.Mode))\n- parent.vfsd.InsertChild(&child.vfsd, name)\n- parent.inode.impl.(*directory).childList.PushBack(child)\n- return nil\n+ childInode = fs.newRegularFile(rp.Credentials(), opts.Mode)\ncase linux.S_IFIFO:\n- child := fs.newDentry(fs.newNamedPipe(rp.Credentials(), opts.Mode))\n- parent.vfsd.InsertChild(&child.vfsd, name)\n- parent.inode.impl.(*directory).childList.PushBack(child)\n- return nil\n- case linux.S_IFBLK, linux.S_IFCHR, linux.S_IFSOCK:\n+ childInode = fs.newNamedPipe(rp.Credentials(), opts.Mode)\n+ case linux.S_IFBLK:\n+ childInode = fs.newDeviceFile(rp.Credentials(), opts.Mode, vfs.BlockDevice, opts.DevMajor, opts.DevMinor)\n+ case linux.S_IFCHR:\n+ childInode = fs.newDeviceFile(rp.Credentials(), opts.Mode, vfs.CharDevice, opts.DevMajor, opts.DevMinor)\n+ case linux.S_IFSOCK:\n// Not yet supported.\nreturn syserror.EPERM\ndefault:\nreturn syserror.EINVAL\n}\n+ child := fs.newDentry(childInode)\n+ parent.vfsd.InsertChild(&child.vfsd, name)\n+ parent.inode.impl.(*directory).childList.PushBack(child)\n+ return nil\n})\n}\n@@ -264,7 +267,7 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nif err != nil {\nreturn nil, err\n}\n- return d.open(ctx, rp, opts.Flags, false /* afterCreate */)\n+ return d.open(ctx, rp, &opts, false /* afterCreate */)\n}\nmustCreate := opts.Flags&linux.O_EXCL != 0\n@@ -279,7 +282,7 @@ func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vf\nif mustCreate {\nreturn nil, syserror.EEXIST\n}\n- return start.open(ctx, rp, opts.Flags, false /* afterCreate */)\n+ return start.open(ctx, rp, &opts, false /* afterCreate */)\n}\nafterTrailingSymlink:\nparent, err := walkParentDirLocked(rp, start)\n@@ -313,7 +316,7 @@ afterTrailingSymlink:\nchild := fs.newDentry(fs.newRegularFile(rp.Credentials(), opts.Mode))\nparent.vfsd.InsertChild(&child.vfsd, name)\nparent.inode.impl.(*directory).childList.PushBack(child)\n- return child.open(ctx, rp, opts.Flags, true)\n+ return child.open(ctx, rp, &opts, true)\n}\nif err != nil {\nreturn nil, err\n@@ -327,11 +330,11 @@ afterTrailingSymlink:\nif mustCreate {\nreturn nil, syserror.EEXIST\n}\n- return child.open(ctx, rp, opts.Flags, false)\n+ return child.open(ctx, rp, &opts, false)\n}\n-func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32, afterCreate bool) (*vfs.FileDescription, error) {\n- ats := vfs.AccessTypesForOpenFlags(flags)\n+func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, opts *vfs.OpenOptions, afterCreate bool) (*vfs.FileDescription, error) {\n+ ats := vfs.AccessTypesForOpenFlags(opts.Flags)\nif !afterCreate {\nif err := d.inode.checkPermissions(rp.Credentials(), ats, d.inode.isDir()); err != nil {\nreturn nil, err\n@@ -340,10 +343,10 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\nswitch impl := d.inode.impl.(type) {\ncase *regularFile:\nvar fd regularFileFD\n- if err := fd.vfsfd.Init(&fd, flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\nreturn nil, err\n}\n- if flags&linux.O_TRUNC != 0 {\n+ if opts.Flags&linux.O_TRUNC != 0 {\nimpl.mu.Lock()\nimpl.data.Truncate(0, impl.memFile)\natomic.StoreUint64(&impl.size, 0)\n@@ -356,7 +359,7 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\nreturn nil, syserror.EISDIR\n}\nvar fd directoryFD\n- if err := fd.vfsfd.Init(&fd, flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\n+ if err := fd.vfsfd.Init(&fd, opts.Flags, rp.Mount(), &d.vfsd, &vfs.FileDescriptionOptions{}); err != nil {\nreturn nil, err\n}\nreturn &fd.vfsfd, nil\n@@ -364,7 +367,9 @@ func (d *dentry) open(ctx context.Context, rp *vfs.ResolvingPath, flags uint32,\n// Can't open symlinks without O_PATH (which is unimplemented).\nreturn nil, syserror.ELOOP\ncase *namedPipe:\n- return newNamedPipeFD(ctx, impl, rp, &d.vfsd, flags)\n+ return newNamedPipeFD(ctx, impl, rp, &d.vfsd, opts.Flags)\n+ case *deviceFile:\n+ return rp.VirtualFilesystem().OpenDeviceSpecialFile(ctx, rp.Mount(), &d.vfsd, impl.kind, impl.major, impl.minor, opts)\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", d.inode.impl))\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "new_path": "pkg/sentry/fsimpl/tmpfs/tmpfs.go", "diff": "@@ -149,6 +149,10 @@ type inode struct {\nctime int64 // nanoseconds\nmtime int64 // nanoseconds\n+ // Only meaningful for device special files.\n+ rdevMajor uint32\n+ rdevMinor uint32\n+\nimpl interface{} // immutable\n}\n@@ -269,6 +273,15 @@ func (i *inode) statTo(stat *linux.Statx) {\nstat.Blocks = allocatedBlocksForSize(stat.Size)\ncase *namedPipe:\nstat.Mode |= linux.S_IFIFO\n+ case *deviceFile:\n+ switch impl.kind {\n+ case vfs.BlockDevice:\n+ stat.Mode |= linux.S_IFBLK\n+ case vfs.CharDevice:\n+ stat.Mode |= linux.S_IFCHR\n+ }\n+ stat.RdevMajor = impl.major\n+ stat.RdevMinor = impl.minor\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", i.impl))\n}\n@@ -309,12 +322,8 @@ func (i *inode) setStat(stat linux.Statx) error {\n}\ncase *directory:\nreturn syserror.EISDIR\n- case *symlink:\n- return syserror.EINVAL\n- case *namedPipe:\n- // Nothing.\ndefault:\n- panic(fmt.Sprintf(\"unknown inode type: %T\", i.impl))\n+ return syserror.EINVAL\n}\n}\nif mask&linux.STATX_ATIME != 0 {\n@@ -353,13 +362,22 @@ func allocatedBlocksForSize(size uint64) uint64 {\n}\nfunc (i *inode) direntType() uint8 {\n- switch i.impl.(type) {\n+ switch impl := i.impl.(type) {\ncase *regularFile:\nreturn linux.DT_REG\ncase *directory:\nreturn linux.DT_DIR\ncase *symlink:\nreturn linux.DT_LNK\n+ case *deviceFile:\n+ switch impl.kind {\n+ case vfs.BlockDevice:\n+ return linux.DT_BLK\n+ case vfs.CharDevice:\n+ return linux.DT_CHR\n+ default:\n+ panic(fmt.Sprintf(\"unknown vfs.DeviceKind: %v\", impl.kind))\n+ }\ndefault:\npanic(fmt.Sprintf(\"unknown inode type: %T\", i.impl))\n}\n" } ]
Go
Apache License 2.0
google/gvisor
Add support for device special files to VFS2 tmpfs. PiperOrigin-RevId: 291471892
259,891
24.01.2020 17:12:03
28,800
2946fe81627afa223853769ed736e2a56e0144b7
We can now actually write out the udp matcher.
[ { "change_type": "MODIFY", "old_path": "pkg/sentry/socket/netfilter/netfilter.go", "new_path": "pkg/sentry/socket/netfilter/netfilter.go", "diff": "@@ -36,7 +36,7 @@ const errorTargetName = \"ERROR\"\n// metadata is opaque to netstack. It holds data that we need to translate\n// between Linux's and netstack's iptables representations.\n-// TODO(gvisor.dev/issue/170): This might be removable.\n+// TODO(gvisor.dev/issue/170): Use metadata to check correctness.\ntype metadata struct {\nHookEntry [linux.NF_INET_NUMHOOKS]uint32\nUnderflow [linux.NF_INET_NUMHOOKS]uint32\n@@ -44,6 +44,14 @@ type metadata struct {\nSize uint32\n}\n+const enableDebugLog = true\n+\n+func nflog(format string, args ...interface{}) {\n+ if enableDebugLog {\n+ log.Infof(\"netfilter: \"+format, args...)\n+ }\n+}\n+\n// GetInfo returns information about iptables.\nfunc GetInfo(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr) (linux.IPTGetinfo, *syserr.Error) {\n// Read in the struct and table name.\n@@ -72,6 +80,8 @@ func GetInfo(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr) (linux.IPT\ninfo.NumEntries = metadata.NumEntries\ninfo.Size = metadata.Size\n+ nflog(\"GetInfo returning info: %+v\", info)\n+\nreturn info, nil\n}\n@@ -80,21 +90,26 @@ func GetEntries(t *kernel.Task, stack *stack.Stack, outPtr usermem.Addr, outLen\n// Read in the struct and table name.\nvar userEntries linux.IPTGetEntries\nif _, err := t.CopyIn(outPtr, &userEntries); err != nil {\n+ log.Warningf(\"netfilter: couldn't copy in entries %q\", userEntries.Name)\nreturn linux.KernelIPTGetEntries{}, syserr.FromError(err)\n}\n// Find the appropriate table.\ntable, err := findTable(stack, userEntries.Name)\nif err != nil {\n+ log.Warningf(\"netfilter: couldn't find table %q\", userEntries.Name)\nreturn linux.KernelIPTGetEntries{}, err\n}\n// Convert netstack's iptables rules to something that the iptables\n// tool can understand.\n- entries, _, err := convertNetstackToBinary(userEntries.Name.String(), table)\n+ entries, meta, err := convertNetstackToBinary(userEntries.Name.String(), table)\nif err != nil {\nreturn linux.KernelIPTGetEntries{}, err\n}\n+ if meta != table.Metadata().(metadata) {\n+ panic(fmt.Sprintf(\"Table %q metadata changed between writing and reading. Was saved as %+v, but is now %+v\", userEntries.Name.String(), table.Metadata().(metadata), meta))\n+ }\nif binary.Size(entries) > uintptr(outLen) {\nlog.Warningf(\"Insufficient GetEntries output size: %d\", uintptr(outLen))\nreturn linux.KernelIPTGetEntries{}, syserr.ErrInvalidArgument\n@@ -148,15 +163,19 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\ncopy(entries.Name[:], tablename)\nfor ruleIdx, rule := range table.Rules {\n+ nflog(\"Current offset: %d\", entries.Size)\n+\n// Is this a chain entry point?\nfor hook, hookRuleIdx := range table.BuiltinChains {\nif hookRuleIdx == ruleIdx {\n+ nflog(\"Found hook %d at offset %d\", hook, entries.Size)\nmeta.HookEntry[hook] = entries.Size\n}\n}\n// Is this a chain underflow point?\nfor underflow, underflowRuleIdx := range table.Underflows {\nif underflowRuleIdx == ruleIdx {\n+ nflog(\"Found underflow %d at offset %d\", underflow, entries.Size)\nmeta.Underflow[underflow] = entries.Size\n}\n}\n@@ -176,6 +195,10 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\n// Serialize the matcher and add it to the\n// entry.\nserialized := marshalMatcher(matcher)\n+ nflog(\"matcher serialized as: %v\", serialized)\n+ if len(serialized)%8 != 0 {\n+ panic(fmt.Sprintf(\"matcher %T is not 64-bit aligned\", matcher))\n+ }\nentry.Elems = append(entry.Elems, serialized...)\nentry.NextOffset += uint16(len(serialized))\nentry.TargetOffset += uint16(len(serialized))\n@@ -183,18 +206,25 @@ func convertNetstackToBinary(tablename string, table iptables.Table) (linux.Kern\n// Serialize and append the target.\nserialized := marshalTarget(rule.Target)\n+ if len(serialized)%8 != 0 {\n+ panic(fmt.Sprintf(\"target %T is not 64-bit aligned\", rule.Target))\n+ }\nentry.Elems = append(entry.Elems, serialized...)\nentry.NextOffset += uint16(len(serialized))\n+ nflog(\"Adding entry: %+v\", entry)\n+\nentries.Size += uint32(entry.NextOffset)\nentries.Entrytable = append(entries.Entrytable, entry)\nmeta.NumEntries++\n}\n+ nflog(\"Finished with an marshalled size of %d\", meta.Size)\nmeta.Size = entries.Size\nreturn entries, meta, nil\n}\n+// TODO: SOMEHOW THIS IS NOT GETTING APPENDED!\nfunc marshalMatcher(matcher iptables.Matcher) []byte {\nswitch m := matcher.(type) {\ncase *iptables.UDPMatcher:\n@@ -207,17 +237,17 @@ func marshalMatcher(matcher iptables.Matcher) []byte {\n}\nfunc marshalUDPMatcher(matcher *iptables.UDPMatcher) []byte {\n+ nflog(\"Marshalling UDP matcher: %+v\", matcher)\n+\nlinuxMatcher := linux.KernelXTEntryMatch{\nXTEntryMatch: linux.XTEntryMatch{\n- MatchSize: linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP,\n+ MatchSize: linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP + 6,\n// Name: \"udp\",\n},\n- Data: make([]byte, linux.SizeOfXTUDP+22),\n+ Data: make([]byte, 0, linux.SizeOfXTUDP),\n}\n- // copy(linuxMatcher.Name[:], \"udp\")\ncopy(linuxMatcher.Name[:], \"udp\")\n- // TODO: Must be aligned.\nxtudp := linux.XTUDP{\nSourcePortStart: matcher.Data.SourcePortStart,\nSourcePortEnd: matcher.Data.SourcePortEnd,\n@@ -225,17 +255,17 @@ func marshalUDPMatcher(matcher *iptables.UDPMatcher) []byte {\nDestinationPortEnd: matcher.Data.DestinationPortEnd,\nInverseFlags: matcher.Data.InverseFlags,\n}\n- binary.Marshal(linuxMatcher.Data[:linux.SizeOfXTUDP], usermem.ByteOrder, xtudp)\n-\n- if binary.Size(linuxMatcher)%64 != 0 {\n- panic(fmt.Sprintf(\"size is actually: %d\", binary.Size(linuxMatcher)))\n- }\n-\n- var buf [linux.SizeOfXTEntryMatch + linux.SizeOfXTUDP + 22]byte\n- if len(buf)%64 != 0 {\n- panic(fmt.Sprintf(\"len is actually: %d\", len(buf)))\n- }\n- binary.Marshal(buf[:], usermem.ByteOrder, linuxMatcher)\n+ nflog(\"marshalUDPMatcher: xtudp: %+v\", xtudp)\n+ linuxMatcher.Data = binary.Marshal(linuxMatcher.Data, usermem.ByteOrder, xtudp)\n+ nflog(\"marshalUDPMatcher: linuxMatcher: %+v\", linuxMatcher)\n+\n+ // We have to pad this struct size to a multiple of 8 bytes, so we make\n+ // this a little longer than it needs to be.\n+ buf := make([]byte, 0, linux.SizeOfXTEntryMatch+linux.SizeOfXTUDP+6)\n+ buf = binary.Marshal(buf, usermem.ByteOrder, linuxMatcher)\n+ buf = append(buf, []byte{0, 0, 0, 0, 0, 0}...)\n+ nflog(\"Marshalled into matcher of size %d\", len(buf))\n+ nflog(\"marshalUDPMatcher: buf is: %v\", buf)\nreturn buf[:]\n}\n@@ -253,6 +283,8 @@ func marshalTarget(target iptables.Target) []byte {\n}\nfunc marshalStandardTarget(verdict iptables.Verdict) []byte {\n+ nflog(\"Marshalling standard target with size %d\", linux.SizeOfXTStandardTarget)\n+\n// TODO: Must be aligned.\n// The target's name will be the empty string.\ntarget := linux.XTStandardTarget{\n@@ -321,7 +353,7 @@ func translateToStandardVerdict(val int32) (iptables.Verdict, *syserr.Error) {\n// SetEntries sets iptables rules for a single table. See\n// net/ipv4/netfilter/ip_tables.c:translate_table for reference.\nfunc SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n- printReplace(optVal)\n+ // printReplace(optVal)\n// Get the basic rules data (struct ipt_replace).\nif len(optVal) < linux.SizeOfIPTReplace {\n@@ -343,10 +375,14 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\nreturn syserr.ErrInvalidArgument\n}\n+ nflog(\"Setting entries in table %q\", replace.Name.String())\n+\n// Convert input into a list of rules and their offsets.\nvar offset uint32\nvar offsets []uint32\nfor entryIdx := uint32(0); entryIdx < replace.NumEntries; entryIdx++ {\n+ nflog(\"Processing entry at offset %d\", offset)\n+\n// Get the struct ipt_entry.\nif len(optVal) < linux.SizeOfIPTEntry {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry %d\", len(optVal))\n@@ -464,9 +500,10 @@ func SetEntries(stack *stack.Stack, optVal []byte) *syserr.Error {\n// parseMatchers parses 0 or more matchers from optVal. optVal should contain\n// only the matchers.\nfunc parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Matcher, *syserr.Error) {\n+ nflog(\"Parsing matchers of size %d\", len(optVal))\nvar matchers []iptables.Matcher\nfor len(optVal) > 0 {\n- log.Infof(\"parseMatchers: optVal has len %d\", len(optVal))\n+ nflog(\"parseMatchers: optVal has len %d\", len(optVal))\n// Get the XTEntryMatch.\nif len(optVal) < linux.SizeOfXTEntryMatch {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry match: %d\", len(optVal))\n@@ -475,7 +512,7 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\nvar match linux.XTEntryMatch\nbuf := optVal[:linux.SizeOfXTEntryMatch]\nbinary.Unmarshal(buf, usermem.ByteOrder, &match)\n- log.Infof(\"parseMatchers: parsed entry match %q: %+v\", match.Name.String(), match)\n+ nflog(\"parseMatchers: parsed entry match %q: %+v\", match.Name.String(), match)\n// Check some invariants.\nif match.MatchSize < linux.SizeOfXTEntryMatch {\n@@ -532,6 +569,7 @@ func parseMatchers(filter iptables.IPHeaderFilter, optVal []byte) ([]iptables.Ma\n// parseTarget parses a target from optVal. optVal should contain only the\n// target.\nfunc parseTarget(optVal []byte) (iptables.Target, *syserr.Error) {\n+ nflog(\"Parsing target of size %d\", len(optVal))\nif len(optVal) < linux.SizeOfXTEntryTarget {\nlog.Warningf(\"netfilter: optVal has insufficient size for entry target %d\", len(optVal))\nreturn nil, syserr.ErrInvalidArgument\n" } ]
Go
Apache License 2.0
google/gvisor
We can now actually write out the udp matcher.
259,962
27.01.2020 05:33:03
28,800
6b43cf791a74a746443f70f98d859c1246f87e2a
Replace calculateChecksum w/ the unrolled version. Fixes
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/checksum.go", "new_path": "pkg/tcpip/header/checksum.go", "diff": "@@ -160,20 +160,23 @@ func unrolledCalculateChecksum(buf []byte, odd bool, initial uint32) (uint16, bo\nreturn ChecksumCombine(uint16(v), uint16(v>>16)), odd\n}\n-// Checksum calculates the checksum (as defined in RFC 1071) of the bytes in the\n-// given byte array.\n+// ChecksumOld calculates the checksum (as defined in RFC 1071) of the bytes in\n+// the given byte array. This function uses a non-optimized implementation. Its\n+// only retained for reference and to use as a benchmark/test. Most code should\n+// use the header.Checksum function.\n//\n// The initial checksum must have been computed on an even number of bytes.\n-func Checksum(buf []byte, initial uint16) uint16 {\n+func ChecksumOld(buf []byte, initial uint16) uint16 {\ns, _ := calculateChecksum(buf, false, uint32(initial))\nreturn s\n}\n-// UnrolledChecksum calculates the checksum (as defined in RFC 1071) of the\n-// bytes in the given byte array.\n+// Checksum calculates the checksum (as defined in RFC 1071) of the bytes in the\n+// given byte array. This function uses an optimized unrolled version of the\n+// checksum algorithm.\n//\n// The initial checksum must have been computed on an even number of bytes.\n-func UnrolledChecksum(buf []byte, initial uint16) uint16 {\n+func Checksum(buf []byte, initial uint16) uint16 {\ns, _ := unrolledCalculateChecksum(buf, false, uint32(initial))\nreturn s\n}\n" }, { "change_type": "MODIFY", "old_path": "pkg/tcpip/header/checksum_test.go", "new_path": "pkg/tcpip/header/checksum_test.go", "diff": "@@ -128,8 +128,8 @@ func TestChecksum(t *testing.T) {\n}\nfor i := range testCases {\n- testCases[i].csumOrig = header.Checksum(testCases[i].buf, testCases[i].initial)\n- testCases[i].csumNew = header.UnrolledChecksum(testCases[i].buf, testCases[i].initial)\n+ testCases[i].csumOrig = header.ChecksumOld(testCases[i].buf, testCases[i].initial)\n+ testCases[i].csumNew = header.Checksum(testCases[i].buf, testCases[i].initial)\nif got, want := testCases[i].csumNew, testCases[i].csumOrig; got != want {\nt.Fatalf(\"new checksum for (buf = %x, initial = %d) does not match old got: %d, want: %d\", testCases[i].buf, testCases[i].initial, got, want)\n}\n@@ -143,8 +143,8 @@ func BenchmarkChecksum(b *testing.B) {\nfn func([]byte, uint16) uint16\nname string\n}{\n+ {header.ChecksumOld, fmt.Sprintf(\"checksum_old\")},\n{header.Checksum, fmt.Sprintf(\"checksum\")},\n- {header.UnrolledChecksum, fmt.Sprintf(\"unrolled_checksum\")},\n}\nfor _, csumImpl := range checkSumImpls {\n" } ]
Go
Apache License 2.0
google/gvisor
Replace calculateChecksum w/ the unrolled version. Fixes #1656 PiperOrigin-RevId: 291703760
259,865
22.01.2020 12:50:28
0
45398b160f4ccc3148644dde5eb5e4610e6a2d9b
Expose gonet.NewPacketConn, for parity with gonet.NewConn API gonet.Conn can be created with both gonet.NewConn and gonet.Dial. gonet.PacketConn was created only by gonet.DialUDP. This prevented us from being able to use PacketConn in udp.NewForwarder() context. This simple constructor - NewPacketConn, allows user to create correct structure from that context.
[ { "change_type": "MODIFY", "old_path": "pkg/tcpip/adapters/gonet/gonet.go", "new_path": "pkg/tcpip/adapters/gonet/gonet.go", "diff": "@@ -556,6 +556,17 @@ type PacketConn struct {\nwq *waiter.Queue\n}\n+// NewPacketConn creates a new PacketConn.\n+func NewPacketConn(s *stack.Stack, wq *waiter.Queue, ep tcpip.Endpoint) *PacketConn {\n+ c := &PacketConn{\n+ stack: s,\n+ ep: ep,\n+ wq: wq,\n+ }\n+ c.deadlineTimer.init()\n+ return c\n+}\n+\n// DialUDP creates a new PacketConn.\n//\n// If laddr is nil, a local address is automatically chosen.\n" } ]
Go
Apache License 2.0
google/gvisor
Expose gonet.NewPacketConn, for parity with gonet.NewConn API gonet.Conn can be created with both gonet.NewConn and gonet.Dial. gonet.PacketConn was created only by gonet.DialUDP. This prevented us from being able to use PacketConn in udp.NewForwarder() context. This simple constructor - NewPacketConn, allows user to create correct structure from that context.