summaryrefslogtreecommitdiffstats
path: root/go-selinux/xattrs_linux.go
blob: 9e473ca168f1196e5ddb1fcd5f56af42a95edbf1 (plain)
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
66
67
68
69
70
71
package selinux

import (
	"golang.org/x/sys/unix"
)

// lgetxattr returns a []byte slice containing the value of
// an extended attribute attr set for path.
func lgetxattr(path, attr string) ([]byte, error) {
	// Start with a 128 length byte array
	dest := make([]byte, 128)
	sz, errno := doLgetxattr(path, attr, dest)
	for errno == unix.ERANGE { //nolint:errorlint // unix errors are bare
		// Buffer too small, use zero-sized buffer to get the actual size
		sz, errno = doLgetxattr(path, attr, []byte{})
		if errno != nil {
			return nil, errno
		}

		dest = make([]byte, sz)
		sz, errno = doLgetxattr(path, attr, dest)
	}
	if errno != nil {
		return nil, errno
	}

	return dest[:sz], nil
}

// doLgetxattr is a wrapper that retries on EINTR
func doLgetxattr(path, attr string, dest []byte) (int, error) {
	for {
		sz, err := unix.Lgetxattr(path, attr, dest)
		if err != unix.EINTR { //nolint:errorlint // unix errors are bare
			return sz, err
		}
	}
}

// getxattr returns a []byte slice containing the value of
// an extended attribute attr set for path.
func getxattr(path, attr string) ([]byte, error) {
	// Start with a 128 length byte array
	dest := make([]byte, 128)
	sz, errno := dogetxattr(path, attr, dest)
	for errno == unix.ERANGE { //nolint:errorlint // unix errors are bare
		// Buffer too small, use zero-sized buffer to get the actual size
		sz, errno = dogetxattr(path, attr, []byte{})
		if errno != nil {
			return nil, errno
		}

		dest = make([]byte, sz)
		sz, errno = dogetxattr(path, attr, dest)
	}
	if errno != nil {
		return nil, errno
	}

	return dest[:sz], nil
}

// dogetxattr is a wrapper that retries on EINTR
func dogetxattr(path, attr string, dest []byte) (int, error) {
	for {
		sz, err := unix.Getxattr(path, attr, dest)
		if err != unix.EINTR { //nolint:errorlint // unix errors are bare
			return sz, err
		}
	}
}