Fix MemMapFs.Chmod changing non-perm bits

This commit is contained in:
John Starich 2020-07-11 18:13:38 -05:00
parent 64b7ddd95f
commit 7b70cb1dbc
2 changed files with 49 additions and 4 deletions

View File

@ -141,9 +141,7 @@ func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
m.registerWithParent(item) m.registerWithParent(item)
m.mu.Unlock() m.mu.Unlock()
m.Chmod(name, perm|os.ModeDir) return m.unrestrictedChmod(name, perm|os.ModeDir)
return nil
} }
func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error { func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
@ -240,7 +238,7 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro
} }
} }
if chmod { if chmod {
m.Chmod(name, perm) return file, m.unrestrictedChmod(name, perm)
} }
return file, nil return file, nil
} }
@ -321,6 +319,22 @@ func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
} }
func (m *MemMapFs) Chmod(name string, mode os.FileMode) error { func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
const chmodBits = os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky // Only a subset of bits are allowed to be changed. Documented under os.Chmod()
mode &= chmodBits
m.mu.RLock()
f, ok := m.getData()[name]
m.mu.RUnlock()
if !ok {
return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
}
prevOtherBits := mem.GetFileInfo(f).Mode() & ^chmodBits
mode = prevOtherBits | mode
return m.unrestrictedChmod(name, mode)
}
func (m *MemMapFs) unrestrictedChmod(name string, mode os.FileMode) error {
name = normalizePath(name) name = normalizePath(name)
m.mu.RLock() m.mu.RLock()

View File

@ -472,3 +472,34 @@ func TestMemFsUnexpectedEOF(t *testing.T) {
t.Fatal("Expected ErrUnexpectedEOF") t.Fatal("Expected ErrUnexpectedEOF")
} }
} }
func TestMemFsChmod(t *testing.T) {
t.Parallel()
fs := NewMemMapFs()
const file = "/hello"
if err := fs.Mkdir(file, 0700); err != nil {
t.Fatal(err)
}
info, err := fs.Stat(file)
if err != nil {
t.Fatal(err)
}
if info.Mode().String() != "drwx------" {
t.Fatal("mkdir failed to create a directory: mode =", info.Mode())
}
err = fs.Chmod(file, 0)
if err != nil {
t.Error("Failed to run chmod:", err)
}
info, err = fs.Stat(file)
if err != nil {
t.Fatal(err)
}
if info.Mode().String() != "d---------" {
t.Error("chmod should not change file type. New mode =", info.Mode())
}
}