diff --git a/cmd/containers-storage/container.go b/cmd/containers-storage/container.go index ce31fbd60..f3ffab247 100644 --- a/cmd/containers-storage/container.go +++ b/cmd/containers-storage/container.go @@ -9,9 +9,7 @@ import ( "github.com/containers/storage/pkg/mflag" ) -var ( - paramContainerDataFile = "" -) +var paramContainerDataFile = "" func container(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { images, err := m.Images() diff --git a/cmd/containers-storage/copy.go b/cmd/containers-storage/copy.go index 14a96c910..9531f4625 100644 --- a/cmd/containers-storage/copy.go +++ b/cmd/containers-storage/copy.go @@ -13,9 +13,7 @@ import ( "github.com/containers/storage/pkg/mflag" ) -var ( - chownOptions = "" -) +var chownOptions = "" func copyContent(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { var untarIDMappings *idtools.IDMappings diff --git a/cmd/containers-storage/image.go b/cmd/containers-storage/image.go index 11b90a262..6851e0ce0 100644 --- a/cmd/containers-storage/image.go +++ b/cmd/containers-storage/image.go @@ -10,9 +10,7 @@ import ( digest "github.com/opencontainers/go-digest" ) -var ( - paramImageDataFile = "" -) +var paramImageDataFile = "" func image(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { matched := []*storage.Image{} diff --git a/cmd/containers-storage/images.go b/cmd/containers-storage/images.go index 60e3a74e0..c3d0ac34e 100644 --- a/cmd/containers-storage/images.go +++ b/cmd/containers-storage/images.go @@ -8,9 +8,7 @@ import ( digest "github.com/opencontainers/go-digest" ) -var ( - imagesQuiet = false -) +var imagesQuiet = false func images(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { images, err := m.Images() diff --git a/cmd/containers-storage/layer.go b/cmd/containers-storage/layer.go index 828b30cee..1b3ab8d7c 100644 --- a/cmd/containers-storage/layer.go +++ b/cmd/containers-storage/layer.go @@ -9,9 +9,7 @@ import ( "github.com/containers/storage/pkg/mflag" ) -var ( - paramLayerDataFile = "" -) +var paramLayerDataFile = "" func listLayerBigData(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { layer, err := m.Layer(args[0]) diff --git a/cmd/containers-storage/shutdown.go b/cmd/containers-storage/shutdown.go index 10fcc8392..3cda6cf10 100644 --- a/cmd/containers-storage/shutdown.go +++ b/cmd/containers-storage/shutdown.go @@ -7,9 +7,7 @@ import ( "github.com/containers/storage/pkg/mflag" ) -var ( - forceShutdown = false -) +var forceShutdown = false func shutdown(flags *mflag.FlagSet, action string, m storage.Store, args []string) (int, error) { _, err := m.Shutdown(forceShutdown) diff --git a/cmd/containers-storage/tree.go b/cmd/containers-storage/tree.go index 3ff757278..b352267e0 100644 --- a/cmd/containers-storage/tree.go +++ b/cmd/containers-storage/tree.go @@ -5,12 +5,14 @@ import ( "strings" ) -const treeIndentStep = 2 -const treeStemWidth = treeIndentStep - 1 -const treeVertical = '\u2502' -const treeThisAndMore = "\u251c" -const treeJustThis = "\u2514" -const treeStem = "\u2500" +const ( + treeIndentStep = 2 + treeStemWidth = treeIndentStep - 1 + treeVertical = '\u2502' + treeThisAndMore = "\u251c" + treeJustThis = "\u2514" + treeStem = "\u2500" +) type treeNode struct { left, right string diff --git a/containers.go b/containers.go index 3a4b251b1..a7dfb405b 100644 --- a/containers.go +++ b/containers.go @@ -536,7 +536,7 @@ func (r *containerStore) save(saveLocations containerLocations) error { continue } rpath := r.jsonPath[locationIndex] - if err := os.MkdirAll(filepath.Dir(rpath), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(rpath), 0o700); err != nil { return err } subsetContainers := make([]*Container, 0, len(r.containers)) @@ -556,7 +556,7 @@ func (r *containerStore) save(saveLocations containerLocations) error { NoSync: true, } } - if err := ioutils.AtomicWriteFileWithOpts(rpath, jdata, 0600, opts); err != nil { + if err := ioutils.AtomicWriteFileWithOpts(rpath, jdata, 0o600, opts); err != nil { return err } } @@ -571,12 +571,12 @@ func (r *containerStore) saveFor(modifiedContainer *Container) error { } func newContainerStore(dir string, runDir string, transient bool) (rwContainerStore, error) { - if err := os.MkdirAll(dir, 0700); err != nil { + if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } volatileDir := dir if transient { - if err := os.MkdirAll(runDir, 0700); err != nil { + if err := os.MkdirAll(runDir, 0o700); err != nil { return nil, err } volatileDir = runDir @@ -928,10 +928,10 @@ func (r *containerStore) SetBigData(id, key string, data []byte) error { if !ok { return ErrContainerUnknown } - if err := os.MkdirAll(r.datadir(c.ID), 0700); err != nil { + if err := os.MkdirAll(r.datadir(c.ID), 0o700); err != nil { return err } - err := ioutils.AtomicWriteFile(r.datapath(c.ID, key), data, 0600) + err := ioutils.AtomicWriteFile(r.datapath(c.ID, key), data, 0o600) if err == nil { save := false if c.BigDataSizes == nil { diff --git a/drivers/aufs/aufs.go b/drivers/aufs/aufs.go index 4b0133a05..0b1766210 100644 --- a/drivers/aufs/aufs.go +++ b/drivers/aufs/aufs.go @@ -64,7 +64,7 @@ var ( enableDirperm bool ) -const defaultPerms = os.FileMode(0555) +const defaultPerms = os.FileMode(0o555) func init() { graphdriver.MustRegister("aufs", Init) @@ -87,11 +87,9 @@ type Driver struct { // Init returns a new AUFS driver. // An error is returned if AUFS is not supported. func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) { - // Try to load the aufs kernel module if err := supportsAufs(); err != nil { return nil, fmt.Errorf("kernel does not support aufs: %w", graphdriver.ErrNotSupported) - } fsMagic, err := graphdriver.GetFSMagic(home) @@ -145,7 +143,7 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) // Create the root aufs driver dir and return // if it already exists // If not populate the dir structure - if err := idtools.MkdirAllAs(home, 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(home, 0o700, rootUID, rootGID); err != nil { if os.IsExist(err) { return a, nil } @@ -158,7 +156,7 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) // Populate the dir structure for _, p := range paths { - if err := idtools.MkdirAllAs(path.Join(home, p), 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(path.Join(home, p), 0o700, rootUID, rootGID); err != nil { return nil, err } } @@ -290,7 +288,6 @@ func (a *Driver) CreateReadWrite(id, parent string, opts *graphdriver.CreateOpts // Create three folders for each id // mnt, layers, and diff func (a *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { - if opts != nil && len(opts.StorageOpt) != 0 { return fmt.Errorf("--storage-opt is not supported for aufs") } diff --git a/drivers/aufs/aufs_test.go b/drivers/aufs/aufs_test.go index 432df7ff2..d57505e02 100644 --- a/drivers/aufs/aufs_test.go +++ b/drivers/aufs/aufs_test.go @@ -52,7 +52,7 @@ func driverGet(d *Driver, id string, mntLabel string) (string, error) { } func newDriver(t testing.TB) *Driver { - if err := os.MkdirAll(tmp, 0755); err != nil { + if err := os.MkdirAll(tmp, 0o755); err != nil { t.Fatal(err) } @@ -61,7 +61,7 @@ func newDriver(t testing.TB) *Driver { } func TestNewDriver(t *testing.T) { - if err := os.MkdirAll(tmp, 0755); err != nil { + if err := os.MkdirAll(tmp, 0o755); err != nil { t.Fatal(err) } @@ -100,7 +100,7 @@ func TestCreateDirStructure(t *testing.T) { // We should be able to create two drivers with the same dir structure func TestNewDriverFromExistingDir(t *testing.T) { - if err := os.MkdirAll(tmp, 0755); err != nil { + if err := os.MkdirAll(tmp, 0o755); err != nil { t.Fatal(err) } @@ -646,7 +646,7 @@ func hash(c string) string { } func testMountMoreThan42Layers(t *testing.T, mountPath string) { - if err := os.MkdirAll(mountPath, 0755); err != nil { + if err := os.MkdirAll(mountPath, 0o755); err != nil { t.Fatal(err) } @@ -786,13 +786,13 @@ func BenchmarkConcurrentAccess(b *testing.B) { } func TestInitStaleCleanup(t *testing.T) { - if err := os.MkdirAll(tmp, 0755); err != nil { + if err := os.MkdirAll(tmp, 0o755); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) for _, d := range []string{"diff", "mnt"} { - if err := os.MkdirAll(filepath.Join(tmp, d, "123-removing"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(tmp, d, "123-removing"), 0o755); err != nil { t.Fatal(err) } } diff --git a/drivers/btrfs/btrfs.go b/drivers/btrfs/btrfs.go index e68804416..b0663b895 100644 --- a/drivers/btrfs/btrfs.go +++ b/drivers/btrfs/btrfs.go @@ -42,7 +42,7 @@ import ( "golang.org/x/sys/unix" ) -const defaultPerms = os.FileMode(0555) +const defaultPerms = os.FileMode(0o555) func init() { graphdriver.MustRegister("btrfs", Init) @@ -56,7 +56,6 @@ type btrfsOptions struct { // Init returns a new BTRFS driver. // An error is returned if BTRFS is not supported. func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) { - fsMagic, err := graphdriver.GetFSMagic(home) if err != nil { return nil, err @@ -70,7 +69,7 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) if err != nil { return nil, err } - if err := idtools.MkdirAllAs(filepath.Join(home, "subvolumes"), 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(filepath.Join(home, "subvolumes"), 0o700, rootUID, rootGID); err != nil { return nil, err } @@ -127,7 +126,7 @@ func parseOptions(opt []string) (btrfsOptions, bool, error) { // Driver contains information about the filesystem mounted. type Driver struct { - //root of the file system + // root of the file system home string uidMaps []idtools.IDMap gidMaps []idtools.IDMap @@ -226,7 +225,7 @@ func subvolSnapshot(src, dest, name string) error { var args C.struct_btrfs_ioctl_vol_args_v2 args.fd = C.__s64(getDirFd(srcDir)) - var cs = C.CString(name) + cs := C.CString(name) C.set_name_btrfs_ioctl_vol_args_v2(&args, cs) C.free(unsafe.Pointer(cs)) @@ -485,7 +484,7 @@ func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { if err != nil { return err } - if err := idtools.MkdirAllAs(subvolumes, 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(subvolumes, 0o700, rootUID, rootGID); err != nil { return err } if parent == "" { @@ -523,10 +522,10 @@ func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) error { if err := d.setStorageSize(path.Join(subvolumes, id), driver); err != nil { return err } - if err := idtools.MkdirAllAs(quotas, 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(quotas, 0o700, rootUID, rootGID); err != nil { return err } - if err := os.WriteFile(path.Join(quotas, id), []byte(fmt.Sprint(driver.options.size)), 0644); err != nil { + if err := os.WriteFile(path.Join(quotas, id), []byte(fmt.Sprint(driver.options.size)), 0o644); err != nil { return err } } diff --git a/drivers/chown_windows.go b/drivers/chown_windows.go index 1845a4e08..06ccf9fa4 100644 --- a/drivers/chown_windows.go +++ b/drivers/chown_windows.go @@ -10,8 +10,7 @@ import ( "github.com/containers/storage/pkg/idtools" ) -type platformChowner struct { -} +type platformChowner struct{} func newLChowner() *platformChowner { return &platformChowner{} diff --git a/drivers/copy/copy_linux.go b/drivers/copy/copy_linux.go index aa88c1a74..9c3d7c668 100644 --- a/drivers/copy/copy_linux.go +++ b/drivers/copy/copy_linux.go @@ -11,6 +11,7 @@ package copy #endif */ import "C" + import ( "container/list" "errors" diff --git a/drivers/copy/copy_test.go b/drivers/copy/copy_test.go index 2e67e2df7..da804a815 100644 --- a/drivers/copy/copy_test.go +++ b/drivers/copy/copy_test.go @@ -92,7 +92,7 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) { for i := 0; i < 10; i++ { dirName := filepath.Join(srcDir, fmt.Sprintf("srcdir-%d", i)) // Owner all bits set - assert.NilError(t, os.Mkdir(dirName, randomMode(0700))) + assert.NilError(t, os.Mkdir(dirName, randomMode(0o700))) populateSrcDir(t, dirName, remainingDepth-1) assert.NilError(t, system.Chtimes(dirName, aTime, mTime)) } @@ -100,7 +100,7 @@ func populateSrcDir(t *testing.T, srcDir string, remainingDepth int) { for i := 0; i < 10; i++ { fileName := filepath.Join(srcDir, fmt.Sprintf("srcfile-%d", i)) // Owner read bit set - assert.NilError(t, os.WriteFile(fileName, []byte{}, randomMode(0400))) + assert.NilError(t, os.WriteFile(fileName, []byte{}, randomMode(0o400))) assert.NilError(t, system.Chtimes(fileName, aTime, mTime)) } } @@ -114,7 +114,7 @@ func doCopyTest(t *testing.T, copyWithFileRange, copyWithFileClone *bool) { buf := make([]byte, 1024) _, err := r.Read(buf) assert.NilError(t, err) - assert.NilError(t, os.WriteFile(srcFilename, buf, 0777)) + assert.NilError(t, os.WriteFile(srcFilename, buf, 0o777)) fileinfo, err := os.Stat(srcFilename) assert.NilError(t, err) @@ -134,7 +134,7 @@ func TestCopyHardlink(t *testing.T) { srcFile2 := filepath.Join(srcDir, "file2") dstFile1 := filepath.Join(dstDir, "file1") dstFile2 := filepath.Join(dstDir, "file2") - assert.NilError(t, os.WriteFile(srcFile1, []byte{}, 0777)) + assert.NilError(t, os.WriteFile(srcFile1, []byte{}, 0o777)) assert.NilError(t, os.Link(srcFile1, srcFile2)) assert.Check(t, DirCopy(srcDir, dstDir, Content, false)) diff --git a/drivers/counter.go b/drivers/counter.go index 015766676..964dcaf2f 100644 --- a/drivers/counter.go +++ b/drivers/counter.go @@ -53,7 +53,7 @@ func (c *RefCounter) incdec(path string, infoOp func(minfo *minfo)) int { } } else if !c.checker.IsMounted(path) { // if the unmount was performed outside of this process (e.g. conmon cleanup) - //the ref counter would lose track of it. Check if it is still mounted. + // the ref counter would lose track of it. Check if it is still mounted. m.count = 0 } infoOp(m) diff --git a/drivers/devmapper/device_setup.go b/drivers/devmapper/device_setup.go index 56c117d1b..388602b63 100644 --- a/drivers/devmapper/device_setup.go +++ b/drivers/devmapper/device_setup.go @@ -177,7 +177,7 @@ func writeLVMConfig(root string, cfg directLVMConfig) error { if err != nil { return fmt.Errorf("marshalling direct lvm config: %w", err) } - if err := os.WriteFile(p, b, 0600); err != nil { + if err := os.WriteFile(p, b, 0o600); err != nil { return fmt.Errorf("writing direct lvm config to file: %w", err) } return nil @@ -193,7 +193,7 @@ func setupDirectLVM(cfg directLVMConfig) error { } } - err := os.MkdirAll(lvmProfileDir, 0755) + err := os.MkdirAll(lvmProfileDir, 0o755) if err != nil { return fmt.Errorf("creating lvm profile directory: %w", err) } @@ -241,7 +241,7 @@ func setupDirectLVM(cfg directLVMConfig) error { } profile := fmt.Sprintf("activation{\nthin_pool_autoextend_threshold=%d\nthin_pool_autoextend_percent=%d\n}", cfg.AutoExtendThreshold, cfg.AutoExtendPercent) - err = os.WriteFile(lvmProfileDir+"/storage-thinpool.profile", []byte(profile), 0600) + err = os.WriteFile(lvmProfileDir+"/storage-thinpool.profile", []byte(profile), 0o600) if err != nil { return fmt.Errorf("writing storage thinp autoextend profile: %w", err) } diff --git a/drivers/devmapper/deviceset.go b/drivers/devmapper/deviceset.go index 8603a0516..5d8df8a78 100644 --- a/drivers/devmapper/deviceset.go +++ b/drivers/devmapper/deviceset.go @@ -124,7 +124,7 @@ type DeviceSet struct { deletionWorkerTicker *time.Ticker uidMaps []idtools.IDMap gidMaps []idtools.IDMap - minFreeSpacePercent uint32 //min free space percentage in thinpool + minFreeSpacePercent uint32 // min free space percentage in thinpool xfsNospaceRetries string // max retries when xfs receives ENOSPC lvmSetupConfig directLVMConfig } @@ -273,7 +273,7 @@ func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) { if err != nil { return "", err } - if err := idtools.MkdirAllAs(dirname, 0700, uid, gid); err != nil { + if err := idtools.MkdirAllAs(dirname, 0o700, uid, gid); err != nil { return "", err } @@ -282,7 +282,7 @@ func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) { return "", err } logrus.Debugf("devmapper: Creating loopback file %s for device-manage use", filename) - file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600) + file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o600) if err != nil { return "", err } @@ -293,7 +293,7 @@ func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) { } } else { if fi.Size() < size { - file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600) + file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o600) if err != nil { return "", err } @@ -421,7 +421,6 @@ func (devices *DeviceSet) constructDeviceIDMap() { } func (devices *DeviceSet) deviceFileWalkFunction(path string, name string) error { - // Skip some of the meta files which are not device files. if strings.HasSuffix(name, ".migrated") { logrus.Debugf("devmapper: Skipping file %s", path) @@ -458,7 +457,7 @@ func (devices *DeviceSet) loadDeviceFilesOnStart() error { logrus.Debug("devmapper: loadDeviceFilesOnStart()") defer logrus.Debug("devmapper: loadDeviceFilesOnStart() END") - var scan = func(path string, d fs.DirEntry, err error) error { + scan := func(path string, d fs.DirEntry, err error) error { if err != nil { logrus.Debugf("devmapper: Can't walk the file %s: %v", path, err) return nil @@ -1156,7 +1155,6 @@ func (devices *DeviceSet) setupVerifyBaseImageUUIDFS(baseInfo *devInfo) error { } func (devices *DeviceSet) checkGrowBaseDeviceFS(info *devInfo) error { - if !userBaseSize { return nil } @@ -1195,7 +1193,7 @@ func (devices *DeviceSet) growFS(info *devInfo) error { fsMountPoint := "/run/containers/storage/mnt" if _, err := os.Stat(fsMountPoint); os.IsNotExist(err) { - if err := os.MkdirAll(fsMountPoint, 0700); err != nil { + if err := os.MkdirAll(fsMountPoint, 0o700); err != nil { return err } defer os.RemoveAll(fsMountPoint) @@ -1661,7 +1659,6 @@ func (devices *DeviceSet) loadThinPoolLoopBackInfo() error { } func (devices *DeviceSet) enableDeferredRemovalDeletion() error { - // If user asked for deferred removal then check both libdm library // and kernel driver support deferred removal otherwise error out. if enableDeferredRemoval { @@ -1699,19 +1696,19 @@ func (devices *DeviceSet) initDevmapper(doInit bool) (retErr error) { } } - //create the root dir of the devmapper driver ownership to match this - //daemon's remapped root uid/gid so containers can start properly + // create the root dir of the devmapper driver ownership to match this + // daemon's remapped root uid/gid so containers can start properly uid, gid, err := idtools.GetRootUIDGID(devices.uidMaps, devices.gidMaps) if err != nil { return err } - if err := idtools.MkdirAs(devices.root, 0700, uid, gid); err != nil { + if err := idtools.MkdirAs(devices.root, 0o700, uid, gid); err != nil { return err } - if err := os.MkdirAll(devices.metadataDir(), 0700); err != nil { + if err := os.MkdirAll(devices.metadataDir(), 0o700); err != nil { return err } - if err := idtools.MkdirAs(filepath.Join(devices.root, "mnt"), 0700, uid, gid); err != nil && !errors.Is(err, os.ErrExist) { + if err := idtools.MkdirAs(filepath.Join(devices.root, "mnt"), 0o700, uid, gid); err != nil && !errors.Is(err, os.ErrExist) { return err } @@ -1818,7 +1815,7 @@ func (devices *DeviceSet) initDevmapper(doInit bool) (retErr error) { devices.dataLoopFile = data devices.dataDevice = dataFile.Name() } else { - dataFile, err = os.OpenFile(devices.dataDevice, os.O_RDWR, 0600) + dataFile, err = os.OpenFile(devices.dataDevice, os.O_RDWR, 0o600) if err != nil { return err } @@ -1851,7 +1848,7 @@ func (devices *DeviceSet) initDevmapper(doInit bool) (retErr error) { devices.metadataLoopFile = metadata devices.metadataDevice = metadataFile.Name() } else { - metadataFile, err = os.OpenFile(devices.metadataDevice, os.O_RDWR, 0600) + metadataFile, err = os.OpenFile(devices.metadataDevice, os.O_RDWR, 0o600) if err != nil { return err } @@ -1973,7 +1970,6 @@ func (devices *DeviceSet) AddDevice(hash, baseHash string, storageOpt map[string } func (devices *DeviceSet) parseStorageOpt(storageOpt map[string]string) (uint64, error) { - // Read size to change the block device size per container. for key, val := range storageOpt { key := strings.ToLower(key) @@ -2547,7 +2543,6 @@ func (devices *DeviceSet) GetDeviceStatus(hash string) (*DevStatus, error) { } sizeInSectors, mappedSectors, highestMappedSector, err := devices.deviceStatus(info.DevName()) - if err != nil { return nil, err } diff --git a/drivers/devmapper/devmapper_test.go b/drivers/devmapper/devmapper_test.go index 89a74f3c8..506a64918 100644 --- a/drivers/devmapper/devmapper_test.go +++ b/drivers/devmapper/devmapper_test.go @@ -61,7 +61,7 @@ func getBaseLoopStats() (*syscall.Stat_t, error) { return &syscall.Stat_t{ Uid: 0, Gid: 0, - Mode: 0660, + Mode: 0o660, }, nil } return nil, err @@ -123,7 +123,7 @@ func testChangeLoopBackSize(t *testing.T, delta, expectDataSize, expectMetaDataS if err := driver.Cleanup(); err != nil { t.Fatal(err) } - //Reload + // Reload d, err := Init(driver.home, graphdriver.Options{DriverOptions: []string{ fmt.Sprintf("dm.loopdatasize=%d", defaultDataLoopbackSize+delta), fmt.Sprintf("dm.loopmetadatasize=%d", defaultMetaDataLoopbackSize+delta), diff --git a/drivers/devmapper/driver.go b/drivers/devmapper/driver.go index f53f0625f..8b8a1d177 100644 --- a/drivers/devmapper/driver.go +++ b/drivers/devmapper/driver.go @@ -20,7 +20,7 @@ import ( "golang.org/x/sys/unix" ) -const defaultPerms = os.FileMode(0555) +const defaultPerms = os.FileMode(0o555) func init() { graphdriver.MustRegister("devicemapper", Init) @@ -102,7 +102,6 @@ func (d *Driver) Status() [][2]string { // Metadata returns a map of information about the device. func (d *Driver) Metadata(id string) (map[string]string, error) { m, err := d.DeviceSet.exportDeviceMetadata(id) - if err != nil { return nil, err } @@ -201,11 +200,11 @@ func (d *Driver) Get(id string, options graphdriver.MountOpts) (string, error) { } // Create the target directories if they don't exist - if err := idtools.MkdirAllAs(path.Join(d.home, "mnt"), 0755, uid, gid); err != nil { + if err := idtools.MkdirAllAs(path.Join(d.home, "mnt"), 0o755, uid, gid); err != nil { d.ctr.Decrement(mp) return "", err } - if err := idtools.MkdirAs(mp, 0755, uid, gid); err != nil && !os.IsExist(err) { + if err := idtools.MkdirAs(mp, 0o755, uid, gid); err != nil && !os.IsExist(err) { d.ctr.Decrement(mp) return "", err } @@ -226,7 +225,7 @@ func (d *Driver) Get(id string, options graphdriver.MountOpts) (string, error) { if _, err := os.Stat(idFile); err != nil && os.IsNotExist(err) { // Create an "id" file with the container/image id in it to help reconstruct this in case // of later problems - if err := os.WriteFile(idFile, []byte(id), 0600); err != nil { + if err := os.WriteFile(idFile, []byte(id), 0o600); err != nil { d.ctr.Decrement(mp) d.DeviceSet.UnmountDevice(id, mp) return "", err diff --git a/drivers/driver_darwin.go b/drivers/driver_darwin.go index 880c45a50..b60883a9e 100644 --- a/drivers/driver_darwin.go +++ b/drivers/driver_darwin.go @@ -1,11 +1,9 @@ package graphdriver -var ( - // Slice of drivers that should be used in order - Priority = []string{ - "vfs", - } -) +// Slice of drivers that should be used in order +var Priority = []string{ + "vfs", +} // GetFSMagic returns the filesystem id given the path. func GetFSMagic(rootpath string) (FsMagic, error) { diff --git a/drivers/driver_freebsd.go b/drivers/driver_freebsd.go index 4954c4c35..a6072ab56 100644 --- a/drivers/driver_freebsd.go +++ b/drivers/driver_freebsd.go @@ -31,8 +31,7 @@ func NewDefaultChecker() Checker { return &defaultChecker{} } -type defaultChecker struct { -} +type defaultChecker struct{} func (c *defaultChecker) IsMounted(path string) bool { m, _ := mount.Mounted(path) diff --git a/drivers/driver_linux.go b/drivers/driver_linux.go index 129eae1f2..3925644ae 100644 --- a/drivers/driver_linux.go +++ b/drivers/driver_linux.go @@ -161,8 +161,7 @@ func NewDefaultChecker() Checker { return &defaultChecker{} } -type defaultChecker struct { -} +type defaultChecker struct{} func (c *defaultChecker) IsMounted(path string) bool { m, _ := mount.Mounted(path) diff --git a/drivers/driver_solaris.go b/drivers/driver_solaris.go index 61fbb4ea7..6b6373a37 100644 --- a/drivers/driver_solaris.go +++ b/drivers/driver_solaris.go @@ -16,6 +16,7 @@ static inline struct statvfs *getstatfs(char *s) { } */ import "C" + import ( "path/filepath" "unsafe" @@ -69,8 +70,7 @@ func NewDefaultChecker() Checker { return &defaultChecker{} } -type defaultChecker struct { -} +type defaultChecker struct{} func (c *defaultChecker) IsMounted(path string) bool { m, _ := mount.Mounted(path) @@ -80,7 +80,6 @@ func (c *defaultChecker) IsMounted(path string) bool { // Mounted checks if the given path is mounted as the fs type // Solaris supports only ZFS for now func Mounted(fsType FsMagic, mountPath string) (bool, error) { - cs := C.CString(filepath.Dir(mountPath)) defer C.free(unsafe.Pointer(cs)) buf := C.getstatfs(cs) diff --git a/drivers/driver_unsupported.go b/drivers/driver_unsupported.go index f62618923..7dfbef007 100644 --- a/drivers/driver_unsupported.go +++ b/drivers/driver_unsupported.go @@ -3,12 +3,10 @@ package graphdriver -var ( - // Slice of drivers that should be used in an order - Priority = []string{ - "unsupported", - } -) +// Slice of drivers that should be used in an order +var Priority = []string{ + "unsupported", +} // GetFSMagic returns the filesystem id given the path. func GetFSMagic(rootpath string) (FsMagic, error) { diff --git a/drivers/driver_windows.go b/drivers/driver_windows.go index 16f16c041..54bd139a3 100644 --- a/drivers/driver_windows.go +++ b/drivers/driver_windows.go @@ -1,11 +1,9 @@ package graphdriver -var ( - // Slice of drivers that should be used in order - Priority = []string{ - "windowsfilter", - } -) +// Slice of drivers that should be used in order +var Priority = []string{ + "windowsfilter", +} // GetFSMagic returns the filesystem id given the path. func GetFSMagic(rootpath string) (FsMagic, error) { diff --git a/drivers/fsdiff.go b/drivers/fsdiff.go index 6b2496ec5..a0e046458 100644 --- a/drivers/fsdiff.go +++ b/drivers/fsdiff.go @@ -14,11 +14,9 @@ import ( "github.com/sirupsen/logrus" ) -var ( - // ApplyUncompressedLayer defines the unpack method used by the graph - // driver. - ApplyUncompressedLayer = chrootarchive.ApplyUncompressedLayer -) +// ApplyUncompressedLayer defines the unpack method used by the graph +// driver. +var ApplyUncompressedLayer = chrootarchive.ApplyUncompressedLayer // NaiveDiffDriver takes a ProtoDriver and adds the // capability of the Diffing methods which it may or may not @@ -173,7 +171,7 @@ func (gdw *NaiveDiffDriver) ApplyDiff(id, parent string, options ApplyDiffOpts) } defer driverPut(driver, id, &err) - defaultForceMask := os.FileMode(0700) + defaultForceMask := os.FileMode(0o700) var forceMask *os.FileMode // = nil if runtime.GOOS == "darwin" { forceMask = &defaultForceMask diff --git a/drivers/graphtest/graphbench_unix.go b/drivers/graphtest/graphbench_unix.go index e3e6f2f28..a5b10ec16 100644 --- a/drivers/graphtest/graphbench_unix.go +++ b/drivers/graphtest/graphbench_unix.go @@ -176,7 +176,7 @@ func DriverBenchDiffApplyN(b *testing.B, fileCount int, drivername string, drive if applyDiffSize != diffSize { // TODO: enforce this - //b.Fatalf("Apply diff size different, got %d, expected %s", applyDiffSize, diffSize) + // b.Fatalf("Apply diff size different, got %d, expected %s", applyDiffSize, diffSize) } if err := checkManyFiles(driver, diff, fileCount, 6); err != nil { b.Fatal(err) diff --git a/drivers/graphtest/graphtest_unix.go b/drivers/graphtest/graphtest_unix.go index 3001a8933..e2a176ccd 100644 --- a/drivers/graphtest/graphtest_unix.go +++ b/drivers/graphtest/graphtest_unix.go @@ -23,9 +23,7 @@ import ( "golang.org/x/sys/unix" ) -var ( - drv *Driver -) +var drv *Driver const ( defaultPerms = os.FileMode(0o555) @@ -52,7 +50,7 @@ func newDriver(t testing.TB, name string, options []string) *Driver { runroot, err := os.MkdirTemp("", "storage-graphtest-") require.NoError(t, err) - require.NoError(t, os.MkdirAll(root, 0755)) + require.NoError(t, os.MkdirAll(root, 0o755)) d, err := graphdriver.GetDriver(name, graphdriver.Options{DriverOptions: options, Root: root, RunRoot: runroot}) if err != nil { t.Logf("graphdriver: %v\n", err) @@ -416,7 +414,7 @@ func writeRandomFile(path string, size uint64) error { return err } - return os.WriteFile(path, data, 0700) + return os.WriteFile(path, data, 0o700) } // DriverTestSetQuota Create a driver and test setting quota. @@ -482,14 +480,14 @@ func DriverTestEcho(t testing.TB, drivername string, driverOptions ...string) { for i := 0; i < components-1; i++ { path = filepath.Join(path, fmt.Sprintf("subdir%d", i+1)) paths = append(paths, path) - if err = os.Mkdir(filepath.Join(root, path), 0700); err != nil { + if err = os.Mkdir(filepath.Join(root, path), 0o700); err != nil { t.Fatal(err) } expectedChanges = append(expectedChanges, archive.Change{Kind: archive.ChangeAdd, Path: path}) } path = filepath.Join(path, "file") paths = append(paths, path) - if err = os.WriteFile(filepath.Join(root, path), randomContent(128, int64(depth)), 0600); err != nil { + if err = os.WriteFile(filepath.Join(root, path), randomContent(128, int64(depth)), 0o600); err != nil { t.Fatal(err) } expectedChanges = append(expectedChanges, archive.Change{Kind: archive.ChangeAdd, Path: path}) @@ -544,12 +542,12 @@ func DriverTestEcho(t testing.TB, drivername string, driverOptions ...string) { expectedChanges = append(expectedChanges, archive.Change{Kind: archive.ChangeModify, Path: paths[i]}) } for i := depth; i < components-1; i++ { - if err = os.Mkdir(filepath.Join(root, paths[i]), 0700); err != nil { + if err = os.Mkdir(filepath.Join(root, paths[i]), 0o700); err != nil { t.Fatal(err) } expectedChanges = append(expectedChanges, archive.Change{Kind: archive.ChangeAdd, Path: paths[i]}) } - if err = os.WriteFile(filepath.Join(root, paths[len(paths)-1]), randomContent(128, int64(depth)), 0600); err != nil { + if err = os.WriteFile(filepath.Join(root, paths[len(paths)-1]), randomContent(128, int64(depth)), 0o600); err != nil { t.Fatal(err) } expectedChanges = append(expectedChanges, archive.Change{Kind: archive.ChangeAdd, Path: paths[len(paths)-1]}) diff --git a/drivers/graphtest/testutil.go b/drivers/graphtest/testutil.go index 473dd17ee..12f20d007 100644 --- a/drivers/graphtest/testutil.go +++ b/drivers/graphtest/testutil.go @@ -40,17 +40,17 @@ func addFiles(drv graphdriver.Driver, layer string, seed int64) error { } defer drv.Put(layer) - if err := os.WriteFile(path.Join(root, "file-a"), randomContent(64, seed), 0755); err != nil { + if err := os.WriteFile(path.Join(root, "file-a"), randomContent(64, seed), 0o755); err != nil { return err } - if err := os.MkdirAll(path.Join(root, "dir-b"), 0755); err != nil { + if err := os.MkdirAll(path.Join(root, "dir-b"), 0o755); err != nil { return err } - if err := os.WriteFile(path.Join(root, "dir-b", "file-b"), randomContent(128, seed+1), 0755); err != nil { + if err := os.WriteFile(path.Join(root, "dir-b", "file-b"), randomContent(128, seed+1), 0o755); err != nil { return err } - return os.WriteFile(path.Join(root, "file-c"), randomContent(128*128, seed+2), 0755) + return os.WriteFile(path.Join(root, "file-c"), randomContent(128*128, seed+2), 0o755) } func checkFile(drv graphdriver.Driver, layer, filename string, content []byte) error { @@ -79,7 +79,7 @@ func addFile(drv graphdriver.Driver, layer, filename string, content []byte) err } defer drv.Put(layer) - return os.WriteFile(path.Join(root, filename), content, 0755) + return os.WriteFile(path.Join(root, filename), content, 0o755) } func addDirectory(drv graphdriver.Driver, layer, dir string) error { @@ -89,7 +89,7 @@ func addDirectory(drv graphdriver.Driver, layer, dir string) error { } defer drv.Put(layer) - return os.MkdirAll(path.Join(root, dir), 0755) + return os.MkdirAll(path.Join(root, dir), 0o755) } func removeAll(drv graphdriver.Driver, layer string, names ...string) error { @@ -132,12 +132,12 @@ func addManyFiles(drv graphdriver.Driver, layer string, count int, seed int64) e for i := 0; i < count; i += 100 { dir := path.Join(root, fmt.Sprintf("directory-%d", i)) - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return err } for j := 0; i+j < count && j < 100; j++ { file := path.Join(dir, fmt.Sprintf("file-%d", i+j)) - if err := os.WriteFile(file, randomContent(64, seed+int64(i+j)), 0755); err != nil { + if err := os.WriteFile(file, randomContent(64, seed+int64(i+j)), 0o755); err != nil { return err } } @@ -156,7 +156,7 @@ func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64 changes := []archive.Change{} for i := 0; i < count; i += 100 { archiveRoot := fmt.Sprintf("/directory-%d", i) - if err := os.MkdirAll(path.Join(root, archiveRoot), 0755); err != nil { + if err := os.MkdirAll(path.Join(root, archiveRoot), 0o755); err != nil { return nil, err } for j := 0; i+j < count && j < 100; j++ { @@ -177,7 +177,7 @@ func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64 return nil, err } for updatedFileInfo == nil || updatedFileInfo.ModTime().Equal(originalFileInfo.ModTime()) { - if err := os.WriteFile(path.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { + if err := os.WriteFile(path.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0o755); err != nil { return nil, err } if updatedFileInfo, err = os.Stat(path.Join(root, change.Path)); err != nil { @@ -188,7 +188,7 @@ func changeManyFiles(drv graphdriver.Driver, layer string, count int, seed int64 case 1: change.Path = path.Join(archiveRoot, fmt.Sprintf("file-%d-%d", seed, i+j)) change.Kind = archive.ChangeAdd - if err := os.WriteFile(path.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0755); err != nil { + if err := os.WriteFile(path.Join(root, change.Path), randomContent(64, seed+int64(i+j)), 0o755); err != nil { return nil, err } // Remove file @@ -267,17 +267,17 @@ func addLayerFiles(drv graphdriver.Driver, layer, parent string, i int) error { } defer drv.Put(layer) - if err := os.WriteFile(path.Join(root, "top-id"), []byte(layer), 0755); err != nil { + if err := os.WriteFile(path.Join(root, "top-id"), []byte(layer), 0o755); err != nil { return err } layerDir := path.Join(root, fmt.Sprintf("layer-%d", i)) - if err := os.MkdirAll(layerDir, 0755); err != nil { + if err := os.MkdirAll(layerDir, 0o755); err != nil { return err } - if err := os.WriteFile(path.Join(layerDir, "layer-id"), []byte(layer), 0755); err != nil { + if err := os.WriteFile(path.Join(layerDir, "layer-id"), []byte(layer), 0o755); err != nil { return err } - if err := os.WriteFile(path.Join(layerDir, "parent-id"), []byte(parent), 0755); err != nil { + if err := os.WriteFile(path.Join(layerDir, "parent-id"), []byte(parent), 0o755); err != nil { return err } diff --git a/drivers/overlay/check.go b/drivers/overlay/check.go index b6bf63288..60980994b 100644 --- a/drivers/overlay/check.go +++ b/drivers/overlay/check.go @@ -38,22 +38,22 @@ func doesSupportNativeDiff(d, mountOpts string) error { }() // Make directories l1/d, l1/d1, l2/d, l3, work, merged - if err := os.MkdirAll(filepath.Join(td, "l1", "d"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "l1", "d"), 0o755); err != nil { return err } - if err := os.MkdirAll(filepath.Join(td, "l1", "d1"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "l1", "d1"), 0o755); err != nil { return err } - if err := os.MkdirAll(filepath.Join(td, "l2", "d"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "l2", "d"), 0o755); err != nil { return err } - if err := os.Mkdir(filepath.Join(td, "l3"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "l3"), 0o755); err != nil { return err } - if err := os.Mkdir(filepath.Join(td, "work"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "work"), 0o755); err != nil { return err } - if err := os.Mkdir(filepath.Join(td, "merged"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "merged"), 0o755); err != nil { return err } @@ -82,7 +82,7 @@ func doesSupportNativeDiff(d, mountOpts string) error { }() // Touch file in d to force copy up of opaque directory "d" from "l2" to "l3" - if err := os.WriteFile(filepath.Join(td, "merged", "d", "f"), []byte{}, 0644); err != nil { + if err := os.WriteFile(filepath.Join(td, "merged", "d", "f"), []byte{}, 0o644); err != nil { return fmt.Errorf("failed to write to merged directory: %w", err) } @@ -132,19 +132,19 @@ func doesMetacopy(d, mountOpts string) (bool, error) { }() // Make directories l1, l2, work, merged - if err := os.MkdirAll(filepath.Join(td, "l1"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "l1"), 0o755); err != nil { return false, err } - if err := ioutils.AtomicWriteFile(filepath.Join(td, "l1", "f"), []byte{0xff}, 0700); err != nil { + if err := ioutils.AtomicWriteFile(filepath.Join(td, "l1", "f"), []byte{0xff}, 0o700); err != nil { return false, err } - if err := os.MkdirAll(filepath.Join(td, "l2"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "l2"), 0o755); err != nil { return false, err } - if err := os.Mkdir(filepath.Join(td, "work"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "work"), 0o755); err != nil { return false, err } - if err := os.Mkdir(filepath.Join(td, "merged"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "merged"), 0o755); err != nil { return false, err } // Mount using the mandatory options and configured options @@ -170,7 +170,7 @@ func doesMetacopy(d, mountOpts string) (bool, error) { }() // Make a change that only impacts the inode, and check if the pulled-up copy is marked // as a metadata-only copy - if err := os.Chmod(filepath.Join(td, "merged", "f"), 0600); err != nil { + if err := os.Chmod(filepath.Join(td, "merged", "f"), 0o600); err != nil { return false, fmt.Errorf("changing permissions on file for metacopy check: %w", err) } metacopy, err := system.Lgetxattr(filepath.Join(td, "l2", "f"), archive.GetOverlayXattrName("metacopy")) @@ -196,16 +196,16 @@ func doesVolatile(d string) (bool, error) { } }() - if err := os.MkdirAll(filepath.Join(td, "lower"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "lower"), 0o755); err != nil { return false, err } - if err := os.MkdirAll(filepath.Join(td, "upper"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(td, "upper"), 0o755); err != nil { return false, err } - if err := os.Mkdir(filepath.Join(td, "work"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "work"), 0o755); err != nil { return false, err } - if err := os.Mkdir(filepath.Join(td, "merged"), 0755); err != nil { + if err := os.Mkdir(filepath.Join(td, "merged"), 0o755); err != nil { return false, err } // Mount using the mandatory options and configured options @@ -241,11 +241,11 @@ func supportsIdmappedLowerLayers(home string) (bool, error) { upperDir := filepath.Join(layerDir, "upper") workDir := filepath.Join(layerDir, "work") - _ = idtools.MkdirAs(mergedDir, 0700, 0, 0) - _ = idtools.MkdirAs(lowerDir, 0700, 0, 0) - _ = idtools.MkdirAs(lowerMappedDir, 0700, 0, 0) - _ = idtools.MkdirAs(upperDir, 0700, 0, 0) - _ = idtools.MkdirAs(workDir, 0700, 0, 0) + _ = idtools.MkdirAs(mergedDir, 0o700, 0, 0) + _ = idtools.MkdirAs(lowerDir, 0o700, 0, 0) + _ = idtools.MkdirAs(lowerMappedDir, 0o700, 0, 0) + _ = idtools.MkdirAs(upperDir, 0o700, 0, 0) + _ = idtools.MkdirAs(workDir, 0o700, 0, 0) mapping := []idtools.IDMap{ { diff --git a/drivers/overlay/mount.go b/drivers/overlay/mount.go index de47951d4..33e60b118 100644 --- a/drivers/overlay/mount.go +++ b/drivers/overlay/mount.go @@ -55,7 +55,7 @@ func mountOverlayFrom(dir, device, target, mType string, flags uintptr, label st w.Close() return fmt.Errorf("mountfrom error on re-exec cmd: %w", err) } - //write the options to the pipe for the untar exec to read + // write the options to the pipe for the untar exec to read if err := json.NewEncoder(w).Encode(options); err != nil { w.Close() return fmt.Errorf("mountfrom json encode to pipe failed: %w", err) diff --git a/drivers/overlay/overlay.go b/drivers/overlay/overlay.go index 2ef74f86a..5431da4e4 100644 --- a/drivers/overlay/overlay.go +++ b/drivers/overlay/overlay.go @@ -40,13 +40,11 @@ import ( "golang.org/x/sys/unix" ) -var ( - // untar defines the untar method - untar = chrootarchive.UntarUncompressed -) +// untar defines the untar method +var untar = chrootarchive.UntarUncompressed const ( - defaultPerms = os.FileMode(0555) + defaultPerms = os.FileMode(0o555) selinuxLabelTest = "system_u:object_r:container_file_t:s0" mountProgramFlagFile = ".has-mount-program" ) @@ -339,17 +337,17 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) } // Create the driver home dir - if err := idtools.MkdirAllAs(path.Join(home, linkDir), 0755, 0, 0); err != nil { + if err := idtools.MkdirAllAs(path.Join(home, linkDir), 0o755, 0, 0); err != nil { return nil, err } if options.ImageStore != "" { - if err := idtools.MkdirAllAs(path.Join(options.ImageStore, linkDir), 0755, 0, 0); err != nil { + if err := idtools.MkdirAllAs(path.Join(options.ImageStore, linkDir), 0o755, 0, 0); err != nil { return nil, err } } - if err := idtools.MkdirAllAs(runhome, 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(runhome, 0o700, rootUID, rootGID); err != nil { return nil, err } @@ -365,12 +363,12 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) if opts.mountProgram != "" { if unshare.IsRootless() && isNetworkFileSystem(fsMagic) && opts.forceMask == nil { - m := os.FileMode(0700) + m := os.FileMode(0o700) opts.forceMask = &m logrus.Warnf("Network file system detected as backing store. Enforcing overlay option `force_mask=\"%o\"`. Add it to storage.conf to silence this warning", m) } - if err := os.WriteFile(getMountProgramFlagFile(home), []byte("true"), 0600); err != nil { + if err := os.WriteFile(getMountProgramFlagFile(home), []byte("true"), 0o600); err != nil { return nil, err } } else { @@ -581,9 +579,9 @@ func parseOptions(options []string) (*overlayOptions, error) { var mask int64 switch val { case "shared": - mask = 0755 + mask = 0o755 case "private": - mask = 0700 + mask = 0o700 default: mask, err = strconv.ParseInt(val, 8, 32) if err != nil { @@ -648,7 +646,7 @@ func SupportsNativeOverlay(home, runhome string) (bool, error) { if err != nil && !os.IsNotExist(err) { return false, err } - if err := os.WriteFile(getMountProgramFlagFile(home), []byte(fmt.Sprintf("%t", needsMountProgram)), 0600); err != nil && !os.IsNotExist(err) { + if err := os.WriteFile(getMountProgramFlagFile(home), []byte(fmt.Sprintf("%t", needsMountProgram)), 0o600); err != nil && !os.IsNotExist(err) { return false, err } if needsMountProgram { @@ -661,7 +659,7 @@ func SupportsNativeOverlay(home, runhome string) (bool, error) { for _, dir := range []string{home, runhome} { if _, err := os.Stat(dir); err != nil { - _ = idtools.MkdirAllAs(dir, 0700, 0, 0) + _ = idtools.MkdirAllAs(dir, 0o700, 0, 0) } } @@ -721,12 +719,12 @@ func supportsOverlay(home string, homeMagic graphdriver.FsMagic, rootUID, rootGI _ = os.RemoveAll(layerDir) _ = os.Remove(home) }() - _ = idtools.MkdirAs(mergedDir, 0700, rootUID, rootGID) - _ = idtools.MkdirAs(lower1Dir, 0700, rootUID, rootGID) - _ = idtools.MkdirAs(lower2Dir, 0700, rootUID, rootGID) - _ = idtools.MkdirAs(lower2Subdir, 0700, rootUID, rootGID) - _ = idtools.MkdirAs(upperDir, 0700, rootUID, rootGID) - _ = idtools.MkdirAs(workDir, 0700, rootUID, rootGID) + _ = idtools.MkdirAs(mergedDir, 0o700, rootUID, rootGID) + _ = idtools.MkdirAs(lower1Dir, 0o700, rootUID, rootGID) + _ = idtools.MkdirAs(lower2Dir, 0o700, rootUID, rootGID) + _ = idtools.MkdirAs(lower2Subdir, 0o700, rootUID, rootGID) + _ = idtools.MkdirAs(upperDir, 0o700, rootUID, rootGID) + _ = idtools.MkdirAs(workDir, 0o700, rootUID, rootGID) f, err := os.Create(lower2SubdirFile) if err != nil { logrus.Debugf("Unable to create test file: %v", err) @@ -744,7 +742,7 @@ func supportsOverlay(home string, homeMagic graphdriver.FsMagic, rootUID, rootGI if unshare.IsRootless() { flags = fmt.Sprintf("%s,userxattr", flags) } - if err := syscall.Mknod(filepath.Join(upperDir, "whiteout"), syscall.S_IFCHR|0600, int(unix.Mkdev(0, 0))); err != nil { + if err := syscall.Mknod(filepath.Join(upperDir, "whiteout"), syscall.S_IFCHR|0o600, int(unix.Mkdev(0, 0))); err != nil { logrus.Debugf("Unable to create kernel-style whiteout: %v", err) return supportsDType, fmt.Errorf("unable to create kernel-style whiteout: %w", err) } @@ -968,7 +966,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, disable } // Make the link directory if it does not exist - if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0755, 0, 0); err != nil { + if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0o755, 0, 0); err != nil { return err } @@ -982,13 +980,13 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, disable GID: rootGID, } - if err := idtools.MkdirAllAndChownNew(path.Dir(dir), 0755, idPair); err != nil { + if err := idtools.MkdirAllAndChownNew(path.Dir(dir), 0o755, idPair); err != nil { return err } workDirBase := dir if imageStore != "" { workDirBase = imageStore - if err := idtools.MkdirAllAndChownNew(path.Dir(imageStore), 0755, idPair); err != nil { + if err := idtools.MkdirAllAndChownNew(path.Dir(imageStore), 0o755, idPair); err != nil { return err } } @@ -1014,11 +1012,11 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, disable } } - if err := idtools.MkdirAllAndChownNew(dir, 0700, idPair); err != nil { + if err := idtools.MkdirAllAndChownNew(dir, 0o700, idPair); err != nil { return err } if imageStore != "" { - if err := idtools.MkdirAllAndChownNew(imageStore, 0700, idPair); err != nil { + if err := idtools.MkdirAllAndChownNew(imageStore, 0o700, idPair); err != nil { return err } } @@ -1096,20 +1094,20 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, disable } // Write link id to link file - if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0644); err != nil { + if err := os.WriteFile(path.Join(dir, "link"), []byte(lid), 0o644); err != nil { return err } - if err := idtools.MkdirAs(path.Join(workDirBase, "work"), 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAs(path.Join(workDirBase, "work"), 0o700, rootUID, rootGID); err != nil { return err } - if err := idtools.MkdirAs(path.Join(dir, "merged"), 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAs(path.Join(dir, "merged"), 0o700, rootUID, rootGID); err != nil { return err } // if no parent directory, create a dummy lower directory and skip writing a "lowers" file if parent == "" { - return idtools.MkdirAs(path.Join(dir, "empty"), 0700, rootUID, rootGID) + return idtools.MkdirAs(path.Join(dir, "empty"), 0o700, rootUID, rootGID) } lower, err := d.getLower(parent) @@ -1117,7 +1115,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, disable return err } if lower != "" { - if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0666); err != nil { + if err := os.WriteFile(path.Join(dir, lowerFile), []byte(lower), 0o666); err != nil { return err } } @@ -1312,7 +1310,7 @@ func (d *Driver) recreateSymlinks() error { return fmt.Errorf("reading driver home directory %q: %w", d.home, err) } // This makes the link directory if it doesn't exist - if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0755, 0, 0); err != nil { + if err := idtools.MkdirAllAs(path.Join(d.home, linkDir), 0o755, 0, 0); err != nil { return err } // Keep looping as long as we take some corrective action in each iteration @@ -1389,7 +1387,7 @@ func (d *Driver) recreateSymlinks() error { if err != nil || string(data) != link.Name() { // NOTE: If two or more links point to the same target, we will update linkFile // with every value of link.Name(), and set madeProgress = true every time. - if err := os.WriteFile(linkFile, []byte(link.Name()), 0644); err != nil { + if err := os.WriteFile(linkFile, []byte(link.Name()), 0o644); err != nil { errs = multierror.Append(errs, fmt.Errorf("correcting link for layer %s: %w", targetID, err)) continue } @@ -1565,7 +1563,7 @@ func (d *Driver) get(id string, disableShifting bool, options graphdriver.MountO mergedDir := path.Join(dir, "merged") // Create the driver merged dir - if err := idtools.MkdirAs(mergedDir, 0700, rootUID, rootGID); err != nil && !os.IsExist(err) { + if err := idtools.MkdirAs(mergedDir, 0o700, rootUID, rootGID); err != nil && !os.IsExist(err) { return "", err } if count := d.ctr.Increment(mergedDir); count > 1 { @@ -1601,7 +1599,7 @@ func (d *Driver) get(id string, disableShifting bool, options graphdriver.MountO if !disableShifting && len(options.UidMaps) > 0 && len(options.GidMaps) > 0 && d.options.mountProgram == "" { var newAbsDir []string mappedRoot := filepath.Join(d.home, id, "mapped") - if err := os.MkdirAll(mappedRoot, 0700); err != nil { + if err := os.MkdirAll(mappedRoot, 0o700); err != nil { return "", err } @@ -1911,7 +1909,7 @@ func (d *Driver) ApplyDiffWithDiffer(id, parent string, options *graphdriver.App var applyDir string if id == "" { - err := os.MkdirAll(d.getStagingDir(), 0700) + err := os.MkdirAll(d.getStagingDir(), 0o700) if err != nil && !os.IsExist(err) { return graphdriver.DriverWithDifferOutput{}, err } @@ -1964,7 +1962,6 @@ func (d *Driver) DifferTarget(id string) (string, error) { // ApplyDiff applies the new layer into a root func (d *Driver) ApplyDiff(id, parent string, options graphdriver.ApplyDiffOpts) (size int64, err error) { - if !d.isParent(id, parent) { if d.options.ignoreChownErrors { options.IgnoreChownErrors = d.options.ignoreChownErrors @@ -2284,7 +2281,7 @@ func (al *additionalLayer) CreateAs(id, parent string) error { } // tell the additional layer store that we use this layer. // mark this layer as "additional layer" - if err := os.WriteFile(path.Join(dir, "additionallayer"), []byte(al.path), 0644); err != nil { + if err := os.WriteFile(path.Join(dir, "additionallayer"), []byte(al.path), 0o644); err != nil { return err } notifyUseAdditionalLayer(al.path) diff --git a/drivers/quota/projectquota.go b/drivers/quota/projectquota.go index 2b051e410..8b6aafab8 100644 --- a/drivers/quota/projectquota.go +++ b/drivers/quota/projectquota.go @@ -50,6 +50,7 @@ struct fsxattr { #endif */ import "C" + import ( "errors" "fmt" @@ -98,7 +99,6 @@ func generateUniqueProjectID(path string) (uint32, error) { stat, ok := fileinfo.Sys().(*syscall.Stat_t) if !ok { return 0, fmt.Errorf("not a syscall.Stat_t %s", path) - } projectID := projectIDsAllocatedPerQuotaHome + (stat.Ino*projectIDsAllocatedPerQuotaHome)%(math.MaxUint32-projectIDsAllocatedPerQuotaHome) return uint32(projectID), nil @@ -191,7 +191,6 @@ func NewControl(basePath string) (*Control, error) { // SetQuota - assign a unique project id to directory and set the quota limits // for that project id func (q *Control) SetQuota(targetPath string, quota Quota) error { - projectID, ok := q.quotas[targetPath] if !ok { projectID = q.nextProjectID @@ -239,7 +238,7 @@ func (q *Control) setProjectQuota(projectID uint32, quota Quota) error { d.d_ino_softlimit = d.d_ino_hardlimit } - var cs = C.CString(q.backingFsBlockDev) + cs := C.CString(q.backingFsBlockDev) defer C.free(unsafe.Pointer(cs)) runQuotactl := func() syscall.Errno { @@ -307,7 +306,7 @@ func (q *Control) fsDiskQuotaFromPath(targetPath string) (C.fs_disk_quota_t, err // // get the quota limit for the container's project id // - var cs = C.CString(q.backingFsBlockDev) + cs := C.CString(q.backingFsBlockDev) defer C.free(unsafe.Pointer(cs)) _, _, errno := unix.Syscall6(unix.SYS_QUOTACTL, C.Q_XGETPQUOTA, @@ -428,7 +427,7 @@ func makeBackingFsDev(home string) (string, error) { backingFsBlockDev := path.Join(home, BackingFsBlockDeviceLink) backingFsBlockDevTmp := backingFsBlockDev + ".tmp" // Re-create just in case someone copied the home directory over to a new device - if err := unix.Mknod(backingFsBlockDevTmp, unix.S_IFBLK|0600, int(stat.Dev)); err != nil { + if err := unix.Mknod(backingFsBlockDevTmp, unix.S_IFBLK|0o600, int(stat.Dev)); err != nil { return "", fmt.Errorf("failed to mknod %s: %w", backingFsBlockDevTmp, err) } if err := unix.Rename(backingFsBlockDevTmp, backingFsBlockDev); err != nil { diff --git a/drivers/quota/projectquota_unsupported.go b/drivers/quota/projectquota_unsupported.go index 2f6c7f28f..648fd3379 100644 --- a/drivers/quota/projectquota_unsupported.go +++ b/drivers/quota/projectquota_unsupported.go @@ -15,8 +15,7 @@ type Quota struct { // Control - Context to be used by storage driver (e.g. overlay) // who wants to apply project quotas to container dirs -type Control struct { -} +type Control struct{} func NewControl(basePath string) (*Control, error) { return nil, errors.New("filesystem does not support, or has not enabled quotas") diff --git a/drivers/vfs/driver.go b/drivers/vfs/driver.go index 50a4adc0b..0facfb42e 100644 --- a/drivers/vfs/driver.go +++ b/drivers/vfs/driver.go @@ -20,7 +20,7 @@ import ( "github.com/vbatts/tar-split/tar/storage" ) -const defaultPerms = os.FileMode(0555) +const defaultPerms = os.FileMode(0o555) func init() { graphdriver.MustRegister("vfs", Init) @@ -36,7 +36,7 @@ func Init(home string, options graphdriver.Options) (graphdriver.Driver, error) } rootIDs := d.idMappings.RootPair() - if err := idtools.MkdirAllAndChown(filepath.Join(home, "dir"), 0700, rootIDs); err != nil { + if err := idtools.MkdirAllAndChown(filepath.Join(home, "dir"), 0o700, rootIDs); err != nil { return nil, err } for _, option := range options.DriverOptions { @@ -160,7 +160,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, ro bool dir := d.dir(id) rootIDs := idMappings.RootPair() - if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0700, rootIDs); err != nil { + if err := idtools.MkdirAllAndChown(filepath.Dir(dir), 0o700, rootIDs); err != nil { return err } @@ -172,7 +172,7 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, ro bool rootPerms := defaultPerms if runtime.GOOS == "darwin" { - rootPerms = os.FileMode(0700) + rootPerms = os.FileMode(0o700) } if parent != "" { @@ -202,7 +202,6 @@ func (d *Driver) create(id, parent string, opts *graphdriver.CreateOpts, ro bool } return nil - } func (d *Driver) dir(id string) string { @@ -312,7 +311,6 @@ func (d *Driver) UpdateLayerIDMap(id string, toContainer, toHost *idtools.IDMapp return err } return os.Chown(dir, rootIDs.UID, rootIDs.GID) - } // Changes produces a list of changes between the specified layer diff --git a/drivers/windows/windows.go b/drivers/windows/windows.go index 66aa460cf..8c2dc18ae 100644 --- a/drivers/windows/windows.go +++ b/drivers/windows/windows.go @@ -64,8 +64,7 @@ func init() { } } -type checker struct { -} +type checker struct{} func (c *checker) IsMounted(path string) bool { return false @@ -102,7 +101,7 @@ func InitFilter(home string, options graphdriver.Options) (graphdriver.Driver, e return nil, fmt.Errorf("%s is on an ReFS volume - ReFS volumes are not supported", home) } - if err := idtools.MkdirAllAs(home, 0700, 0, 0); err != nil { + if err := idtools.MkdirAllAs(home, 0o700, 0, 0); err != nil { return nil, fmt.Errorf("windowsfilter failed to create '%s': %w", home, err) } @@ -885,7 +884,7 @@ func (d *Driver) resolveID(id string) (string, error) { // setID stores the layerId in disk. func (d *Driver) setID(id, altID string) error { - return os.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0600) + return os.WriteFile(filepath.Join(d.dir(id), "layerId"), []byte(altID), 0o600) } // getLayerChain returns the layer chain information. @@ -915,7 +914,7 @@ func (d *Driver) setLayerChain(id string, chain []string) error { } jPath := filepath.Join(d.dir(id), "layerchain.json") - err = os.WriteFile(jPath, content, 0600) + err = os.WriteFile(jPath, content, 0o600) if err != nil { return fmt.Errorf("unable to write layerchain file - %s", err) } diff --git a/drivers/zfs/zfs.go b/drivers/zfs/zfs.go index 703b660d2..e02289784 100644 --- a/drivers/zfs/zfs.go +++ b/drivers/zfs/zfs.go @@ -30,7 +30,7 @@ type zfsOptions struct { mountOptions string } -const defaultPerms = os.FileMode(0555) +const defaultPerms = os.FileMode(0o555) func init() { graphdriver.MustRegister("zfs", Init) @@ -57,7 +57,7 @@ func Init(base string, opt graphdriver.Options) (graphdriver.Driver, error) { return nil, fmt.Errorf("the 'zfs' command is not available: %w", graphdriver.ErrPrerequisites) } - file, err := unix.Open("/dev/zfs", unix.O_RDWR, 0600) + file, err := unix.Open("/dev/zfs", unix.O_RDWR, 0o600) if err != nil { logger.Debugf("cannot open /dev/zfs: %v", err) return nil, fmt.Errorf("could not open /dev/zfs: %v: %w", err, graphdriver.ErrPrerequisites) @@ -110,7 +110,7 @@ func Init(base string, opt graphdriver.Options) (graphdriver.Driver, error) { if err != nil { return nil, fmt.Errorf("failed to get root uid/gid: %w", err) } - if err := idtools.MkdirAllAs(base, 0700, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(base, 0o700, rootUID, rootGID); err != nil { return nil, fmt.Errorf("failed to create '%s': %w", base, err) } @@ -453,7 +453,7 @@ func (d *Driver) Get(id string, options graphdriver.MountOpts) (_ string, retErr return "", err } // Create the target directories if they don't exist - if err := idtools.MkdirAllAs(mountpoint, 0755, rootUID, rootGID); err != nil { + if err := idtools.MkdirAllAs(mountpoint, 0o755, rootUID, rootGID); err != nil { return "", err } diff --git a/idset_test.go b/idset_test.go index 2d8aa7e8a..e6a789df8 100644 --- a/idset_test.go +++ b/idset_test.go @@ -566,7 +566,8 @@ func TestIDSetFindAvailable(t *testing.T) { nil, true, }, - {"OneIntervalFindZero", + { + "OneIntervalFindZero", newIDSet([]interval{{1, 5}}), 0, &idSet{set: intervalset.NewImmutableSet(nil)}, diff --git a/images.go b/images.go index c1de19d7d..d71eab08b 100644 --- a/images.go +++ b/images.go @@ -568,7 +568,7 @@ func (r *imageStore) Save() error { } r.lockfile.AssertLockedForWriting() rpath := r.imagespath() - if err := os.MkdirAll(filepath.Dir(rpath), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(rpath), 0o700); err != nil { return err } jdata, err := json.Marshal(&r.images) @@ -582,14 +582,14 @@ func (r *imageStore) Save() error { return err } r.lastWrite = lw - if err := ioutils.AtomicWriteFile(rpath, jdata, 0600); err != nil { + if err := ioutils.AtomicWriteFile(rpath, jdata, 0o600); err != nil { return err } return nil } func newImageStore(dir string) (rwImageStore, error) { - if err := os.MkdirAll(dir, 0700); err != nil { + if err := os.MkdirAll(dir, 0o700); err != nil { return nil, err } lockfile, err := lockfile.GetLockFile(filepath.Join(dir, "images.lock")) @@ -1017,11 +1017,11 @@ func (r *imageStore) setBigData(image *Image, key string, data []byte, newDigest if key == "" { return fmt.Errorf("can't set empty name for image big data item: %w", ErrInvalidBigDataName) } - err := os.MkdirAll(r.datadir(image.ID), 0700) + err := os.MkdirAll(r.datadir(image.ID), 0o700) if err != nil { return err } - err = ioutils.AtomicWriteFile(r.datapath(image.ID, key), data, 0600) + err = ioutils.AtomicWriteFile(r.datapath(image.ID, key), data, 0o600) if err == nil { save := false if image.BigDataSizes == nil { diff --git a/internal/opts/opts.go b/internal/opts/opts.go index 30d8f22bc..47b79e152 100644 --- a/internal/opts/opts.go +++ b/internal/opts/opts.go @@ -209,7 +209,7 @@ type ValidatorFctListType func(val string) ([]string, error) // ValidateIPAddress validates an Ip address. func ValidateIPAddress(val string) (string, error) { - var ip = net.ParseIP(strings.TrimSpace(val)) + ip := net.ParseIP(strings.TrimSpace(val)) if ip != nil { return ip.String(), nil } diff --git a/internal/opts/opts_test.go b/internal/opts/opts_test.go index 5ea0bc9e2..b6fe2c840 100644 --- a/internal/opts/opts_test.go +++ b/internal/opts/opts_test.go @@ -30,7 +30,6 @@ func TestValidateIPAddress(t *testing.T) { if ret, err := opts.ValidateIPAddress(`random invalid string`); err == nil || ret != "" { t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) } - } func TestMapOpts(t *testing.T) { @@ -95,7 +94,6 @@ func TestListOptsWithoutValidator(t *testing.T) { if len(mapListOpts) != 1 { t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) } - } func TestListOptsWithValidator(t *testing.T) { diff --git a/internal/opts/parse.go b/internal/opts/parse.go index b1f8cdb31..be2a766ea 100644 --- a/internal/opts/parse.go +++ b/internal/opts/parse.go @@ -131,7 +131,7 @@ func (args Args) Len() int { func (args Args) MatchKVList(key string, sources map[string]string) bool { fieldValues := args.fields[key] - //do not filter if there is no filter set or cannot determine filter + // do not filter if there is no filter set or cannot determine filter if len(fieldValues) == 0 { return true } @@ -177,7 +177,7 @@ func (args Args) Match(field, source string) bool { // ExactMatch returns true if the source matches exactly one of the values. func (args Args) ExactMatch(key, source string) bool { fieldValues, ok := args.fields[key] - //do not filter if there is no filter set or cannot determine filter + // do not filter if there is no filter set or cannot determine filter if !ok || len(fieldValues) == 0 { return true } @@ -190,7 +190,7 @@ func (args Args) ExactMatch(key, source string) bool { // matches exactly the value. func (args Args) UniqueExactMatch(key, source string) bool { fieldValues := args.fields[key] - //do not filter if there is no filter set or cannot determine filter + // do not filter if there is no filter set or cannot determine filter if len(fieldValues) == 0 { return true } diff --git a/layers.go b/layers.go index daafc971a..03c2db696 100644 --- a/layers.go +++ b/layers.go @@ -657,7 +657,6 @@ func (r *layerStore) Layers() ([]Layer, error) { // Requires startWriting. func (r *layerStore) GarbageCollect() error { layers, err := r.driver.ListLayers() - if err != nil { if errors.Is(err, drivers.ErrNotSupported) { return nil @@ -936,7 +935,7 @@ func (r *layerStore) saveLayers(saveLocations layerLocations) error { continue } rpath := r.jsonPath[locationIndex] - if err := os.MkdirAll(filepath.Dir(rpath), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(rpath), 0o700); err != nil { return err } subsetLayers := make([]*Layer, 0, len(r.layers)) @@ -954,7 +953,7 @@ func (r *layerStore) saveLayers(saveLocations layerLocations) error { if location == volatileLayerLocation { opts.NoSync = true } - if err := ioutils.AtomicWriteFileWithOpts(rpath, jldata, 0600, &opts); err != nil { + if err := ioutils.AtomicWriteFileWithOpts(rpath, jldata, 0o600, &opts); err != nil { return err } r.layerspathsModified[locationIndex] = opts.ModTime @@ -970,7 +969,7 @@ func (r *layerStore) saveMounts() error { } r.mountsLockfile.AssertLockedForWriting() mpath := r.mountspath() - if err := os.MkdirAll(filepath.Dir(mpath), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(mpath), 0o700); err != nil { return err } mounts := make([]layerMountPoint, 0, len(r.layers)) @@ -996,17 +995,17 @@ func (r *layerStore) saveMounts() error { } r.mountsLastWrite = lw - if err = ioutils.AtomicWriteFile(mpath, jmdata, 0600); err != nil { + if err = ioutils.AtomicWriteFile(mpath, jmdata, 0o600); err != nil { return err } return r.loadMounts() } func (s *store) newLayerStore(rundir string, layerdir string, driver drivers.Driver, transient bool) (rwLayerStore, error) { - if err := os.MkdirAll(rundir, 0700); err != nil { + if err := os.MkdirAll(rundir, 0o700); err != nil { return nil, err } - if err := os.MkdirAll(layerdir, 0700); err != nil { + if err := os.MkdirAll(layerdir, 0o700); err != nil { return nil, err } // Note: While the containers.lock file is in rundir for transient stores @@ -1222,10 +1221,10 @@ func (r *layerStore) create(id string, parentLayer *Layer, names []string, mount if !r.lockfile.IsReadWrite() { return nil, -1, fmt.Errorf("not allowed to create new layers at %q: %w", r.layerdir, ErrStoreIsReadOnly) } - if err := os.MkdirAll(r.rundir, 0700); err != nil { + if err := os.MkdirAll(r.rundir, 0o700); err != nil { return nil, -1, err } - if err := os.MkdirAll(r.layerdir, 0700); err != nil { + if err := os.MkdirAll(r.layerdir, 0o700); err != nil { return nil, -1, err } if id == "" { @@ -1699,7 +1698,7 @@ func (r *layerStore) setBigData(layer *Layer, key string, data io.Reader) error if key == "" { return fmt.Errorf("can't set empty name for layer big data item: %w", ErrInvalidBigDataName) } - err := os.MkdirAll(r.datadir(layer.ID), 0700) + err := os.MkdirAll(r.datadir(layer.ID), 0o700) if err != nil { return err } @@ -1707,7 +1706,7 @@ func (r *layerStore) setBigData(layer *Layer, key string, data io.Reader) error // NewAtomicFileWriter doesn't overwrite/truncate the existing inode. // BigData() relies on this behaviour when opening the file for read // so that it is either accessing the old data or the new one. - writer, err := ioutils.NewAtomicFileWriter(r.datapath(layer.ID, key), 0600) + writer, err := ioutils.NewAtomicFileWriter(r.datapath(layer.ID, key), 0o600) if err != nil { return fmt.Errorf("opening bigdata file: %w", err) } @@ -2291,10 +2290,10 @@ func (r *layerStore) applyDiffWithOptions(to string, layerOptions *LayerOptions, return -1, err } compressor.Close() - if err := os.MkdirAll(filepath.Dir(r.tspath(layer.ID)), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(r.tspath(layer.ID)), 0o700); err != nil { return -1, err } - if err := ioutils.AtomicWriteFile(r.tspath(layer.ID), tsdata.Bytes(), 0600); err != nil { + if err := ioutils.AtomicWriteFile(r.tspath(layer.ID), tsdata.Bytes(), 0o600); err != nil { return -1, err } if compressedDigester != nil { diff --git a/pkg/archive/archive.go b/pkg/archive/archive.go index a391a8986..408e4599c 100644 --- a/pkg/archive/archive.go +++ b/pkg/archive/archive.go @@ -132,13 +132,13 @@ const ( ) const ( - modeISDIR = 040000 // Directory - modeISFIFO = 010000 // FIFO - modeISREG = 0100000 // Regular file - modeISLNK = 0120000 // Symbolic link - modeISBLK = 060000 // Block special file - modeISCHR = 020000 // Character special file - modeISSOCK = 0140000 // Socket + modeISDIR = 0o40000 // Directory + modeISFIFO = 0o10000 // FIFO + modeISREG = 0o100000 // Regular file + modeISLNK = 0o120000 // Symbolic link + modeISBLK = 0o60000 // Block special file + modeISCHR = 0o20000 // Character special file + modeISSOCK = 0o140000 // Socket ) // IsArchivePath checks if the (possibly compressed) file at the given path @@ -328,7 +328,6 @@ func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModi } pipeWriter.Close() - }() return pipeReader } @@ -552,9 +551,9 @@ func (ta *tarAppender) addTarFile(path, name string) error { } } - //handle re-mapping container ID mappings back to host ID mappings before - //writing tar headers/files. We skip whiteout files because they were written - //by the kernel and already have proper ownership relative to the host + // handle re-mapping container ID mappings back to host ID mappings before + // writing tar headers/files. We skip whiteout files because they were written + // by the kernel and already have proper ownership relative to the host if !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IDMappings.Empty() { fileIDPair, err := getFileUIDGID(fi.Sys()) if err != nil { @@ -702,7 +701,7 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, L } if forceMask != nil && (hdr.Typeflag != tar.TypeSymlink || runtime.GOOS == "darwin") { - value := fmt.Sprintf("%d:%d:0%o", hdr.Uid, hdr.Gid, hdrInfo.Mode()&07777) + value := fmt.Sprintf("%d:%d:0%o", hdr.Uid, hdr.Gid, hdrInfo.Mode()&0o7777) if err := system.Lsetxattr(path, idtools.ContainersOverrideXattr, []byte(value), 0); err != nil { return err } @@ -800,7 +799,6 @@ func Tar(path string, compression Compression) (io.ReadCloser, error) { // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { - // Fix the source path to work with long path names. This is a no-op // on platforms other than Windows. srcPath = fixVolumePathPrefix(srcPath) @@ -1032,7 +1030,7 @@ loop: parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = idtools.MkdirAllAndChownNew(parentPath, 0777, rootIDs) + err = idtools.MkdirAllAndChownNew(parentPath, 0o777, rootIDs) if err != nil { return err } @@ -1239,7 +1237,7 @@ func (archiver *Archiver) CopyWithTar(src, dst string) error { } // Create dst, copy src's content into it logrus.Debugf("Creating dest directory: %s", dst) - if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { + if err := idtools.MkdirAllAndChownNew(dst, 0o755, rootIDs); err != nil { return err } logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) @@ -1266,7 +1264,7 @@ func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { dst = filepath.Join(dst, filepath.Base(src)) } // Create the holding directory if necessary - if err := os.MkdirAll(filepath.Dir(dst), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(dst), 0o700); err != nil { return err } diff --git a/pkg/archive/archive_linux.go b/pkg/archive/archive_linux.go index 775bd0766..02995d767 100644 --- a/pkg/archive/archive_linux.go +++ b/pkg/archive/archive_linux.go @@ -153,8 +153,7 @@ func (overlayWhiteoutConverter) ConvertReadWithHandler(hdr *tar.Header, path str return true, nil } -type directHandler struct { -} +type directHandler struct{} func (d directHandler) Setxattr(path, name string, value []byte) error { return unix.Setxattr(path, name, value, 0) @@ -185,7 +184,7 @@ func GetFileOwner(path string) (uint32, uint32, uint32, error) { } s, ok := f.Sys().(*syscall.Stat_t) if ok { - return s.Uid, s.Gid, s.Mode & 07777, nil + return s.Uid, s.Gid, s.Mode & 0o7777, nil } return 0, 0, uint32(f.Mode()), nil } diff --git a/pkg/archive/archive_linux_test.go b/pkg/archive/archive_linux_test.go index dbb43647d..9b56b3752 100644 --- a/pkg/archive/archive_linux_test.go +++ b/pkg/archive/archive_linux_test.go @@ -25,27 +25,27 @@ import ( // └── f1 # whiteout, 0000 func setupOverlayTestDir(t *testing.T, src string) { // Create opaque directory containing single file and permission 0700 - err := os.Mkdir(filepath.Join(src, "d1"), 0700) + err := os.Mkdir(filepath.Join(src, "d1"), 0o700) require.NoError(t, err) err = system.Lsetxattr(filepath.Join(src, "d1"), getOverlayOpaqueXattrName(), []byte("y"), 0) require.NoError(t, err) - err = os.WriteFile(filepath.Join(src, "d1", "f1"), []byte{}, 0600) + err = os.WriteFile(filepath.Join(src, "d1", "f1"), []byte{}, 0o600) require.NoError(t, err) // Create another opaque directory containing single file but with permission 0750 - err = os.Mkdir(filepath.Join(src, "d2"), 0750) + err = os.Mkdir(filepath.Join(src, "d2"), 0o750) require.NoError(t, err) err = system.Lsetxattr(filepath.Join(src, "d2"), getOverlayOpaqueXattrName(), []byte("y"), 0) require.NoError(t, err) - err = os.WriteFile(filepath.Join(src, "d2", "f1"), []byte{}, 0660) + err = os.WriteFile(filepath.Join(src, "d2", "f1"), []byte{}, 0o660) require.NoError(t, err) // Create regular directory with deleted file - err = os.Mkdir(filepath.Join(src, "d3"), 0700) + err = os.Mkdir(filepath.Join(src, "d3"), 0o700) require.NoError(t, err) err = system.Mknod(filepath.Join(src, "d3", "f1"), unix.S_IFCHR, 0) @@ -54,10 +54,10 @@ func setupOverlayTestDir(t *testing.T, src string) { func setupOverlayLowerDir(t *testing.T, lower string) { // Create a subdirectory to use as the "lower layer"'s copy of a deleted directory - err := os.Mkdir(filepath.Join(lower, "d1"), 0700) + err := os.Mkdir(filepath.Join(lower, "d1"), 0o700) require.NoError(t, err) - err = os.WriteFile(filepath.Join(lower, "d1", "f1"), []byte{}, 0600) + err = os.WriteFile(filepath.Join(lower, "d1", "f1"), []byte{}, 0o600) require.NoError(t, err) } @@ -68,7 +68,6 @@ func checkOpaqueness(t *testing.T, path string, opaque string) { if string(xattrOpaque) != opaque { t.Fatalf("Unexpected opaque value: %q, expected %q", string(xattrOpaque), opaque) } - } func checkOverlayWhiteout(t *testing.T, path string) { @@ -118,11 +117,11 @@ func TestOverlayTarUntar(t *testing.T) { err = Untar(archive, dst, options) require.NoError(t, err) - checkFileMode(t, filepath.Join(dst, "d1"), 0700|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d2"), 0750|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d3"), 0700|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d1", "f1"), 0600) - checkFileMode(t, filepath.Join(dst, "d2", "f1"), 0660) + checkFileMode(t, filepath.Join(dst, "d1"), 0o700|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d2"), 0o750|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d3"), 0o700|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d1", "f1"), 0o600) + checkFileMode(t, filepath.Join(dst, "d2", "f1"), 0o660) checkFileMode(t, filepath.Join(dst, "d3", "f1"), os.ModeCharDevice|os.ModeDevice) checkOpaqueness(t, filepath.Join(dst, "d1"), "y") @@ -158,12 +157,12 @@ func TestOverlayTarAUFSUntar(t *testing.T) { }) require.NoError(t, err) - checkFileMode(t, filepath.Join(dst, "d1"), 0700|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d1", WhiteoutOpaqueDir), 0700) - checkFileMode(t, filepath.Join(dst, "d2"), 0750|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d3"), 0700|os.ModeDir) - checkFileMode(t, filepath.Join(dst, "d1", "f1"), 0600) - checkFileMode(t, filepath.Join(dst, "d2", "f1"), 0660) + checkFileMode(t, filepath.Join(dst, "d1"), 0o700|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d1", WhiteoutOpaqueDir), 0o700) + checkFileMode(t, filepath.Join(dst, "d2"), 0o750|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d3"), 0o700|os.ModeDir) + checkFileMode(t, filepath.Join(dst, "d1", "f1"), 0o600) + checkFileMode(t, filepath.Join(dst, "d2", "f1"), 0o660) checkFileMode(t, filepath.Join(dst, "d3", WhiteoutPrefix+"f1"), 0) } diff --git a/pkg/archive/archive_test.go b/pkg/archive/archive_test.go index a3475eaa2..f1fa132f1 100644 --- a/pkg/archive/archive_test.go +++ b/pkg/archive/archive_test.go @@ -186,6 +186,7 @@ func TestExtensionUncompressed(t *testing.T) { t.Fatalf("The extension of an uncompressed archive should be 'tar'.") } } + func TestExtensionBzip2(t *testing.T) { compression := Bzip2 output := compression.Extension() @@ -193,6 +194,7 @@ func TestExtensionBzip2(t *testing.T) { t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") } } + func TestExtensionGzip(t *testing.T) { compression := Gzip output := compression.Extension() @@ -200,6 +202,7 @@ func TestExtensionGzip(t *testing.T) { t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") } } + func TestExtensionXz(t *testing.T) { compression := Xz output := compression.Extension() @@ -258,7 +261,7 @@ func TestUntarPath(t *testing.T) { createEmptyFile(t, filepath.Join(tmpFolder, "src")) destFolder := filepath.Join(tmpFolder, "dest") - err := os.MkdirAll(destFolder, 0740) + err := os.MkdirAll(destFolder, 0o740) if err != nil { t.Fatalf("Fail to create the destination file") } @@ -335,13 +338,13 @@ func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) { t.Fatal(err) } destFolder := filepath.Join(tmpFolder, "dest") - err = os.MkdirAll(destFolder, 0740) + err = os.MkdirAll(destFolder, 0o740) if err != nil { t.Fatalf("Fail to create the destination folder") } // Let's create a folder that will has the same path as the extracted file (from tar) destSrcFileAsFolder := filepath.Join(destFolder, srcFileU) - err = os.MkdirAll(destSrcFileAsFolder, 0740) + err = os.MkdirAll(destSrcFileAsFolder, 0o740) if err != nil { t.Fatal(err) } @@ -355,7 +358,7 @@ func TestCopyWithTarInvalidSrc(t *testing.T) { tempFolder := t.TempDir() destFolder := filepath.Join(tempFolder, "dest") invalidSrc := filepath.Join(tempFolder, "doesnotexists") - err := os.MkdirAll(destFolder, 0740) + err := os.MkdirAll(destFolder, 0o740) if err != nil { t.Fatal(err) } @@ -369,7 +372,7 @@ func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) { tempFolder := t.TempDir() srcFolder := filepath.Join(tempFolder, "src") inexistentDestFolder := filepath.Join(tempFolder, "doesnotexists") - err := os.MkdirAll(srcFolder, 0740) + err := os.MkdirAll(srcFolder, 0o740) if err != nil { t.Fatal(err) } @@ -389,15 +392,15 @@ func TestCopyWithTarSrcFile(t *testing.T) { dest := filepath.Join(folder, "dest") srcFolder := filepath.Join(folder, "src") src := filepath.Join(folder, filepath.Join("src", "src")) - err := os.MkdirAll(srcFolder, 0740) + err := os.MkdirAll(srcFolder, 0o740) if err != nil { t.Fatal(err) } - err = os.MkdirAll(dest, 0740) + err = os.MkdirAll(dest, 0o740) if err != nil { t.Fatal(err) } - err = os.WriteFile(src, []byte("content"), 0777) + err = os.WriteFile(src, []byte("content"), 0o777) if err != nil { t.Fatalf("archiver.CopyWithTar couldn't write content, %s.", err) } @@ -415,7 +418,7 @@ func TestCopyWithTarSrcFile(t *testing.T) { if err != nil { t.Fatalf("archiver.CopyWithTar shouldn't have thrown an error, %s.", err) } - err = os.WriteFile(dest, []byte("modified content"), 0751) + err = os.WriteFile(dest, []byte("modified content"), 0o751) if err != nil { t.Fatalf("archiver.CopyWithTar couldn't write modified content, %s.", err) } @@ -450,15 +453,15 @@ func TestCopyWithTarSrcFolder(t *testing.T) { folder := t.TempDir() dest := filepath.Join(folder, "dest") src := filepath.Join(folder, filepath.Join("src", "folder")) - err := os.MkdirAll(src, 0740) + err := os.MkdirAll(src, 0o740) if err != nil { t.Fatal(err) } - err = os.MkdirAll(dest, 0740) + err = os.MkdirAll(dest, 0o740) if err != nil { t.Fatal(err) } - err = os.WriteFile(filepath.Join(src, "file"), []byte("content"), 0777) + err = os.WriteFile(filepath.Join(src, "file"), []byte("content"), 0o777) require.NoError(t, err) err = defaultCopyWithTar(src, dest) if err != nil { @@ -474,7 +477,7 @@ func TestCopyWithTarSrcFolder(t *testing.T) { func TestCopyFileWithTarInvalidSrc(t *testing.T) { tempFolder := t.TempDir() destFolder := filepath.Join(tempFolder, "dest") - err := os.MkdirAll(destFolder, 0740) + err := os.MkdirAll(destFolder, 0o740) if err != nil { t.Fatal(err) } @@ -505,11 +508,11 @@ func TestCopyFileWithTarSrcFolder(t *testing.T) { folder := t.TempDir() dest := filepath.Join(folder, "dest") src := filepath.Join(folder, "srcfolder") - err := os.MkdirAll(src, 0740) + err := os.MkdirAll(src, 0o740) if err != nil { t.Fatal(err) } - err = os.MkdirAll(dest, 0740) + err = os.MkdirAll(dest, 0o740) if err != nil { t.Fatal(err) } @@ -524,15 +527,15 @@ func TestCopyFileWithTarSrcFile(t *testing.T) { dest := filepath.Join(folder, "dest") srcFolder := filepath.Join(folder, "src") src := filepath.Join(folder, filepath.Join("src", "src")) - err := os.MkdirAll(srcFolder, 0740) + err := os.MkdirAll(srcFolder, 0o740) if err != nil { t.Fatal(err) } - err = os.MkdirAll(dest, 0740) + err = os.MkdirAll(dest, 0o740) if err != nil { t.Fatal(err) } - err = os.WriteFile(src, []byte("content"), 0777) + err = os.WriteFile(src, []byte("content"), 0o777) require.NoError(t, err) err = defaultCopyWithTar(src, dest+"/") if err != nil { @@ -548,7 +551,7 @@ func TestCopySocket(t *testing.T) { folder := t.TempDir() dest := filepath.Join(folder, "dest") src := filepath.Join(folder, "src") - err := os.MkdirAll(src, 0740) + err := os.MkdirAll(src, 0o740) if err != nil { t.Fatal(err) } @@ -558,7 +561,7 @@ func TestCopySocket(t *testing.T) { t.Fatal(err) } - err = os.MkdirAll(dest, 0740) + err = os.MkdirAll(dest, 0o740) if err != nil { t.Fatal(err) } @@ -647,13 +650,13 @@ func TestTarUntar(t *testing.T) { t.Skip("Failing on Windows") } origin := t.TempDir() - if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil { + if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { + if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { + if err := os.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0o700); err != nil { t.Fatal(err) } @@ -665,7 +668,6 @@ func TestTarUntar(t *testing.T) { Compression: c, ExcludePatterns: []string{"3"}, }) - if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } @@ -679,7 +681,7 @@ func TestTarUntar(t *testing.T) { func TestTarWithOptionsChownOptsAlwaysOverridesIdPair(t *testing.T) { origin := t.TempDir() filePath := filepath.Join(origin, "1") - err := os.WriteFile(filePath, []byte("hello world"), 0700) + err := os.WriteFile(filePath, []byte("hello world"), 0o700) require.NoError(t, err) idMaps := []idtools.IDMap{ @@ -733,10 +735,10 @@ func TestTarWithOptions(t *testing.T) { if _, err := os.MkdirTemp(origin, "folder"); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700); err != nil { + if err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { + if err := os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0o700); err != nil { t.Fatal(err) } @@ -810,7 +812,7 @@ func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) - if err := os.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil { + if err := os.WriteFile(filepath.Join(targetPath, fileName), fileData, 0o700); err != nil { return 0, err } if makeLinks { @@ -872,7 +874,7 @@ func TestUntarSelinuxLabel(t *testing.T) { { Name: "foo", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, PAXRecords: xattrs, }, }, @@ -893,7 +895,7 @@ func TestUntarInvalidFilenames(t *testing.T) { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { @@ -901,7 +903,7 @@ func TestUntarInvalidFilenames(t *testing.T) { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -922,18 +924,18 @@ func TestUntarHardlinkToSymlink(t *testing.T) { Name: "symlink1", Typeflag: tar.TypeSymlink, Linkname: "regfile", - Mode: 0644, + Mode: 0o644, }, { Name: "symlink2", Typeflag: tar.TypeLink, Linkname: "symlink1", - Mode: 0644, + Mode: 0o644, }, { Name: "regfile", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -954,7 +956,7 @@ func TestUntarInvalidHardlink(t *testing.T) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (/../) @@ -963,7 +965,7 @@ func TestUntarInvalidHardlink(t *testing.T) { Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try writing victim/file @@ -971,12 +973,12 @@ func TestUntarInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (hardlink, symlink) @@ -984,13 +986,13 @@ func TestUntarInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // Try reading victim/hello (hardlink, hardlink) @@ -998,13 +1000,13 @@ func TestUntarInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // Try removing victim directory (hardlink) @@ -1012,12 +1014,12 @@ func TestUntarInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -1038,7 +1040,7 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (/../) @@ -1047,7 +1049,7 @@ func TestUntarInvalidSymlink(t *testing.T) { Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try writing victim/file @@ -1055,12 +1057,12 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (symlink, symlink) @@ -1068,13 +1070,13 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (symlink, hardlink) @@ -1082,13 +1084,13 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try removing victim directory (symlink) @@ -1096,12 +1098,12 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { // try writing to victim/newdir/newfile with a symlink in the path @@ -1110,12 +1112,12 @@ func TestUntarInvalidSymlink(t *testing.T) { Name: "dir/loophole", Typeflag: tar.TypeSymlink, Linkname: "../../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "dir/loophole/newdir/newfile", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -1209,7 +1211,7 @@ func buildSourceArchive(t *testing.T, numberOfFiles int) (io.ReadCloser, func()) func createOrReplaceModifier(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) { return &tar.Header{ - Mode: 0600, + Mode: 0o600, Typeflag: tar.TypeReg, }, []byte("the new content"), nil } @@ -1229,7 +1231,7 @@ func appendModifier(path string, header *tar.Header, content io.Reader) (*tar.He } } buffer.WriteString("\nnext line") - return &tar.Header{Mode: 0600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil + return &tar.Header{Mode: 0o600, Typeflag: tar.TypeReg}, buffer.Bytes(), nil } func readFileFromArchive(t *testing.T, archive io.ReadCloser, name string, expectedCount int, doc string) string { diff --git a/pkg/archive/archive_unix.go b/pkg/archive/archive_unix.go index f8a34c831..88192f220 100644 --- a/pkg/archive/archive_unix.go +++ b/pkg/archive/archive_unix.go @@ -88,7 +88,7 @@ func minor(device uint64) uint64 { // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - mode := uint32(hdr.Mode & 07777) + mode := uint32(hdr.Mode & 0o7777) switch hdr.Typeflag { case tar.TypeBlock: mode |= unix.S_IFBLK diff --git a/pkg/archive/archive_unix_test.go b/pkg/archive/archive_unix_test.go index b01430ceb..79c57fa5d 100644 --- a/pkg/archive/archive_unix_test.go +++ b/pkg/archive/archive_unix_test.go @@ -59,11 +59,11 @@ func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ - {0000, 0000}, - {0777, 0777}, - {0644, 0644}, - {0755, 0755}, - {0444, 0444}, + {0o000, 0o000}, + {0o777, 0o777}, + {0o644, 0o644}, + {0o755, 0o755}, + {0o444, 0o444}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { @@ -75,7 +75,7 @@ func TestChmodTarEntry(t *testing.T) { func TestTarWithHardLink(t *testing.T) { origin := t.TempDir() - err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700) + err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700) require.NoError(t, err) err = os.Link(filepath.Join(origin, "1"), filepath.Join(origin, "2")) @@ -117,10 +117,10 @@ func TestTarWithHardLinkAndRebase(t *testing.T) { tmpDir := t.TempDir() origin := filepath.Join(tmpDir, "origin") - err := os.Mkdir(origin, 0700) + err := os.Mkdir(origin, 0o700) require.NoError(t, err) - err = os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700) + err = os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700) require.NoError(t, err) err = os.Link(filepath.Join(origin, "1"), filepath.Join(origin, "2")) @@ -181,7 +181,7 @@ func getInode(path string) (uint64, error) { func TestTarWithBlockCharFifo(t *testing.T) { origin := t.TempDir() - err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700) + err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700) require.NoError(t, err) err = system.Mknod(filepath.Join(origin, "2"), unix.S_IFBLK, system.Mkdev(int64(12), int64(5))) @@ -222,12 +222,12 @@ func TestTarUntarWithXattr(t *testing.T) { t.Skip() } origin := t.TempDir() - err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0700) + err := os.WriteFile(filepath.Join(origin, "1"), []byte("hello world"), 0o700) require.NoError(t, err) - err = os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0700) + err = os.WriteFile(filepath.Join(origin, "2"), []byte("welcome!"), 0o700) require.NoError(t, err) - err = os.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0700) + err = os.WriteFile(filepath.Join(origin, "3"), []byte("will be ignored"), 0o700) require.NoError(t, err) encoded := [20]byte{0, 0, 0, 2} err = system.Lsetxattr(filepath.Join(origin, "2"), "security.capability", encoded[:], 0) @@ -241,7 +241,6 @@ func TestTarUntarWithXattr(t *testing.T) { Compression: c, ExcludePatterns: []string{"3"}, }) - if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } diff --git a/pkg/archive/archive_windows.go b/pkg/archive/archive_windows.go index e44011775..85a5b3a5d 100644 --- a/pkg/archive/archive_windows.go +++ b/pkg/archive/archive_windows.go @@ -38,18 +38,17 @@ func CanonicalTarNameForPath(p string) (string, error) { return "", fmt.Errorf("windows path contains forward slash: %s", p) } return strings.Replace(p, string(os.PathSeparator), "/", -1), nil - } // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { - //perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) + // perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) permPart := perm & os.ModePerm noPermPart := perm &^ os.ModePerm // Add the x bit: make everything +x from windows - permPart |= 0111 - permPart &= 0755 + permPart |= 0o111 + permPart &= 0o755 return noPermPart | permPart } diff --git a/pkg/archive/archive_windows_test.go b/pkg/archive/archive_windows_test.go index 80da76957..c4c10e872 100644 --- a/pkg/archive/archive_windows_test.go +++ b/pkg/archive/archive_windows_test.go @@ -18,11 +18,11 @@ func TestCopyFileWithInvalidDest(t *testing.T) { dest := "c:dest" srcFolder := filepath.Join(folder, "src") src := filepath.Join(folder, "src", "src") - err := os.MkdirAll(srcFolder, 0740) + err := os.MkdirAll(srcFolder, 0o740) if err != nil { t.Fatal(err) } - os.WriteFile(src, []byte("content"), 0777) + os.WriteFile(src, []byte("content"), 0o777) err = defaultCopyWithTar(src, dest) if err == nil { t.Fatalf("archiver.CopyWithTar should throw an error on invalid dest.") @@ -73,13 +73,13 @@ func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ - {0000, 0111}, - {0777, 0755}, - {0644, 0755}, - {0755, 0755}, - {0444, 0555}, - {0755 | os.ModeDir, 0755 | os.ModeDir}, - {0755 | os.ModeSymlink, 0755 | os.ModeSymlink}, + {0o000, 0o111}, + {0o777, 0o755}, + {0o644, 0o755}, + {0o755, 0o755}, + {0o444, 0o555}, + {0o755 | os.ModeDir, 0o755 | os.ModeDir}, + {0o755 | os.ModeSymlink, 0o755 | os.ModeSymlink}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { diff --git a/pkg/archive/changes.go b/pkg/archive/changes.go index fc705484e..01c6f30c2 100644 --- a/pkg/archive/changes.go +++ b/pkg/archive/changes.go @@ -131,9 +131,11 @@ func isENOTDIR(err error) bool { return false } -type skipChange func(string) (bool, error) -type deleteChange func(string, string, os.FileInfo) (string, error) -type whiteoutChange func(string, string) (bool, error) +type ( + skipChange func(string) (bool, error) + deleteChange func(string, string, os.FileInfo) (string, error) + whiteoutChange func(string, string) (bool, error) +) func changes(layers []string, rw string, dc deleteChange, sc skipChange, wc whiteoutChange) ([]Change, error) { var ( @@ -299,7 +301,6 @@ func (info *FileInfo) path() string { } func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { - sizeAtEntry := len(*changes) if oldInfo == nil { @@ -373,7 +374,6 @@ func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) (*changes)[sizeAtEntry] = change } - } // Changes add changes to file information. @@ -398,9 +398,7 @@ func newRootFileInfo(idMappings *idtools.IDMappings) *FileInfo { // ChangesDirs compares two directories and generates an array of Change objects describing the changes. // If oldDir is "", then all files in newDir will be Add-Changes. func ChangesDirs(newDir string, newMappings *idtools.IDMappings, oldDir string, oldMappings *idtools.IDMappings) ([]Change, error) { - var ( - oldRoot, newRoot *FileInfo - ) + var oldRoot, newRoot *FileInfo if oldDir == "" { emptyDir, err := os.MkdirTemp("", "empty") if err != nil { diff --git a/pkg/archive/changes_bsd_test.go b/pkg/archive/changes_bsd_test.go index 93ea18f78..2805239b3 100644 --- a/pkg/archive/changes_bsd_test.go +++ b/pkg/archive/changes_bsd_test.go @@ -62,7 +62,7 @@ func TestApplyToImmutable(t *testing.T) { createSampleDir(t, src) file1 := path.Join(src, "dir1/file1-1") file2 := path.Join(src, "dir1/file1-2") - require.NoError(t, os.Chmod(file1, 0777)) + require.NoError(t, os.Chmod(file1, 0o777)) require.NoError(t, system.Lchflags(file1, system.SF_IMMUTABLE)) require.NoError(t, system.Lchflags(file2, system.SF_IMMUTABLE)) @@ -73,7 +73,7 @@ func TestApplyToImmutable(t *testing.T) { file1 = path.Join(dst, "dir1/file1-1") file2 = path.Join(dst, "dir1/file1-2") require.NoError(t, system.Lchflags(file1, 0)) - require.NoError(t, os.Chmod(file1, 0666)) + require.NoError(t, os.Chmod(file1, 0o666)) require.NoError(t, system.Lchflags(file2, 0)) require.NoError(t, os.RemoveAll(file2)) diff --git a/pkg/archive/changes_linux.go b/pkg/archive/changes_linux.go index 77d3d6f51..f8414717b 100644 --- a/pkg/archive/changes_linux.go +++ b/pkg/archive/changes_linux.go @@ -397,5 +397,4 @@ func overlayDeletedFile(layers []string, root, path string, fi os.FileInfo) (str // We didn't find the same path in any older layers, so it was new in this one. return "", nil - } diff --git a/pkg/archive/changes_posix_test.go b/pkg/archive/changes_posix_test.go index 7bd364c5e..460150943 100644 --- a/pkg/archive/changes_posix_test.go +++ b/pkg/archive/changes_posix_test.go @@ -14,7 +14,7 @@ import ( ) func TestHardLinkOrder(t *testing.T) { - //TODO Should run for Solaris + // TODO Should run for Solaris if runtime.GOOS == "solaris" { t.Skip("gcp failures on Solaris") } @@ -99,7 +99,6 @@ func TestHardLinkOrder(t *testing.T) { t.Errorf("headers - %q expected linkname %q; but got %q", hdrs[i].Name, hdrs[i].Linkname, hdrsRev[i].Linkname) } } - } type tarHeaders []tar.Header diff --git a/pkg/archive/changes_test.go b/pkg/archive/changes_test.go index 096a6751d..615abbc6a 100644 --- a/pkg/archive/changes_test.go +++ b/pkg/archive/changes_test.go @@ -50,30 +50,30 @@ type FileData struct { func createSampleDir(t *testing.T, root string) { files := []FileData{ - {Regular, "file1", "file1\n", 0600}, - {Regular, "file2", "file2\n", 0666}, - {Regular, "file3", "file3\n", 0404}, - {Regular, "file4", "file4\n", 0600}, - {Regular, "file5", "file5\n", 0600}, - {Regular, "file6", "file6\n", 0600}, - {Regular, "file7", "file7\n", 0600}, - {Dir, "dir1", "", 0740}, - {Regular, "dir1/file1-1", "file1-1\n", 01444}, - {Regular, "dir1/file1-2", "file1-2\n", 0666}, - {Dir, "dir2", "", 0700}, - {Regular, "dir2/file2-1", "file2-1\n", 0666}, - {Regular, "dir2/file2-2", "file2-2\n", 0666}, - {Dir, "dir3", "", 0700}, - {Regular, "dir3/file3-1", "file3-1\n", 0666}, - {Regular, "dir3/file3-2", "file3-2\n", 0666}, - {Dir, "dir4", "", 0700}, - {Regular, "dir4/file3-1", "file4-1\n", 0666}, - {Regular, "dir4/file3-2", "file4-2\n", 0666}, - {Symlink, "symlink1", "target1", 0666}, - {Symlink, "symlink2", "target2", 0666}, - {Symlink, "symlink3", root + "/file1", 0666}, - {Symlink, "symlink4", root + "/symlink3", 0666}, - {Symlink, "dirSymlink", root + "/dir1", 0740}, + {Regular, "file1", "file1\n", 0o600}, + {Regular, "file2", "file2\n", 0o666}, + {Regular, "file3", "file3\n", 0o404}, + {Regular, "file4", "file4\n", 0o600}, + {Regular, "file5", "file5\n", 0o600}, + {Regular, "file6", "file6\n", 0o600}, + {Regular, "file7", "file7\n", 0o600}, + {Dir, "dir1", "", 0o740}, + {Regular, "dir1/file1-1", "file1-1\n", 0o1444}, + {Regular, "dir1/file1-2", "file1-2\n", 0o666}, + {Dir, "dir2", "", 0o700}, + {Regular, "dir2/file2-1", "file2-1\n", 0o666}, + {Regular, "dir2/file2-2", "file2-2\n", 0o666}, + {Dir, "dir3", "", 0o700}, + {Regular, "dir3/file3-1", "file3-1\n", 0o666}, + {Regular, "dir3/file3-2", "file3-2\n", 0o666}, + {Dir, "dir4", "", 0o700}, + {Regular, "dir4/file3-1", "file4-1\n", 0o666}, + {Regular, "dir4/file3-2", "file4-2\n", 0o666}, + {Symlink, "symlink1", "target1", 0o666}, + {Symlink, "symlink2", "target2", 0o666}, + {Symlink, "symlink3", root + "/file1", 0o666}, + {Symlink, "symlink4", root + "/symlink3", 0o666}, + {Symlink, "dirSymlink", root + "/dir1", 0o740}, } now := time.Now() @@ -141,7 +141,7 @@ func TestChangesWithChanges(t *testing.T) { // Mock the readonly layer layer := t.TempDir() createSampleDir(t, layer) - err := os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740) + err := os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0o740) require.NoError(t, err) // Mock the RW layer @@ -149,20 +149,20 @@ func TestChangesWithChanges(t *testing.T) { // Create a folder in RW layer dir1 := path.Join(rwLayer, "dir1") - err = os.MkdirAll(dir1, 0740) + err = os.MkdirAll(dir1, 0o740) require.NoError(t, err) deletedFile := path.Join(dir1, ".wh.file1-2") - err = os.WriteFile(deletedFile, []byte{}, 0600) + err = os.WriteFile(deletedFile, []byte{}, 0o600) require.NoError(t, err) modifiedFile := path.Join(dir1, "file1-1") - err = os.WriteFile(modifiedFile, []byte{0x00}, 01444) + err = os.WriteFile(modifiedFile, []byte{0x00}, 0o1444) require.NoError(t, err) // Let's add a subfolder for a newFile subfolder := path.Join(dir1, "subfolder") - err = os.MkdirAll(subfolder, 0740) + err = os.MkdirAll(subfolder, 0o740) require.NoError(t, err) newFile := path.Join(subfolder, "newFile") - err = os.WriteFile(newFile, []byte{}, 0740) + err = os.WriteFile(newFile, []byte{}, 0o740) require.NoError(t, err) changes, err := Changes([]string{layer}, rwLayer) @@ -188,11 +188,11 @@ func TestChangesWithChangesGH13590(t *testing.T) { baseLayer := t.TempDir() dir3 := path.Join(baseLayer, "dir1/dir2/dir3") - err := os.MkdirAll(dir3, 07400) + err := os.MkdirAll(dir3, 0o7400) require.NoError(t, err) file := path.Join(dir3, "file.txt") - err = os.WriteFile(file, []byte("hello"), 0666) + err = os.WriteFile(file, []byte("hello"), 0o666) require.NoError(t, err) layer := t.TempDir() @@ -204,7 +204,7 @@ func TestChangesWithChangesGH13590(t *testing.T) { os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt")) file = path.Join(layer, "dir1/dir2/dir3/file1.txt") - err = os.WriteFile(file, []byte("bye"), 0666) + err = os.WriteFile(file, []byte("bye"), 0o666) require.NoError(t, err) changes, err := Changes([]string{baseLayer}, layer) @@ -226,7 +226,7 @@ func TestChangesWithChangesGH13590(t *testing.T) { } file = path.Join(layer, "dir1/dir2/dir3/file.txt") - err = os.WriteFile(file, []byte("bye"), 0666) + err = os.WriteFile(file, []byte("bye"), 0o666) require.NoError(t, err) changes, err = Changes([]string{baseLayer}, layer) @@ -273,13 +273,13 @@ func mutateSampleDir(t *testing.T, root string) { require.NoError(t, err) // Rewrite a file - err = os.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777) + err = os.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0o777) require.NoError(t, err) // Replace a file err = os.RemoveAll(path.Join(root, "file3")) require.NoError(t, err) - err = os.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404) + err = os.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0o404) require.NoError(t, err) // Touch file @@ -289,15 +289,15 @@ func mutateSampleDir(t *testing.T, root string) { // Replace file with dir err = os.RemoveAll(path.Join(root, "file5")) require.NoError(t, err) - err = os.MkdirAll(path.Join(root, "file5"), 0666) + err = os.MkdirAll(path.Join(root, "file5"), 0o666) require.NoError(t, err) // Create new file - err = os.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777) + err = os.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0o777) require.NoError(t, err) // Create new dir - err = os.MkdirAll(path.Join(root, "dirnew"), 0766) + err = os.MkdirAll(path.Join(root, "dirnew"), 0o766) require.NoError(t, err) // Create a new symlink @@ -314,7 +314,7 @@ func mutateSampleDir(t *testing.T, root string) { // Replace dir with file err = os.RemoveAll(path.Join(root, "dir2")) require.NoError(t, err) - err = os.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777) + err = os.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0o777) require.NoError(t, err) // Touch dir @@ -451,10 +451,10 @@ func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) { func TestChangesSize(t *testing.T) { parentPath := t.TempDir() addition := path.Join(parentPath, "addition") - err := os.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744) + err := os.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0o744) require.NoError(t, err) modification := path.Join(parentPath, "modification") - err = os.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744) + err = os.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0o744) require.NoError(t, err) changes := []Change{ diff --git a/pkg/archive/changes_windows.go b/pkg/archive/changes_windows.go index 966400e59..1bab94fa5 100644 --- a/pkg/archive/changes_windows.go +++ b/pkg/archive/changes_windows.go @@ -7,7 +7,6 @@ import ( ) func statDifferent(oldStat *system.StatT, oldInfo *FileInfo, newStat *system.StatT, newInfo *FileInfo) bool { - // Don't look at size for dirs, its not a good measure of change if oldStat.Mtim() != newStat.Mtim() || oldStat.Mode() != newStat.Mode() || diff --git a/pkg/archive/copy.go b/pkg/archive/copy.go index 2c714e8da..55f753bf4 100644 --- a/pkg/archive/copy.go +++ b/pkg/archive/copy.go @@ -297,7 +297,6 @@ func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir } return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil } - } // RebaseArchiveEntries rewrites the given srcContent archive replacing diff --git a/pkg/archive/copy_unix_test.go b/pkg/archive/copy_unix_test.go index 62affd182..5ad09746a 100644 --- a/pkg/archive/copy_unix_test.go +++ b/pkg/archive/copy_unix_test.go @@ -328,7 +328,6 @@ func TestCopyCaseB(t *testing.T) { if err != ErrDirNotExists { t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) } - } // C. SRC specifies a file and DST exists as a file. This should overwrite @@ -431,7 +430,7 @@ func TestCopyCaseD(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -482,7 +481,7 @@ func TestCopyCaseDFSym(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -648,7 +647,7 @@ func TestCopyCaseG(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -694,7 +693,7 @@ func TestCopyCaseGFSym(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -857,7 +856,7 @@ func TestCopyCaseJ(t *testing.T) { var err error // first to create an empty dir - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -874,7 +873,7 @@ func TestCopyCaseJ(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -908,7 +907,7 @@ func TestCopyCaseJFSym(t *testing.T) { var err error // first to create an empty dir - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } @@ -925,7 +924,7 @@ func TestCopyCaseJFSym(t *testing.T) { t.Fatalf("unable to remove dstDir: %s", err) } - if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { + if err = os.MkdirAll(dstDir, os.FileMode(0o755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } diff --git a/pkg/archive/diff.go b/pkg/archive/diff.go index 8fec5af38..713551859 100644 --- a/pkg/archive/diff.go +++ b/pkg/archive/diff.go @@ -85,7 +85,7 @@ func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = os.MkdirAll(parentPath, 0755) + err = os.MkdirAll(parentPath, 0o755) if err != nil { return 0, err } diff --git a/pkg/archive/diff_test.go b/pkg/archive/diff_test.go index b2a3a2e8f..19f14414a 100644 --- a/pkg/archive/diff_test.go +++ b/pkg/archive/diff_test.go @@ -23,7 +23,7 @@ func TestApplyLayerInvalidFilenames(t *testing.T) { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { @@ -31,7 +31,7 @@ func TestApplyLayerInvalidFilenames(t *testing.T) { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -51,7 +51,7 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (/../) @@ -60,7 +60,7 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try writing victim/file @@ -68,12 +68,12 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (hardlink, symlink) @@ -81,13 +81,13 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // Try reading victim/hello (hardlink, hardlink) @@ -95,13 +95,13 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // Try removing victim directory (hardlink) @@ -109,12 +109,12 @@ func TestApplyLayerInvalidHardlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -134,7 +134,7 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (/../) @@ -143,7 +143,7 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try writing victim/file @@ -151,12 +151,12 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (symlink, symlink) @@ -164,13 +164,13 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try reading victim/hello (symlink, hardlink) @@ -178,13 +178,13 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", - Mode: 0644, + Mode: 0o644, }, }, { // try removing victim directory (symlink) @@ -192,12 +192,12 @@ func TestApplyLayerInvalidSymlink(t *testing.T) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", - Mode: 0755, + Mode: 0o755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, - Mode: 0644, + Mode: 0o644, }, }, } { @@ -321,18 +321,17 @@ func TestApplyLayerWhiteouts(t *testing.T) { t.Fatalf("invalid files for layer %d: expected %q, got %q", i, tc.expected, paths) } } - } func makeTestLayer(t *testing.T, paths []string) (rc io.ReadCloser, err error) { tmpDir := t.TempDir() for _, p := range paths { if p[len(p)-1] == filepath.Separator { - if err = os.MkdirAll(filepath.Join(tmpDir, p), 0700); err != nil { + if err = os.MkdirAll(filepath.Join(tmpDir, p), 0o700); err != nil { return } } else { - if err = os.WriteFile(filepath.Join(tmpDir, p), nil, 0600); err != nil { + if err = os.WriteFile(filepath.Join(tmpDir, p), nil, 0o600); err != nil { return } } diff --git a/pkg/archive/example_changes.go b/pkg/archive/example_changes.go index 3e1271878..f617e0e06 100644 --- a/pkg/archive/example_changes.go +++ b/pkg/archive/example_changes.go @@ -83,7 +83,7 @@ func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) - if err := os.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { + if err := os.WriteFile(path.Join(targetPath, fileName), fileData, 0o700); err != nil { return 0, err } if makeLinks { diff --git a/pkg/archive/fflags_bsd.go b/pkg/archive/fflags_bsd.go index 14661c411..92b8d05ed 100644 --- a/pkg/archive/fflags_bsd.go +++ b/pkg/archive/fflags_bsd.go @@ -98,7 +98,7 @@ func parseFileFlags(fflags string) (uint32, uint32, error) { } func formatFileFlags(fflags uint32) (string, error) { - var res = []string{} + res := []string{} for fflags != 0 { // Extract lowest set bit fflag := uint32(1) << bits.TrailingZeros32(fflags) diff --git a/pkg/archive/utils_test.go b/pkg/archive/utils_test.go index 39f7403b3..8e6b8dfe3 100644 --- a/pkg/archive/utils_test.go +++ b/pkg/archive/utils_test.go @@ -40,12 +40,12 @@ func testBreakout(t *testing.T, untarFn string, headers []*tar.Header) error { tmpdir := t.TempDir() dest := filepath.Join(tmpdir, "dest") - if err := os.Mkdir(dest, 0755); err != nil { + if err := os.Mkdir(dest, 0o755); err != nil { return err } victim := filepath.Join(tmpdir, "victim") - if err := os.Mkdir(victim, 0755); err != nil { + if err := os.Mkdir(victim, 0o755); err != nil { return err } hello := filepath.Join(victim, "hello") @@ -53,7 +53,7 @@ func testBreakout(t *testing.T, untarFn string, headers []*tar.Header) error { if err != nil { return err } - if err := os.WriteFile(hello, helloData, 0644); err != nil { + if err := os.WriteFile(hello, helloData, 0o644); err != nil { return err } helloStat, err := os.Stat(hello) diff --git a/pkg/chrootarchive/archive.go b/pkg/chrootarchive/archive.go index 2de95f39a..f221a2283 100644 --- a/pkg/chrootarchive/archive.go +++ b/pkg/chrootarchive/archive.go @@ -77,7 +77,7 @@ func untarHandler(tarArchive io.Reader, dest string, options *archive.TarOptions dest = filepath.Clean(dest) if _, err := os.Stat(dest); os.IsNotExist(err) { - if err := idtools.MkdirAllAndChownNew(dest, 0755, rootIDs); err != nil { + if err := idtools.MkdirAllAndChownNew(dest, 0o755, rootIDs); err != nil { return err } } diff --git a/pkg/chrootarchive/archive_darwin.go b/pkg/chrootarchive/archive_darwin.go index 42ee39f48..f7a16e9f9 100644 --- a/pkg/chrootarchive/archive_darwin.go +++ b/pkg/chrootarchive/archive_darwin.go @@ -8,7 +8,8 @@ import ( func invokeUnpack(decompressedArchive io.Reader, dest string, - options *archive.TarOptions, root string) error { + options *archive.TarOptions, root string, +) error { return archive.Unpack(decompressedArchive, dest, options) } diff --git a/pkg/chrootarchive/archive_test.go b/pkg/chrootarchive/archive_test.go index 10444d26e..ba68d843d 100644 --- a/pkg/chrootarchive/archive_test.go +++ b/pkg/chrootarchive/archive_test.go @@ -49,13 +49,13 @@ func CopyWithTar(src, dst string) error { func TestChrootTarUntar(t *testing.T) { tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { + if err := os.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0o644); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(src, "lolo"), []byte("hello lolo"), 0644); err != nil { + if err := os.WriteFile(filepath.Join(src, "lolo"), []byte("hello lolo"), 0o644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) @@ -63,7 +63,7 @@ func TestChrootTarUntar(t *testing.T) { t.Fatal(err) } dest := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(dest, 0700); err != nil { + if err := os.MkdirAll(dest, 0o700); err != nil { t.Fatal(err) } if err := Untar(stream, dest, &archive.TarOptions{ExcludePatterns: []string{"lolo"}}); err != nil { @@ -76,10 +76,10 @@ func TestChrootTarUntar(t *testing.T) { func TestChrootUntarWithHugeExcludesList(t *testing.T) { tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { + if err := os.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0o644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) @@ -87,12 +87,12 @@ func TestChrootUntarWithHugeExcludesList(t *testing.T) { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") - if err := os.MkdirAll(dest, 0700); err != nil { + if err := os.MkdirAll(dest, 0o700); err != nil { t.Fatal(err) } options := &archive.TarOptions{} - //65534 entries of 64-byte strings ~= 4MB of environment space which should overflow - //on most systems when passed via environment or command line arguments + // 65534 entries of 64-byte strings ~= 4MB of environment space which should overflow + // on most systems when passed via environment or command line arguments excludes := make([]string, 65534) for i := 0; i < 65534; i++ { excludes[i] = strings.Repeat(fmt.Sprintf("%d", i), 64) @@ -114,7 +114,7 @@ func prepareSourceDirectory(numberOfFiles int, targetPath string, makeSymLinks b fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) - if err := os.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil { + if err := os.WriteFile(filepath.Join(targetPath, fileName), fileData, 0o700); err != nil { return 0, err } if makeSymLinks { @@ -190,7 +190,6 @@ func compareFilesChown(src string, dest string, uid, gid int) error { } } return err - } func TestChrootTarUntarWithSymlink(t *testing.T) { @@ -200,7 +199,7 @@ func TestChrootTarUntarWithSymlink(t *testing.T) { } tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, false); err != nil { @@ -222,7 +221,7 @@ func TestChrootCopyWithTar(t *testing.T) { } tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { @@ -268,7 +267,7 @@ func TestChrootCopyWithTarAndChown(t *testing.T) { } tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { @@ -316,7 +315,7 @@ func TestChrootCopyWithTarAndChown(t *testing.T) { func TestChrootCopyFileWithTar(t *testing.T) { tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { @@ -355,7 +354,7 @@ func TestChrootCopyFileWithTar(t *testing.T) { func TestChrootCopyFileWithTarAndChown(t *testing.T) { tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { @@ -405,7 +404,7 @@ func TestChrootUntarPath(t *testing.T) { } tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, false); err != nil { @@ -427,7 +426,7 @@ func TestChrootUntarPath(t *testing.T) { _, err = buf.ReadFrom(stream) require.NoError(t, err) tarfile := filepath.Join(tmpdir, "src.tar") - if err := os.WriteFile(tarfile, buf.Bytes(), 0644); err != nil { + if err := os.WriteFile(tarfile, buf.Bytes(), 0o644); err != nil { t.Fatal(err) } if err := UntarPath(tarfile, dest); err != nil { @@ -445,7 +444,7 @@ func TestChrootUntarPathAndChown(t *testing.T) { } tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, false); err != nil { @@ -477,7 +476,7 @@ func TestChrootUntarPathAndChown(t *testing.T) { _, err = buf.ReadFrom(stream) require.NoError(t, err) tarfile := filepath.Join(tmpdir, "src.tar") - if err := os.WriteFile(tarfile, buf.Bytes(), 0644); err != nil { + if err := os.WriteFile(tarfile, buf.Bytes(), 0o644); err != nil { t.Fatal(err) } if err := untarFunc(tarfile, dest); err != nil { @@ -514,7 +513,7 @@ func (s *slowEmptyTarReader) Read(p []byte) (int, error) { func TestChrootUntarEmptyArchiveFromSlowReader(t *testing.T) { tmpdir := t.TempDir() dest := filepath.Join(tmpdir, "dest") - if err := os.MkdirAll(dest, 0700); err != nil { + if err := os.MkdirAll(dest, 0o700); err != nil { t.Fatal(err) } stream := &slowEmptyTarReader{size: 10240, chunkSize: 1024} @@ -526,7 +525,7 @@ func TestChrootUntarEmptyArchiveFromSlowReader(t *testing.T) { func TestChrootApplyEmptyArchiveFromSlowReader(t *testing.T) { tmpdir := t.TempDir() dest := filepath.Join(tmpdir, "dest") - if err := os.MkdirAll(dest, 0700); err != nil { + if err := os.MkdirAll(dest, 0o700); err != nil { t.Fatal(err) } stream := &slowEmptyTarReader{size: 10240, chunkSize: 1024} @@ -538,10 +537,10 @@ func TestChrootApplyEmptyArchiveFromSlowReader(t *testing.T) { func TestChrootApplyDotDotFile(t *testing.T) { tmpdir := t.TempDir() src := filepath.Join(tmpdir, "src") - if err := os.MkdirAll(src, 0700); err != nil { + if err := os.MkdirAll(src, 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(src, "..gitme"), []byte(""), 0644); err != nil { + if err := os.WriteFile(filepath.Join(src, "..gitme"), []byte(""), 0o644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) @@ -549,7 +548,7 @@ func TestChrootApplyDotDotFile(t *testing.T) { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") - if err := os.MkdirAll(dest, 0700); err != nil { + if err := os.MkdirAll(dest, 0o700); err != nil { t.Fatal(err) } if _, err := ApplyLayer(dest, stream); err != nil { diff --git a/pkg/chrootarchive/archive_unix.go b/pkg/chrootarchive/archive_unix.go index 8cc0f33b3..259f8c99a 100644 --- a/pkg/chrootarchive/archive_unix.go +++ b/pkg/chrootarchive/archive_unix.go @@ -27,7 +27,7 @@ func untar() { var options archive.TarOptions - //read the options from the pipe "ExtraFiles" + // read the options from the pipe "ExtraFiles" if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil { fatal(err) } @@ -99,7 +99,7 @@ func invokeUnpack(decompressedArchive io.Reader, dest string, options *archive.T return fmt.Errorf("untar error on re-exec cmd: %w", err) } - //write the options to the pipe for the untar exec to read + // write the options to the pipe for the untar exec to read if err := json.NewEncoder(w).Encode(options); err != nil { w.Close() return fmt.Errorf("untar json encode to pipe failed: %w", err) diff --git a/pkg/chrootarchive/archive_unix_test.go b/pkg/chrootarchive/archive_unix_test.go index ccd016d76..de28eea07 100644 --- a/pkg/chrootarchive/archive_unix_test.go +++ b/pkg/chrootarchive/archive_unix_test.go @@ -26,12 +26,12 @@ func TestUntarWithMaliciousSymlinks(t *testing.T) { dir := t.TempDir() root := filepath.Join(dir, "root") - err := os.MkdirAll(root, 0755) + err := os.MkdirAll(root, 0o755) assert.NilError(t, err) // Add a file into a directory above root // Ensure that we can't access this file while tarring. - err = os.WriteFile(filepath.Join(dir, "host-file"), []byte("I am a host file"), 0644) + err = os.WriteFile(filepath.Join(dir, "host-file"), []byte("I am a host file"), 0o644) assert.NilError(t, err) // Create some data which will be copied into the "container" root into @@ -39,9 +39,9 @@ func TestUntarWithMaliciousSymlinks(t *testing.T) { // Before this change, the copy would overwrite the "host" content. // With this change it should not. data := filepath.Join(dir, "data") - err = os.MkdirAll(data, 0755) + err = os.MkdirAll(data, 0o755) assert.NilError(t, err) - err = os.WriteFile(filepath.Join(data, "local-file"), []byte("pwn3d"), 0644) + err = os.WriteFile(filepath.Join(data, "local-file"), []byte("pwn3d"), 0o644) assert.NilError(t, err) safe := filepath.Join(root, "safe") @@ -86,14 +86,14 @@ func TestTarWithMaliciousSymlinks(t *testing.T) { root := filepath.Join(dir, "root") - err := os.MkdirAll(root, 0755) + err := os.MkdirAll(root, 0o755) assert.NilError(t, err) hostFileData := []byte("I am a host file") // Add a file into a directory above root // Ensure that we can't access this file while tarring. - err = os.WriteFile(filepath.Join(dir, "host-file"), hostFileData, 0644) + err = os.WriteFile(filepath.Join(dir, "host-file"), hostFileData, 0o644) assert.NilError(t, err) safe := filepath.Join(root, "safe") @@ -101,7 +101,7 @@ func TestTarWithMaliciousSymlinks(t *testing.T) { assert.NilError(t, err) data := filepath.Join(dir, "data") - err = os.MkdirAll(data, 0755) + err = os.MkdirAll(data, 0o755) assert.NilError(t, err) type testCase struct { diff --git a/pkg/chrootarchive/archive_windows.go b/pkg/chrootarchive/archive_windows.go index 1395ff8cd..745502204 100644 --- a/pkg/chrootarchive/archive_windows.go +++ b/pkg/chrootarchive/archive_windows.go @@ -14,7 +14,8 @@ func chroot(path string) error { func invokeUnpack(decompressedArchive io.Reader, dest string, - options *archive.TarOptions, root string) error { + options *archive.TarOptions, root string, +) error { // Windows is different to Linux here because Windows does not support // chroot. Hence there is no point sandboxing a chrooted process to // do the unpack. We call inline instead within the daemon process. diff --git a/pkg/chrootarchive/diff_unix.go b/pkg/chrootarchive/diff_unix.go index 90f453913..71ed094d1 100644 --- a/pkg/chrootarchive/diff_unix.go +++ b/pkg/chrootarchive/diff_unix.go @@ -26,7 +26,6 @@ type applyLayerResponse struct { // used on Windows as it does not support chroot, hence no point sandboxing // through chroot and rexec. func applyLayer() { - var ( tmpDir string err error diff --git a/pkg/chunked/cache_linux.go b/pkg/chunked/cache_linux.go index 7efd12373..14064717a 100644 --- a/pkg/chunked/cache_linux.go +++ b/pkg/chunked/cache_linux.go @@ -48,8 +48,10 @@ type layersCache struct { created time.Time } -var cacheMutex sync.Mutex -var cache *layersCache +var ( + cacheMutex sync.Mutex + cache *layersCache +) func (c *layersCache) release() { cacheMutex.Lock() diff --git a/pkg/chunked/compressor/compressor.go b/pkg/chunked/compressor/compressor.go index 2a9bdc675..0d1acafec 100644 --- a/pkg/chunked/compressor/compressor.go +++ b/pkg/chunked/compressor/compressor.go @@ -15,8 +15,10 @@ import ( "github.com/vbatts/tar-split/archive/tar" ) -const RollsumBits = 16 -const holesThreshold = int64(1 << 10) +const ( + RollsumBits = 16 + holesThreshold = int64(1 << 10) +) type holesFinder struct { reader *bufio.Reader diff --git a/pkg/chunked/compressor/rollsum.go b/pkg/chunked/compressor/rollsum.go index f4dfad822..59df6901e 100644 --- a/pkg/chunked/compressor/rollsum.go +++ b/pkg/chunked/compressor/rollsum.go @@ -25,11 +25,15 @@ import ( "math/bits" ) -const windowSize = 64 // Roll assumes windowSize is a power of 2 -const charOffset = 31 +const ( + windowSize = 64 // Roll assumes windowSize is a power of 2 + charOffset = 31 +) -const blobBits = 13 -const blobSize = 1 << blobBits // 8k +const ( + blobBits = 13 + blobSize = 1 << blobBits // 8k +) type RollSum struct { s1, s2 uint32 diff --git a/pkg/chunked/internal/compression.go b/pkg/chunked/internal/compression.go index 092b03533..5eb9edb38 100644 --- a/pkg/chunked/internal/compression.go +++ b/pkg/chunked/internal/compression.go @@ -134,7 +134,7 @@ func WriteZstdChunkedManifest(dest io.Writer, outMetadata map[string]string, off Entries: metadata, } - var json = jsoniter.ConfigCompatibleWithStandardLibrary + json := jsoniter.ConfigCompatibleWithStandardLibrary // Generate the manifest manifest, err := json.Marshal(toc) if err != nil { diff --git a/pkg/chunked/storage_linux.go b/pkg/chunked/storage_linux.go index adc1ad398..711962298 100644 --- a/pkg/chunked/storage_linux.go +++ b/pkg/chunked/storage_linux.go @@ -558,7 +558,7 @@ func openFileUnderRootFallback(dirfd int, name string, flags uint64, mode os.Fil func openFileUnderRootOpenat2(dirfd int, name string, flags uint64, mode os.FileMode) (int, error) { how := unix.OpenHow{ Flags: flags, - Mode: uint64(mode & 07777), + Mode: uint64(mode & 0o7777), Resolve: unix.RESOLVE_IN_ROOT, } return unix.Openat2(dirfd, name, &how) @@ -636,7 +636,7 @@ func openOrCreateDirUnderRoot(name string, dirfd int, mode os.FileMode) (*os.Fil baseName := filepath.Base(name) - if err2 := unix.Mkdirat(int(pDir.Fd()), baseName, 0755); err2 != nil { + if err2 := unix.Mkdirat(int(pDir.Fd()), baseName, 0o755); err2 != nil { return nil, err } @@ -1384,7 +1384,7 @@ func (c *chunkedDiffer) ApplyDiff(dest string, options *archive.TarOptions) (gra filesToWaitFor := 0 for i, r := range mergedEntries { if options.ForceMask != nil { - value := fmt.Sprintf("%d:%d:0%o", r.UID, r.GID, r.Mode&07777) + value := fmt.Sprintf("%d:%d:0%o", r.UID, r.GID, r.Mode&0o7777) r.Xattrs[containersOverrideXattr] = base64.StdEncoding.EncodeToString([]byte(value)) r.Mode = int64(*options.ForceMask) } diff --git a/pkg/chunked/zstdchunked_test.go b/pkg/chunked/zstdchunked_test.go index e6b6735f9..00315c326 100644 --- a/pkg/chunked/zstdchunked_test.go +++ b/pkg/chunked/zstdchunked_test.go @@ -61,13 +61,13 @@ var someFiles = []internal.FileMetadata{ { Type: "dir", Name: "/foo", - Mode: 0755, + Mode: 0o755, Size: 0, }, { Type: "reg", Name: "/foo/bar", - Mode: 0755, + Mode: 0o755, Size: 10, Digest: "sha256:5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03", Offset: 100, @@ -79,7 +79,7 @@ var someFiles = []internal.FileMetadata{ { Type: "reg", Name: "/foo/baz", - Mode: 0755, + Mode: 0o755, Size: 12, Digest: "sha256:6f0378f21a495f5c13247317d158e9d51da45a5bf68fc2f366e450deafdc8302", Offset: 200, diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 5b6b432a5..1c75774be 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -123,7 +123,6 @@ func TestDeviceMapperOptions(t *testing.T) { if !searchOptions(doptions, s100) { t.Fatalf("Expected to find size %q, got %v", s100, doptions) } - } func TestBtrfsOptions(t *testing.T) { @@ -164,7 +163,6 @@ func TestBtrfsOptions(t *testing.T) { if !searchOptions(doptions, s100) { t.Fatalf("Expected to find size %q, got %v", s100, doptions) } - } func TestOverlayOptions(t *testing.T) { @@ -281,7 +279,6 @@ func TestOverlayOptions(t *testing.T) { if !searchOptions(doptions, s100) { t.Fatalf("Expected to find size %q, got %v", s100, doptions) } - } func TestVfsOptions(t *testing.T) { diff --git a/pkg/devicemapper/devmapper.go b/pkg/devicemapper/devmapper.go index b26e47d80..33bf7184e 100644 --- a/pkg/devicemapper/devmapper.go +++ b/pkg/devicemapper/devmapper.go @@ -239,8 +239,8 @@ func (t *Task) getDriverVersion() (string, error) { } func (t *Task) getNextTarget(next unsafe.Pointer) (nextPtr unsafe.Pointer, start uint64, - length uint64, targetType string, params string) { - + length uint64, targetType string, params string, +) { return DmGetNextTarget(t.unmanaged, next, &start, &length, &targetType, ¶ms), start, length, targetType, params diff --git a/pkg/devicemapper/devmapper_wrapper.go b/pkg/devicemapper/devmapper_wrapper.go index 28810063a..9aef4c2fb 100644 --- a/pkg/devicemapper/devmapper_wrapper.go +++ b/pkg/devicemapper/devmapper_wrapper.go @@ -138,8 +138,8 @@ func dmTaskSetRoFct(task *cdmTask) int { } func dmTaskAddTargetFct(task *cdmTask, - start, size uint64, ttype, params string) int { - + start, size uint64, ttype, params string, +) int { Cttype := C.CString(ttype) defer free(Cttype) diff --git a/pkg/fileutils/fileutils.go b/pkg/fileutils/fileutils.go index bcc2109b6..9d0714b1b 100644 --- a/pkg/fileutils/fileutils.go +++ b/pkg/fileutils/fileutils.go @@ -183,7 +183,6 @@ func (p *Pattern) Exclusion() bool { } func (p *Pattern) match(path string) (bool, error) { - if p.regexp == nil { if err := p.compile(); err != nil { return false, filepath.ErrBadPattern @@ -356,12 +355,12 @@ func CreateIfNotExists(path string, isDir bool) error { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { if isDir { - return os.MkdirAll(path, 0755) + return os.MkdirAll(path, 0o755) } - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return err } - f, err := os.OpenFile(path, os.O_CREATE, 0755) + f, err := os.OpenFile(path, os.O_CREATE, 0o755) if err != nil { return err } diff --git a/pkg/fileutils/fileutils_test.go b/pkg/fileutils/fileutils_test.go index 95d8bf970..3131720b1 100644 --- a/pkg/fileutils/fileutils_test.go +++ b/pkg/fileutils/fileutils_test.go @@ -25,14 +25,13 @@ func TestCopyFileWithInvalidSrc(t *testing.T) { if bytes != 0 { t.Fatal("Should have written 0 bytes") } - } // CopyFile with invalid dest func TestCopyFileWithInvalidDest(t *testing.T) { tempFolder := t.TempDir() src := path.Join(tempFolder, "file") - err := os.WriteFile(src, []byte("content"), 0740) + err := os.WriteFile(src, []byte("content"), 0o740) if err != nil { t.Fatal(err) } @@ -43,14 +42,13 @@ func TestCopyFileWithInvalidDest(t *testing.T) { if bytes != 0 { t.Fatal("Should have written 0 bytes") } - } // CopyFile with same src and dest func TestCopyFileWithSameSrcAndDest(t *testing.T) { tempFolder := t.TempDir() file := path.Join(tempFolder, "file") - err := os.WriteFile(file, []byte("content"), 0740) + err := os.WriteFile(file, []byte("content"), 0o740) if err != nil { t.Fatal(err) } @@ -67,13 +65,13 @@ func TestCopyFileWithSameSrcAndDest(t *testing.T) { func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { tempFolder := t.TempDir() testFolder := path.Join(tempFolder, "test") - err := os.MkdirAll(testFolder, 0740) + err := os.MkdirAll(testFolder, 0o740) if err != nil { t.Fatal(err) } file := path.Join(testFolder, "file") sameFile := testFolder + "/../test/file" - err = os.WriteFile(file, []byte("content"), 0740) + err = os.WriteFile(file, []byte("content"), 0o740) if err != nil { t.Fatal(err) } @@ -90,10 +88,10 @@ func TestCopyFile(t *testing.T) { tempFolder := t.TempDir() src := path.Join(tempFolder, "src") dest := path.Join(tempFolder, "dest") - err := os.WriteFile(src, []byte("content"), 0777) + err := os.WriteFile(src, []byte("content"), 0o777) require.NoError(t, err) - err = os.WriteFile(dest, []byte("destContent"), 0777) + err = os.WriteFile(dest, []byte("destContent"), 0o777) require.NoError(t, err) bytes, err := CopyFile(src, dest) if err != nil { @@ -118,7 +116,7 @@ func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { t.Skip("Needs porting to Windows") } var err error - if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { + if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0o777); err != nil { t.Errorf("failed to create directory: %s", err) } diff --git a/pkg/idmap/idmapped_utils.go b/pkg/idmap/idmapped_utils.go index f52239f87..68c8c867d 100644 --- a/pkg/idmap/idmapped_utils.go +++ b/pkg/idmap/idmapped_utils.go @@ -104,7 +104,7 @@ func CreateIDMappedMount(source, target string, pid int) error { &attr, uint(unsafe.Sizeof(attr))); err != nil { return err } - if err := os.Mkdir(target, 0700); err != nil && !os.IsExist(err) { + if err := os.Mkdir(target, 0o700); err != nil && !os.IsExist(err) { return err } return moveMount(targetDirFd, target) @@ -140,7 +140,7 @@ func CreateUsernsProcess(uidMaps []idtools.IDMap, gidMaps []idtools.IDMap) (int, for _, m := range idmap { mappings = mappings + fmt.Sprintf("%d %d %d\n", m.ContainerID, m.HostID, m.Size) } - return os.WriteFile(fmt.Sprintf("/proc/%d/%s", pid, fname), []byte(mappings), 0600) + return os.WriteFile(fmt.Sprintf("/proc/%d/%s", pid, fname), []byte(mappings), 0o600) } if err := writeMappings("uid_map", uidMaps); err != nil { cleanupFunc() diff --git a/pkg/idtools/idtools_unix.go b/pkg/idtools/idtools_unix.go index daff1e4a9..4701dc5ac 100644 --- a/pkg/idtools/idtools_unix.go +++ b/pkg/idtools/idtools_unix.go @@ -91,13 +91,13 @@ func CanAccess(path string, pair IDPair) bool { } func accessible(isOwner, isGroup bool, perms os.FileMode) bool { - if isOwner && (perms&0100 == 0100) { + if isOwner && (perms&0o100 == 0o100) { return true } - if isGroup && (perms&0010 == 0010) { + if isGroup && (perms&0o010 == 0o010) { return true } - if perms&0001 == 0001 { + if perms&0o001 == 0o001 { return true } return false diff --git a/pkg/idtools/idtools_unix_test.go b/pkg/idtools/idtools_unix_test.go index 8108c4fb8..0740c4ee8 100644 --- a/pkg/idtools/idtools_unix_test.go +++ b/pkg/idtools/idtools_unix_test.go @@ -34,7 +34,7 @@ func TestMkdirAllAs(t *testing.T) { } // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid - if err := MkdirAllAs(filepath.Join(dirName, "usr", "share"), 0755, 99, 99); err != nil { + if err := MkdirAllAs(filepath.Join(dirName, "usr", "share"), 0o755, 99, 99); err != nil { t.Fatal(err) } testTree["usr/share"] = node{99, 99} @@ -47,7 +47,7 @@ func TestMkdirAllAs(t *testing.T) { } // test 2-deep new directories--both should be owned by the uid/gid pair - if err := MkdirAllAs(filepath.Join(dirName, "lib", "some", "other"), 0755, 101, 101); err != nil { + if err := MkdirAllAs(filepath.Join(dirName, "lib", "some", "other"), 0o755, 101, 101); err != nil { t.Fatal(err) } testTree["lib/some"] = node{101, 101} @@ -61,7 +61,7 @@ func TestMkdirAllAs(t *testing.T) { } // test a directory that already exists; should be chowned, but nothing else - if err := MkdirAllAs(filepath.Join(dirName, "usr"), 0755, 102, 102); err != nil { + if err := MkdirAllAs(filepath.Join(dirName, "usr"), 0o755, 102, 102); err != nil { t.Fatal(err) } testTree["usr"] = node{102, 102} @@ -74,7 +74,7 @@ func TestMkdirAllAs(t *testing.T) { } // relative path will return an error - if err := MkdirAllAs("test", 0755, 102, 102); err == nil || err.Error() != "path: test should be absolute" { + if err := MkdirAllAs("test", 0o755, 102, 102); err == nil || err.Error() != "path: test should be absolute" { t.Fatalf("Expect path error, but got:%v", err) } } @@ -92,7 +92,7 @@ func TestMkdirAllAndChownNew(t *testing.T) { require.NoError(t, buildTree(dirName, testTree)) // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid - err := MkdirAllAndChownNew(filepath.Join(dirName, "usr", "share"), 0755, IDPair{99, 99}) + err := MkdirAllAndChownNew(filepath.Join(dirName, "usr", "share"), 0o755, IDPair{99, 99}) require.NoError(t, err) testTree["usr/share"] = node{99, 99} @@ -101,7 +101,7 @@ func TestMkdirAllAndChownNew(t *testing.T) { require.NoError(t, compareTrees(testTree, verifyTree)) // test 2-deep new directories--both should be owned by the uid/gid pair - err = MkdirAllAndChownNew(filepath.Join(dirName, "lib", "some", "other"), 0755, IDPair{101, 101}) + err = MkdirAllAndChownNew(filepath.Join(dirName, "lib", "some", "other"), 0o755, IDPair{101, 101}) require.NoError(t, err) testTree["lib/some"] = node{101, 101} testTree["lib/some/other"] = node{101, 101} @@ -110,7 +110,7 @@ func TestMkdirAllAndChownNew(t *testing.T) { require.NoError(t, compareTrees(testTree, verifyTree)) // test a directory that already exists; should NOT be chowned - err = MkdirAllAndChownNew(filepath.Join(dirName, "usr"), 0755, IDPair{102, 102}) + err = MkdirAllAndChownNew(filepath.Join(dirName, "usr"), 0o755, IDPair{102, 102}) require.NoError(t, err) verifyTree, err = readTree(dirName, "") require.NoError(t, err) @@ -118,7 +118,6 @@ func TestMkdirAllAndChownNew(t *testing.T) { } func TestMkdirAs(t *testing.T) { - dirName := t.TempDir() testTree := map[string]node{ @@ -129,7 +128,7 @@ func TestMkdirAs(t *testing.T) { } // test a directory that already exists; should just chown to the requested uid/gid - if err := MkdirAs(filepath.Join(dirName, "usr"), 0755, 99, 99); err != nil { + if err := MkdirAs(filepath.Join(dirName, "usr"), 0o755, 99, 99); err != nil { t.Fatal(err) } testTree["usr"] = node{99, 99} @@ -142,12 +141,12 @@ func TestMkdirAs(t *testing.T) { } // create a subdir under a dir which doesn't exist--should fail - if err := MkdirAs(filepath.Join(dirName, "usr", "bin", "subdir"), 0755, 102, 102); err == nil { + if err := MkdirAs(filepath.Join(dirName, "usr", "bin", "subdir"), 0o755, 102, 102); err == nil { t.Fatalf("Trying to create a directory with Mkdir where the parent doesn't exist should have failed") } // create a subdir under an existing dir; should only change the ownership of the new subdir - if err := MkdirAs(filepath.Join(dirName, "usr", "bin"), 0755, 102, 102); err != nil { + if err := MkdirAs(filepath.Join(dirName, "usr", "bin"), 0o755, 102, 102); err != nil { t.Fatal(err) } testTree["usr/bin"] = node{102, 102} @@ -163,7 +162,7 @@ func TestMkdirAs(t *testing.T) { func buildTree(base string, tree map[string]node) error { for path, node := range tree { fullPath := filepath.Join(base, path) - if err := os.MkdirAll(fullPath, 0755); err != nil { + if err := os.MkdirAll(fullPath, 0o755); err != nil { return fmt.Errorf("couldn't create path: %s; error: %w", fullPath, err) } if err := os.Chown(fullPath, node.uid, node.gid); err != nil { @@ -227,7 +226,7 @@ func TestParseSubidFileWithNewlinesAndComments(t *testing.T) { # empty default subuid/subgid file dockremap:231072:65536` - if err := os.WriteFile(fnamePath, []byte(fcontent), 0644); err != nil { + if err := os.WriteFile(fnamePath, []byte(fcontent), 0o644); err != nil { t.Fatal(err) } ranges, err := parseSubidFile(fnamePath, "dockremap") diff --git a/pkg/idtools/usergroupadd_linux.go b/pkg/idtools/usergroupadd_linux.go index 40e507f77..ac27718de 100644 --- a/pkg/idtools/usergroupadd_linux.go +++ b/pkg/idtools/usergroupadd_linux.go @@ -89,7 +89,6 @@ func addUser(userName string) error { } func createSubordinateRanges(name string) error { - // first, we should verify that ranges weren't automatically created // by the distro tooling ranges, err := readSubuid(name) diff --git a/pkg/idtools/utils_unix.go b/pkg/idtools/utils_unix.go index 33a7dee6c..b3772bdb3 100644 --- a/pkg/idtools/utils_unix.go +++ b/pkg/idtools/utils_unix.go @@ -19,8 +19,8 @@ func resolveBinary(binname string) (string, error) { if err != nil { return "", err } - //only return no error if the final resolved binary basename - //matches what was searched for + // only return no error if the final resolved binary basename + // matches what was searched for if filepath.Base(resolvedPath) == binname { return resolvedPath, nil } diff --git a/pkg/ioutils/fswriters_test.go b/pkg/ioutils/fswriters_test.go index c96800b8a..9c997c9e6 100644 --- a/pkg/ioutils/fswriters_test.go +++ b/pkg/ioutils/fswriters_test.go @@ -8,14 +8,12 @@ import ( "testing" ) -var ( - testMode os.FileMode = 0640 -) +var testMode os.FileMode = 0o640 func init() { // Windows does not support full Linux file mode if runtime.GOOS == "windows" { - testMode = 0666 + testMode = 0o666 } } @@ -53,13 +51,12 @@ func TestAtomicCommitAndRollbackFile(t *testing.T) { newData := "newdata" check := func(n int, initData string, writeData string, expected string, explicit bool, commit bool) { - if err := os.WriteFile(path, []byte(initData), 0644); err != nil { + if err := os.WriteFile(path, []byte(initData), 0o644); err != nil { t.Fatalf("Failed creating initial file: %v", err) } opts := &AtomicFileWriterOptions{ExplicitCommit: explicit} - w, err := NewAtomicFileWriterWithOpts(filepath.Join(tmpDir, "foo"), 0644, opts) - + w, err := NewAtomicFileWriterWithOpts(filepath.Join(tmpDir, "foo"), 0o644, opts) if err != nil { t.Fatalf("(%d) Failed creating writer: %v", n, err) } @@ -98,7 +95,7 @@ func TestAtomicCommitAndRollbackFile(t *testing.T) { func TestAtomicWriteSetCommit(t *testing.T) { tmpDir := t.TempDir() - if err := os.Mkdir(filepath.Join(tmpDir, "tmp"), 0700); err != nil { + if err := os.Mkdir(filepath.Join(tmpDir, "tmp"), 0o700); err != nil { t.Fatalf("Error creating tmp directory: %s", err) } @@ -137,13 +134,12 @@ func TestAtomicWriteSetCommit(t *testing.T) { if expected := os.FileMode(testMode); st.Mode() != expected { t.Fatalf("Mode mismatched, expected %o, got %o", expected, st.Mode()) } - } func TestAtomicWriteSetCancel(t *testing.T) { tmpDir := t.TempDir() - if err := os.Mkdir(filepath.Join(tmpDir, "tmp"), 0700); err != nil { + if err := os.Mkdir(filepath.Join(tmpDir, "tmp"), 0o700); err != nil { t.Fatalf("Error creating tmp directory: %s", err) } diff --git a/pkg/ioutils/writers_test.go b/pkg/ioutils/writers_test.go index bb711ead4..abda43bbe 100644 --- a/pkg/ioutils/writers_test.go +++ b/pkg/ioutils/writers_test.go @@ -29,7 +29,6 @@ func TestNopWriteCloser(t *testing.T) { if err := wrapper.Close(); err != nil { t.Fatal("NopWriteCloser always return nil on Close.") } - } func TestNopWriter(t *testing.T) { diff --git a/pkg/lockfile/lockfile_unix.go b/pkg/lockfile/lockfile_unix.go index 335980914..a357b809e 100644 --- a/pkg/lockfile/lockfile_unix.go +++ b/pkg/lockfile/lockfile_unix.go @@ -135,7 +135,7 @@ func openLock(path string, ro bool) (fd int, err error) { // the directory of the lockfile seems to be removed, try to create it if os.IsNotExist(err) { - if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return fd, fmt.Errorf("creating lock file directory: %w", err) } diff --git a/pkg/lockfile/lockfile_windows.go b/pkg/lockfile/lockfile_windows.go index 09f2aca5c..ca27a483d 100644 --- a/pkg/lockfile/lockfile_windows.go +++ b/pkg/lockfile/lockfile_windows.go @@ -138,6 +138,7 @@ func (l *LockFile) Modified() (bool, error) { func (l *LockFile) Touch() error { return nil } + func (l *LockFile) IsReadWrite() bool { return false } diff --git a/pkg/loopback/attach_loopback.go b/pkg/loopback/attach_loopback.go index de10e3324..b8bfa5897 100644 --- a/pkg/loopback/attach_loopback.go +++ b/pkg/loopback/attach_loopback.go @@ -26,7 +26,7 @@ func stringToLoopName(src string) [LoNameSize]uint8 { } func getNextFreeLoopbackIndex() (int, error) { - f, err := os.OpenFile("/dev/loop-control", os.O_RDONLY, 0644) + f, err := os.OpenFile("/dev/loop-control", os.O_RDONLY, 0o644) if err != nil { return 0, err } @@ -67,7 +67,7 @@ func openNextAvailableLoopback(index int, sparseName string, sparseFile *os.File } // OpenFile adds O_CLOEXEC - loopFile, err = os.OpenFile(target, os.O_RDWR, 0644) + loopFile, err = os.OpenFile(target, os.O_RDWR, 0o644) if err != nil { logrus.Errorf("Opening loopback device: %s", err) return nil, ErrAttachLoopbackDevice @@ -114,7 +114,6 @@ func openNextAvailableLoopback(index int, sparseName string, sparseFile *os.File // AttachLoopDevice attaches the given sparse file to the next // available loopback device. It returns an opened *os.File. func AttachLoopDevice(sparseName string) (loop *os.File, err error) { - // Try to retrieve the next available loopback device via syscall. // If it fails, we discard error and start looping for a // loopback from index 0. @@ -124,7 +123,7 @@ func AttachLoopDevice(sparseName string) (loop *os.File, err error) { } // OpenFile adds O_CLOEXEC - sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644) + sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0o644) if err != nil { logrus.Errorf("Opening sparse file: %v", err) return nil, ErrAttachLoopbackDevice diff --git a/pkg/mflag/example/example.go b/pkg/mflag/example/example.go index 0747c0210..2a6fc23bc 100644 --- a/pkg/mflag/example/example.go +++ b/pkg/mflag/example/example.go @@ -23,6 +23,7 @@ func init() { flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3") flag.Parse() } + func main() { if h { flag.PrintDefaults() diff --git a/pkg/mflag/flag_test.go b/pkg/mflag/flag_test.go index f86b3878d..91f4319c0 100644 --- a/pkg/mflag/flag_test.go +++ b/pkg/mflag/flag_test.go @@ -24,6 +24,7 @@ func ResetForTesting(usage func()) { CommandLine = NewFlagSet(os.Args[0], ContinueOnError) Usage = usage } + func boolString(s string) string { if s == "0" { return "false" @@ -405,7 +406,7 @@ func TestChangingArgs(t *testing.T) { // Test that -help invokes the usage message and returns ErrHelp. func TestHelp(t *testing.T) { - var helpCalled = false + helpCalled := false fs := NewFlagSet("help test", ContinueOnError) fs.Usage = func() { helpCalled = true } var flag bool diff --git a/pkg/mount/mount_unix_test.go b/pkg/mount/mount_unix_test.go index f0acbbf11..cc11fd53e 100644 --- a/pkg/mount/mount_unix_test.go +++ b/pkg/mount/mount_unix_test.go @@ -31,7 +31,7 @@ func TestMounted(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -43,11 +43,11 @@ func TestMounted(t *testing.T) { targetPath = path.Join(targetDir, "file.txt") ) - if err := os.Mkdir(sourceDir, 0777); err != nil { + if err := os.Mkdir(sourceDir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(targetDir, 0777); err != nil { + if err := os.Mkdir(targetDir, 0o777); err != nil { t.Fatal(err) } @@ -94,7 +94,7 @@ func TestMountReadonly(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -106,10 +106,10 @@ func TestMountReadonly(t *testing.T) { targetPath = path.Join(targetDir, "file.txt") ) - if err := os.Mkdir(sourceDir, 0777); err != nil { + if err := os.Mkdir(sourceDir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(targetDir, 0777); err != nil { + if err := os.Mkdir(targetDir, 0o777); err != nil { t.Fatal(err) } @@ -138,7 +138,7 @@ func TestMountReadonly(t *testing.T) { } }() - f, err = os.OpenFile(targetPath, os.O_RDWR, 0777) + f, err = os.OpenFile(targetPath, os.O_RDWR, 0o777) if err == nil { f.Close() t.Fatal("Should not be able to open a ro file as rw") diff --git a/pkg/mount/sharedsubtree_linux_test.go b/pkg/mount/sharedsubtree_linux_test.go index 5b919feb1..6db1a4081 100644 --- a/pkg/mount/sharedsubtree_linux_test.go +++ b/pkg/mount/sharedsubtree_linux_test.go @@ -16,7 +16,7 @@ func TestSubtreePrivate(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -32,19 +32,19 @@ func TestSubtreePrivate(t *testing.T) { outside1CheckPath = path.Join(targetDir, "a", "file.txt") outside2CheckPath = path.Join(sourceDir, "b", "file.txt") ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { + if err := os.MkdirAll(path.Join(sourceDir, "a"), 0o777); err != nil { t.Fatal(err) } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { + if err := os.MkdirAll(path.Join(sourceDir, "b"), 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(targetDir, 0777); err != nil { + if err := os.Mkdir(targetDir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(outside1Dir, 0777); err != nil { + if err := os.Mkdir(outside1Dir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(outside2Dir, 0777); err != nil { + if err := os.Mkdir(outside2Dir, 0o777); err != nil { t.Fatal(err) } @@ -118,7 +118,7 @@ func TestSubtreeShared(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -132,13 +132,13 @@ func TestSubtreeShared(t *testing.T) { sourceCheckPath = path.Join(sourceDir, "a", "file.txt") ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { + if err := os.MkdirAll(path.Join(sourceDir, "a"), 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(targetDir, 0777); err != nil { + if err := os.Mkdir(targetDir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(outsideDir, 0777); err != nil { + if err := os.Mkdir(outsideDir, 0o777); err != nil { t.Fatal(err) } @@ -190,7 +190,7 @@ func TestSubtreeSharedSlave(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -206,19 +206,19 @@ func TestSubtreeSharedSlave(t *testing.T) { outside1CheckPath = path.Join(targetDir, "a", "file.txt") outside2CheckPath = path.Join(sourceDir, "b", "file.txt") ) - if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { + if err := os.MkdirAll(path.Join(sourceDir, "a"), 0o777); err != nil { t.Fatal(err) } - if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { + if err := os.MkdirAll(path.Join(sourceDir, "b"), 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(targetDir, 0777); err != nil { + if err := os.Mkdir(targetDir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(outside1Dir, 0777); err != nil { + if err := os.Mkdir(outside1Dir, 0o777); err != nil { t.Fatal(err) } - if err := os.Mkdir(outside2Dir, 0777); err != nil { + if err := os.Mkdir(outside2Dir, 0o777); err != nil { t.Fatal(err) } @@ -298,7 +298,7 @@ func TestSubtreeUnbindable(t *testing.T) { } tmp := path.Join(os.TempDir(), "mount-tests") - if err := os.MkdirAll(tmp, 0777); err != nil { + if err := os.MkdirAll(tmp, 0o777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) @@ -307,10 +307,10 @@ func TestSubtreeUnbindable(t *testing.T) { sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") ) - if err := os.MkdirAll(sourceDir, 0777); err != nil { + if err := os.MkdirAll(sourceDir, 0o777); err != nil { t.Fatal(err) } - if err := os.MkdirAll(targetDir, 0777); err != nil { + if err := os.MkdirAll(targetDir, 0o777); err != nil { t.Fatal(err) } diff --git a/pkg/parsers/kernel/kernel_unix_test.go b/pkg/parsers/kernel/kernel_unix_test.go index 9bf956bae..5ca918746 100644 --- a/pkg/parsers/kernel/kernel_unix_test.go +++ b/pkg/parsers/kernel/kernel_unix_test.go @@ -10,9 +10,7 @@ import ( func assertParseRelease(t *testing.T, release string, b *VersionInfo, result int) { t.Helper() - var ( - a *VersionInfo - ) + var a *VersionInfo a, _ = ParseRelease(release) if r := CompareKernelVersion(*a, *b); r != result { diff --git a/pkg/parsers/kernel/kernel_windows.go b/pkg/parsers/kernel/kernel_windows.go index b30da9fad..4b7fdee83 100644 --- a/pkg/parsers/kernel/kernel_windows.go +++ b/pkg/parsers/kernel/kernel_windows.go @@ -24,7 +24,6 @@ func (k *VersionInfo) String() string { // GetKernelVersion gets the current kernel version. func GetKernelVersion() (*VersionInfo, error) { - var ( h windows.Handle dwVersion uint32 diff --git a/pkg/parsers/operatingsystem/operatingsystem_unix_test.go b/pkg/parsers/operatingsystem/operatingsystem_unix_test.go index a9db8a7d8..1df2af1ba 100644 --- a/pkg/parsers/operatingsystem/operatingsystem_unix_test.go +++ b/pkg/parsers/operatingsystem/operatingsystem_unix_test.go @@ -10,7 +10,7 @@ import ( ) func TestGetOperatingSystem(t *testing.T) { - var backup = etcOsRelease + backup := etcOsRelease invalids := []struct { content string @@ -117,7 +117,7 @@ PRETTY_NAME="Source Mage"`, }() for _, elt := range invalids { - if err := os.WriteFile(etcOsRelease, []byte(elt.content), 0600); err != nil { + if err := os.WriteFile(etcOsRelease, []byte(elt.content), 0o600); err != nil { t.Fatalf("failed to write to %s: %v", etcOsRelease, err) } s, err := GetOperatingSystem() @@ -127,7 +127,7 @@ PRETTY_NAME="Source Mage"`, } for _, elt := range valids { - if err := os.WriteFile(etcOsRelease, []byte(elt.content), 0600); err != nil { + if err := os.WriteFile(etcOsRelease, []byte(elt.content), 0o600); err != nil { t.Fatalf("failed to write to %s: %v", etcOsRelease, err) } s, err := GetOperatingSystem() @@ -183,7 +183,7 @@ func TestIsContainerized(t *testing.T) { proc1Cgroup = backup }() - if err := os.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroup, 0600); err != nil { + if err := os.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroup, 0o600); err != nil { t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) } inContainer, err := IsContainerized() @@ -194,7 +194,7 @@ func TestIsContainerized(t *testing.T) { t.Fatal("Wrongly assuming containerized") } - if err := os.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroupsystemd226, 0600); err != nil { + if err := os.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroupsystemd226, 0o600); err != nil { t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) } inContainer, err = IsContainerized() @@ -205,7 +205,7 @@ func TestIsContainerized(t *testing.T) { t.Fatal("Wrongly assuming containerized for systemd /init.scope cgroup layout") } - if err := os.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0600); err != nil { + if err := os.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0o600); err != nil { t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) } inContainer, err = IsContainerized() @@ -218,8 +218,8 @@ func TestIsContainerized(t *testing.T) { } func TestOsReleaseFallback(t *testing.T) { - var backup = etcOsRelease - var altBackup = altOsRelease + backup := etcOsRelease + altBackup := altOsRelease dir := os.TempDir() etcOsRelease = filepath.Join(dir, "etcOsRelease") altOsRelease = filepath.Join(dir, "altOsRelease") @@ -237,7 +237,7 @@ HOME_URL="http://www.gentoo.org/" SUPPORT_URL="http://www.gentoo.org/main/en/support.xml" BUG_REPORT_URL="https://bugs.gentoo.org/" ` - if err := os.WriteFile(altOsRelease, []byte(content), 0600); err != nil { + if err := os.WriteFile(altOsRelease, []byte(content), 0o600); err != nil { t.Fatalf("failed to write to %s: %v", etcOsRelease, err) } s, err := GetOperatingSystem() diff --git a/pkg/parsers/operatingsystem/operatingsystem_windows.go b/pkg/parsers/operatingsystem/operatingsystem_windows.go index 5d8b42cc3..bcf736c75 100644 --- a/pkg/parsers/operatingsystem/operatingsystem_windows.go +++ b/pkg/parsers/operatingsystem/operatingsystem_windows.go @@ -11,7 +11,6 @@ import ( // GetOperatingSystem gets the name of the current operating system. func GetOperatingSystem() (string, error) { - var h windows.Handle // Default return value diff --git a/pkg/promise/promise_test.go b/pkg/promise/promise_test.go index 287213b50..5837904c5 100644 --- a/pkg/promise/promise_test.go +++ b/pkg/promise/promise_test.go @@ -20,6 +20,7 @@ func TestGo(t *testing.T) { func functionWithError() (err error) { return errors.New("Error Occurred") } + func functionWithNoError() (err error) { return nil } diff --git a/pkg/regexp/regexp.go b/pkg/regexp/regexp.go index 8c116aa07..17b7ce8a3 100644 --- a/pkg/regexp/regexp.go +++ b/pkg/regexp/regexp.go @@ -47,6 +47,7 @@ func (re *Regexp) ExpandString(dst []byte, template string, src string, match [] re.compile() return re.regexp.ExpandString(dst, template, src, match) } + func (re *Regexp) Find(b []byte) []byte { re.compile() return re.regexp.Find(b) @@ -156,6 +157,7 @@ func (re *Regexp) MatchReader(r io.RuneReader) bool { re.compile() return re.regexp.MatchReader(r) } + func (re *Regexp) MatchString(s string) bool { re.compile() return re.regexp.MatchString(s) diff --git a/pkg/system/chtimes_test.go b/pkg/system/chtimes_test.go index 286c8d77f..8aba3c149 100644 --- a/pkg/system/chtimes_test.go +++ b/pkg/system/chtimes_test.go @@ -11,7 +11,7 @@ import ( func prepareTempFile(t *testing.T) string { t.Helper() file := filepath.Join(t.TempDir(), "exist") - if err := os.WriteFile(file, []byte("hello"), 0644); err != nil { + if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { t.Fatal(err) } return file diff --git a/pkg/system/errors.go b/pkg/system/errors.go index 288318985..b87d419b5 100644 --- a/pkg/system/errors.go +++ b/pkg/system/errors.go @@ -4,7 +4,5 @@ import ( "errors" ) -var ( - // ErrNotSupportedPlatform means the platform is not supported. - ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") -) +// ErrNotSupportedPlatform means the platform is not supported. +var ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") diff --git a/pkg/system/init_windows.go b/pkg/system/init_windows.go index 019c66441..5f6fea1d3 100644 --- a/pkg/system/init_windows.go +++ b/pkg/system/init_windows.go @@ -13,5 +13,4 @@ func init() { if os.Getenv("LCOW_SUPPORTED") != "" { lcowSupported = true } - } diff --git a/pkg/system/meminfo_solaris.go b/pkg/system/meminfo_solaris.go index df53c40e2..a90b23e03 100644 --- a/pkg/system/meminfo_solaris.go +++ b/pkg/system/meminfo_solaris.go @@ -84,7 +84,6 @@ func getFreeMem() int64 { // // MemInfo type. func ReadMemInfo() (*MemInfo, error) { - ppKernel := C.getPpKernel() MemTotal := getTotalMem() MemFree := getFreeMem() diff --git a/pkg/system/path.go b/pkg/system/path.go index f634a6be6..ca076f2bc 100644 --- a/pkg/system/path.go +++ b/pkg/system/path.go @@ -17,5 +17,4 @@ func DefaultPathEnv(platform string) string { return "" } return defaultUnixPathEnv - } diff --git a/pkg/system/rm_test.go b/pkg/system/rm_test.go index dced94191..58f03a70e 100644 --- a/pkg/system/rm_test.go +++ b/pkg/system/rm_test.go @@ -44,7 +44,7 @@ func TestEnsureRemoveAllWithMount(t *testing.T) { dir2 := t.TempDir() bindDir := filepath.Join(dir1, "bind") - if err := os.MkdirAll(bindDir, 0755); err != nil { + if err := os.MkdirAll(bindDir, 0o755); err != nil { t.Fatal(err) } diff --git a/pkg/system/stat_common.go b/pkg/system/stat_common.go index e965c54c2..2f44d18b6 100644 --- a/pkg/system/stat_common.go +++ b/pkg/system/stat_common.go @@ -3,8 +3,7 @@ package system -type platformStatT struct { -} +type platformStatT struct{} // Flags return file flags if supported or zero otherwise func (s StatT) Flags() uint32 { diff --git a/pkg/system/stat_darwin.go b/pkg/system/stat_darwin.go index 715f05b93..57850a883 100644 --- a/pkg/system/stat_darwin.go +++ b/pkg/system/stat_darwin.go @@ -4,10 +4,12 @@ import "syscall" // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, + return &StatT{ + size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil + mtim: s.Mtimespec, + }, nil } diff --git a/pkg/system/stat_freebsd.go b/pkg/system/stat_freebsd.go index 9c510468f..4b95073a3 100644 --- a/pkg/system/stat_freebsd.go +++ b/pkg/system/stat_freebsd.go @@ -13,13 +13,15 @@ func (s StatT) Flags() uint32 { // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - st := &StatT{size: s.Size, + st := &StatT{ + size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtimespec, - dev: s.Dev} + dev: s.Dev, + } st.flags = s.Flags st.dev = s.Dev return st, nil diff --git a/pkg/system/stat_freebsd_test.go b/pkg/system/stat_freebsd_test.go index deac2f3b6..8a9cb4719 100644 --- a/pkg/system/stat_freebsd_test.go +++ b/pkg/system/stat_freebsd_test.go @@ -23,7 +23,7 @@ func platformTestFromStatT(t *testing.T, stat *syscall.Stat_t, s *StatT) { func TestFileFlags(t *testing.T) { dir := t.TempDir() file := filepath.Join(dir, "append") - if err := os.WriteFile(file, []byte("hello"), 0644); err != nil { + if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { t.Fatal(err) } diff --git a/pkg/system/stat_linux.go b/pkg/system/stat_linux.go index e5dcba822..e3d13463f 100644 --- a/pkg/system/stat_linux.go +++ b/pkg/system/stat_linux.go @@ -4,13 +4,15 @@ import "syscall" // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, + return &StatT{ + size: s.Size, mode: s.Mode, uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtim, - dev: uint64(s.Dev)}, nil + dev: uint64(s.Dev), + }, nil } // FromStatT converts a syscall.Stat_t type to a system.Stat_t type diff --git a/pkg/system/stat_openbsd.go b/pkg/system/stat_openbsd.go index b607dea94..a413e1714 100644 --- a/pkg/system/stat_openbsd.go +++ b/pkg/system/stat_openbsd.go @@ -4,10 +4,12 @@ import "syscall" // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, + return &StatT{ + size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil + mtim: s.Mtim, + }, nil } diff --git a/pkg/system/stat_solaris.go b/pkg/system/stat_solaris.go index b607dea94..a413e1714 100644 --- a/pkg/system/stat_solaris.go +++ b/pkg/system/stat_solaris.go @@ -4,10 +4,12 @@ import "syscall" // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, + return &StatT{ + size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil + mtim: s.Mtim, + }, nil } diff --git a/pkg/system/stat_windows.go b/pkg/system/stat_windows.go index 81edaadbb..6d5c6c142 100644 --- a/pkg/system/stat_windows.go +++ b/pkg/system/stat_windows.go @@ -65,5 +65,6 @@ func fromStatT(fi *os.FileInfo) (*StatT, error) { return &StatT{ size: (*fi).Size(), mode: (*fi).Mode(), - mtim: (*fi).ModTime()}, nil + mtim: (*fi).ModTime(), + }, nil } diff --git a/pkg/system/utimes_unix_test.go b/pkg/system/utimes_unix_test.go index a921f34e8..1536760a9 100644 --- a/pkg/system/utimes_unix_test.go +++ b/pkg/system/utimes_unix_test.go @@ -15,7 +15,7 @@ func prepareFiles(t *testing.T) (string, string, string) { dir := t.TempDir() file := filepath.Join(dir, "exist") - if err := os.WriteFile(file, []byte("hello"), 0644); err != nil { + if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil { t.Fatal(err) } diff --git a/pkg/truncindex/truncindex.go b/pkg/truncindex/truncindex.go index b81793adc..c14a5cc4d 100644 --- a/pkg/truncindex/truncindex.go +++ b/pkg/truncindex/truncindex.go @@ -102,9 +102,7 @@ func (idx *TruncIndex) Get(s string) (string, error) { if s == "" { return "", ErrEmptyPrefix } - var ( - id string - ) + var id string subTreeVisitFunc := func(prefix patricia.Prefix, item patricia.Item) error { if id != "" { // we haven't found the ID if there are two or more IDs diff --git a/pkg/unshare/unshare_test.go b/pkg/unshare/unshare_test.go index 99cf28026..f3e3db013 100644 --- a/pkg/unshare/unshare_test.go +++ b/pkg/unshare/unshare_test.go @@ -29,15 +29,13 @@ func init() { reexec.Register("report", report) } -var ( - CloneFlags = map[string]int{ - "ipc": syscall.CLONE_NEWIPC, - "net": syscall.CLONE_NEWNET, - "mnt": syscall.CLONE_NEWNS, - "user": syscall.CLONE_NEWUSER, - "uts": syscall.CLONE_NEWUTS, - } -) +var CloneFlags = map[string]int{ + "ipc": syscall.CLONE_NEWIPC, + "net": syscall.CLONE_NEWNET, + "mnt": syscall.CLONE_NEWNS, + "user": syscall.CLONE_NEWUSER, + "uts": syscall.CLONE_NEWUTS, +} type Report struct { Namespaces map[string]string diff --git a/store.go b/store.go index a4dd215c2..e75420089 100644 --- a/store.go +++ b/store.go @@ -758,22 +758,22 @@ func GetStore(options types.StoreOptions) (Store, error) { options.RunRoot = defaultOpts.RunRoot } - if err := os.MkdirAll(options.RunRoot, 0700); err != nil { + if err := os.MkdirAll(options.RunRoot, 0o700); err != nil { return nil, err } - if err := os.MkdirAll(options.GraphRoot, 0700); err != nil { + if err := os.MkdirAll(options.GraphRoot, 0o700); err != nil { return nil, err } if options.ImageStore != "" { - if err := os.MkdirAll(options.ImageStore, 0700); err != nil { + if err := os.MkdirAll(options.ImageStore, 0o700); err != nil { return nil, err } } - if err := os.MkdirAll(filepath.Join(options.GraphRoot, options.GraphDriverName), 0700); err != nil { + if err := os.MkdirAll(filepath.Join(options.GraphRoot, options.GraphDriverName), 0o700); err != nil { return nil, err } if options.ImageStore != "" { - if err := os.MkdirAll(filepath.Join(options.ImageStore, options.GraphDriverName), 0700); err != nil { + if err := os.MkdirAll(filepath.Join(options.ImageStore, options.GraphDriverName), 0o700); err != nil { return nil, err } } @@ -914,7 +914,7 @@ func (s *store) load() error { imgStoreRoot = s.graphRoot } gipath := filepath.Join(imgStoreRoot, driverPrefix+"images") - if err := os.MkdirAll(gipath, 0700); err != nil { + if err := os.MkdirAll(gipath, 0o700); err != nil { return err } ris, err := newImageStore(gipath) @@ -924,11 +924,11 @@ func (s *store) load() error { s.imageStore = ris gcpath := filepath.Join(s.graphRoot, driverPrefix+"containers") - if err := os.MkdirAll(gcpath, 0700); err != nil { + if err := os.MkdirAll(gcpath, 0o700); err != nil { return err } rcpath := filepath.Join(s.runRoot, driverPrefix+"containers") - if err := os.MkdirAll(rcpath, 0700); err != nil { + if err := os.MkdirAll(rcpath, 0o700); err != nil { return err } @@ -962,7 +962,7 @@ func (s *store) load() error { } s.digestLockRoot = filepath.Join(s.runRoot, driverPrefix+"locks") - if err := os.MkdirAll(s.digestLockRoot, 0700); err != nil { + if err := os.MkdirAll(s.digestLockRoot, 0o700); err != nil { return err } @@ -1061,7 +1061,7 @@ func (s *store) getLayerStoreLocked() (rwLayerStore, error) { } driverPrefix := s.graphDriverName + "-" rlpath := filepath.Join(s.runRoot, driverPrefix+"layers") - if err := os.MkdirAll(rlpath, 0700); err != nil { + if err := os.MkdirAll(rlpath, 0o700); err != nil { return nil, err } imgStoreRoot := s.imageStoreDir @@ -1069,7 +1069,7 @@ func (s *store) getLayerStoreLocked() (rwLayerStore, error) { imgStoreRoot = s.graphRoot } glpath := filepath.Join(imgStoreRoot, driverPrefix+"layers") - if err := os.MkdirAll(glpath, 0700); err != nil { + if err := os.MkdirAll(glpath, 0o700); err != nil { return nil, err } rls, err := s.newLayerStore(rlpath, glpath, s.graphDriver, s.transientStore) @@ -1100,7 +1100,7 @@ func (s *store) getROLayerStoresLocked() ([]roLayerStore, error) { } driverPrefix := s.graphDriverName + "-" rlpath := filepath.Join(s.runRoot, driverPrefix+"layers") - if err := os.MkdirAll(rlpath, 0700); err != nil { + if err := os.MkdirAll(rlpath, 0o700); err != nil { return nil, err } for _, store := range s.graphDriver.AdditionalImageStores() { @@ -2382,7 +2382,6 @@ func (s *store) Names(id string) ([]string, error) { } return nil, ErrLayerUnknown - } func (s *store) Lookup(name string) (string, error) { @@ -3250,7 +3249,7 @@ func (s *store) ContainerDirectory(id string) (string, error) { middleDir := s.graphDriverName + "-containers" gcpath := filepath.Join(s.GraphRoot(), middleDir, id, "userdata") - if err := os.MkdirAll(gcpath, 0700); err != nil { + if err := os.MkdirAll(gcpath, 0o700); err != nil { return "", true, err } return gcpath, true, nil @@ -3267,7 +3266,7 @@ func (s *store) ContainerRunDirectory(id string) (string, error) { middleDir := s.graphDriverName + "-containers" rcpath := filepath.Join(s.RunRoot(), middleDir, id, "userdata") - if err := os.MkdirAll(rcpath, 0700); err != nil { + if err := os.MkdirAll(rcpath, 0o700); err != nil { return "", true, err } return rcpath, true, nil @@ -3280,11 +3279,11 @@ func (s *store) SetContainerDirectoryFile(id, file string, data []byte) error { if err != nil { return err } - err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0700) + err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0o700) if err != nil { return err } - return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0600) + return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0o600) } func (s *store) FromContainerDirectory(id, file string) ([]byte, error) { @@ -3300,11 +3299,11 @@ func (s *store) SetContainerRunDirectoryFile(id, file string, data []byte) error if err != nil { return err } - err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0700) + err = os.MkdirAll(filepath.Dir(filepath.Join(dir, file)), 0o700) if err != nil { return err } - return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0600) + return ioutils.AtomicWriteFile(filepath.Join(dir, file), data, 0o600) } func (s *store) FromContainerRunDirectory(id, file string) ([]byte, error) { diff --git a/types/options_darwin.go b/types/options_darwin.go index 3c8ff4e4e..3eecc2b82 100644 --- a/types/options_darwin.go +++ b/types/options_darwin.go @@ -8,9 +8,7 @@ const ( SystemConfigFile = "/usr/share/containers/storage.conf" ) -var ( - defaultOverrideConfigFile = "/etc/containers/storage.conf" -) +var defaultOverrideConfigFile = "/etc/containers/storage.conf" // canUseRootlessOverlay returns true if the overlay driver can be used for rootless containers func canUseRootlessOverlay(home, runhome string) bool { diff --git a/types/utils.go b/types/utils.go index 72c38f861..73134f82d 100644 --- a/types/utils.go +++ b/types/utils.go @@ -20,7 +20,7 @@ func GetRootlessRuntimeDir(rootlessUID int) (string, error) { return "", err } path = filepath.Join(path, "containers") - if err := os.MkdirAll(path, 0700); err != nil { + if err := os.MkdirAll(path, 0o700); err != nil { return "", fmt.Errorf("unable to make rootless runtime: %w", err) } return path, nil @@ -45,25 +45,30 @@ type rootlessRuntimeDirEnvironmentImplementation struct { func (env rootlessRuntimeDirEnvironmentImplementation) getProcCommandFile() string { return env.procCommandFile } + func (env rootlessRuntimeDirEnvironmentImplementation) getRunUserDir() string { return env.runUserDir } + func (env rootlessRuntimeDirEnvironmentImplementation) getTmpPerUserDir() string { return env.tmpPerUserDir } + func (rootlessRuntimeDirEnvironmentImplementation) homeDirGetRuntimeDir() (string, error) { return homedir.GetRuntimeDir() } + func (rootlessRuntimeDirEnvironmentImplementation) systemLstat(path string) (*system.StatT, error) { return system.Lstat(path) } + func (rootlessRuntimeDirEnvironmentImplementation) homedirGet() string { return homedir.Get() } func isRootlessRuntimeDirOwner(dir string, env rootlessRuntimeDirEnvironment) bool { st, err := env.systemLstat(dir) - return err == nil && int(st.UID()) == os.Getuid() && st.Mode()&0700 == 0700 && st.Mode()&0066 == 0000 + return err == nil && int(st.UID()) == os.Getuid() && st.Mode()&0o700 == 0o700 && st.Mode()&0o066 == 0o000 } // getRootlessRuntimeDirIsolated is an internal implementation detail of getRootlessRuntimeDir to allow testing. @@ -85,7 +90,7 @@ func getRootlessRuntimeDirIsolated(env rootlessRuntimeDirEnvironment) (string, e tmpPerUserDir := env.getTmpPerUserDir() if tmpPerUserDir != "" { if _, err := env.systemLstat(tmpPerUserDir); os.IsNotExist(err) { - if err := os.Mkdir(tmpPerUserDir, 0700); err != nil { + if err := os.Mkdir(tmpPerUserDir, 0o700); err != nil { logrus.Errorf("Failed to create temp directory for user: %v", err) } else { return tmpPerUserDir, nil diff --git a/types/utils_test.go b/types/utils_test.go index 21b4bb673..a6c8d50f4 100644 --- a/types/utils_test.go +++ b/types/utils_test.go @@ -29,18 +29,23 @@ type rootlessRuntimeDirEnvironmentTest struct { func (env rootlessRuntimeDirEnvironmentTest) getProcCommandFile() string { return env.procCommandFile } + func (env rootlessRuntimeDirEnvironmentTest) getRunUserDir() string { return env.runUserDir } + func (env rootlessRuntimeDirEnvironmentTest) getTmpPerUserDir() string { return env.tmpPerUserDir } + func (env rootlessRuntimeDirEnvironmentTest) homeDirGetRuntimeDir() (string, error) { return env.homeRuntime.dir, env.homeRuntime.err } + func (env rootlessRuntimeDirEnvironmentTest) systemLstat(path string) (*system.StatT, error) { return system.Lstat(path) } + func (env rootlessRuntimeDirEnvironmentTest) homedirGet() string { return env.homeDir } @@ -49,25 +54,25 @@ func TestRootlessRuntimeDir(t *testing.T) { testDir := t.TempDir() homeRuntimeDir := filepath.Join(testDir, "home-rundir") - err := os.Mkdir(homeRuntimeDir, 0700) + err := os.Mkdir(homeRuntimeDir, 0o700) assert.NilError(t, err) homeRuntimeDisabled := homeRuntimeData{err: errors.New("homedirGetRuntimeDir is disabled")} systemdCommandFile := filepath.Join(testDir, "systemd-command") - err = os.WriteFile(systemdCommandFile, []byte("systemd"), 0644) + err = os.WriteFile(systemdCommandFile, []byte("systemd"), 0o644) assert.NilError(t, err) initCommandFile := filepath.Join(testDir, "init-command") - err = os.WriteFile(initCommandFile, []byte("init"), 0644) + err = os.WriteFile(initCommandFile, []byte("init"), 0o644) assert.NilError(t, err) dirForOwner := filepath.Join(testDir, "dir-for-owner") - err = os.Mkdir(dirForOwner, 0700) + err = os.Mkdir(dirForOwner, 0o700) assert.NilError(t, err) dirForAll := filepath.Join(testDir, "dir-for-all") - err = os.Mkdir(dirForAll, 0777) + err = os.Mkdir(dirForAll, 0o777) assert.NilError(t, err) dirToBeCreated := filepath.Join(testDir, "dir-to-be-created") @@ -216,26 +221,31 @@ type rootlessRuntimeDirEnvironmentRace struct { func (env rootlessRuntimeDirEnvironmentRace) getProcCommandFile() string { return env.procCommandFile } + func (rootlessRuntimeDirEnvironmentRace) getRunUserDir() string { return "" } + func (env rootlessRuntimeDirEnvironmentRace) getTmpPerUserDir() string { return env.tmpPerUserDir } + func (rootlessRuntimeDirEnvironmentRace) homeDirGetRuntimeDir() (string, error) { return "", errors.New("homedirGetRuntimeDir is disabled") } + func (env rootlessRuntimeDirEnvironmentRace) systemLstat(path string) (*system.StatT, error) { if path == env.tmpPerUserDir { st, err := system.Lstat(path) // We can simulate that race directory was created immediately after system.Lstat call. - if err := os.Mkdir(path, 0700); err != nil { + if err := os.Mkdir(path, 0o700); err != nil { return nil, err } return st, err } return system.Lstat(path) } + func (rootlessRuntimeDirEnvironmentRace) homedirGet() string { return homedir.Get() } @@ -244,7 +254,7 @@ func TestRootlessRuntimeDirRace(t *testing.T) { raceDir := t.TempDir() procCommandFile := filepath.Join(raceDir, "command") - err := os.WriteFile(procCommandFile, []byte("init"), 0644) + err := os.WriteFile(procCommandFile, []byte("init"), 0o644) assert.NilError(t, err) tmpPerUserDir := filepath.Join(raceDir, "tmp")