File: chown_unix.go

package info (click to toggle)
golang-github-containers-common 0.50.1%2Bds1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,440 kB
  • sloc: makefile: 118; sh: 46
file content (65 lines) | stat: -rw-r--r-- 1,656 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//go:build !windows
// +build !windows

package chown

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"
)

// ChangeHostPathOwnership changes the uid and gid ownership of a directory or file within the host.
// This is used by the volume U flag to change source volumes ownership
func ChangeHostPathOwnership(path string, recursive bool, uid, gid int) error {
	// Validate if host path can be chowned
	isDangerous, err := DangerousHostPath(path)
	if err != nil {
		return fmt.Errorf("failed to validate if host path is dangerous: %w", err)
	}

	if isDangerous {
		return fmt.Errorf("chowning host path %q is not allowed. You can manually `chown -R %d:%d %s`", path, uid, gid, path)
	}

	// Chown host path
	if recursive {
		err := filepath.Walk(path, func(filePath string, f os.FileInfo, err error) error {
			if err != nil {
				return err
			}

			// Get current ownership
			currentUID := int(f.Sys().(*syscall.Stat_t).Uid)
			currentGID := int(f.Sys().(*syscall.Stat_t).Gid)

			if uid != currentUID || gid != currentGID {
				return os.Lchown(filePath, uid, gid)
			}

			return nil
		})
		if err != nil {
			return fmt.Errorf("failed to chown recursively host path: %w", err)
		}
	} else {
		// Get host path info
		f, err := os.Lstat(path)
		if err != nil {
			return fmt.Errorf("failed to get host path information: %w", err)
		}

		// Get current ownership
		currentUID := int(f.Sys().(*syscall.Stat_t).Uid)
		currentGID := int(f.Sys().(*syscall.Stat_t).Gid)

		if uid != currentUID || gid != currentGID {
			if err := os.Lchown(path, uid, gid); err != nil {
				return fmt.Errorf("failed to chown host path: %w", err)
			}
		}
	}

	return nil
}