spf13 / afero

A FileSystem Abstraction System for Go
Apache License 2.0
5.98k stars 514 forks source link

MemMapFs clears out non chmod mode bits when writing file #392

Open sridgeway7 opened 1 year ago

sridgeway7 commented 1 year ago

I recently update a project from v1.3.3 to v1.8.2 and it looks like file mode is not preserved when creating files using MemMapFs.

I'm trying to write a file with os.ModeSocket to a MemMapFs instance in a test. After writing the file, I can see that os.ModeSocket is not set. It looks like this is cause by this line which mutate perm at the top of MemMapFs.OpenFile:

https://github.com/spf13/afero/blob/45ef3465a4a977576eb1a9b2518d4736ea39d77b/memmap.go#L223-L224

Which was changed here: https://github.com/spf13/afero/commit/b598fbbf555db47578806d127b221ac1cd8dd854

This effectively zeroes out any perm bits that are not the chmodBits which make it impossible to create irregular files. It looks like the handling for preserving previous bits while only honoring chmodBits is already in MemMapFs.Chmod. So maybe a better approach is to not modify perm, set the mode as passed on creation, and then call Chmod if chmod is true?:

    if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
        file, err = m.Create(name)
        if err == nil {
            err = file.setFileMode(perm & ^chmodBits)
        }

        chmod = true
    }

    /* ... */

    if chmod {
        return file, m.Chmod(name, perm)
    }