github.com/avfs/avfs@v0.33.1-0.20240303173310-c6ba67c33eb7/umask_linux.go (about) 1 // 2 // Copyright 2023 The AVFS authors 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 //go:build linux 18 19 package avfs 20 21 import ( 22 "io/fs" 23 "sync" 24 "syscall" 25 ) 26 27 var ( 28 // umask is the file mode creation mask. 29 umask fs.FileMode = initUMask() //nolint:gochecknoglobals // Used by UMask and SetUMask. 30 31 // umLock lock access to the umask. 32 umLock sync.RWMutex //nolint:gochecknoglobals // Used by UMask and SetUMask. 33 ) 34 35 func initUMask() fs.FileMode { 36 umLock.Lock() 37 defer umLock.Unlock() 38 39 m := syscall.Umask(0) // read mask. 40 syscall.Umask(m) // restore mask after read. 41 42 return fs.FileMode(m) 43 } 44 45 // SetUMask sets the file mode creation mask. 46 // Umask must be set to 0 using umask(2) system call to be read, 47 // so its value is cached and protected by a mutex. 48 func SetUMask(mask fs.FileMode) error { 49 umLock.Lock() 50 m := int(mask & fs.ModePerm) 51 _ = syscall.Umask(m) 52 umask = fs.FileMode(m) 53 umLock.Unlock() 54 55 return nil 56 } 57 58 // UMask returns the file mode creation mask. 59 func UMask() fs.FileMode { 60 umLock.RLock() 61 um := umask 62 umLock.RUnlock() 63 64 return um 65 }