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 72 73 74 75 76 77 78 79 80 81 82 83 84
|
package system
import (
"bytes"
"os"
"golang.org/x/sys/unix"
)
const (
// Value is larger than the maximum size allowed
E2BIG unix.Errno = unix.E2BIG
// Operation not supported
EOPNOTSUPP unix.Errno = unix.EOPNOTSUPP
)
// Lgetxattr retrieves the value of the extended attribute identified by attr
// and associated with the given path in the file system.
// Returns a []byte slice if the xattr is set and nil otherwise.
func Lgetxattr(path string, attr string) ([]byte, error) {
// Start with a 128 length byte array
dest := make([]byte, 128)
sz, errno := unix.Lgetxattr(path, attr, dest)
for errno == unix.ERANGE {
// Buffer too small, use zero-sized buffer to get the actual size
sz, errno = unix.Lgetxattr(path, attr, []byte{})
if errno != nil {
return nil, &os.PathError{Op: "lgetxattr", Path: path, Err: errno}
}
dest = make([]byte, sz)
sz, errno = unix.Lgetxattr(path, attr, dest)
}
switch {
case errno == unix.ENODATA:
return nil, nil
case errno != nil:
return nil, &os.PathError{Op: "lgetxattr", Path: path, Err: errno}
}
return dest[:sz], nil
}
// Lsetxattr sets the value of the extended attribute identified by attr
// and associated with the given path in the file system.
func Lsetxattr(path string, attr string, data []byte, flags int) error {
if err := unix.Lsetxattr(path, attr, data, flags); err != nil {
return &os.PathError{Op: "lsetxattr", Path: path, Err: err}
}
return nil
}
// Llistxattr lists extended attributes associated with the given path
// in the file system.
func Llistxattr(path string) ([]string, error) {
dest := make([]byte, 128)
sz, errno := unix.Llistxattr(path, dest)
for errno == unix.ERANGE {
// Buffer too small, use zero-sized buffer to get the actual size
sz, errno = unix.Llistxattr(path, []byte{})
if errno != nil {
return nil, &os.PathError{Op: "llistxattr", Path: path, Err: errno}
}
dest = make([]byte, sz)
sz, errno = unix.Llistxattr(path, dest)
}
if errno != nil {
return nil, &os.PathError{Op: "llistxattr", Path: path, Err: errno}
}
var attrs []string
for _, token := range bytes.Split(dest[:sz], []byte{0}) {
if len(token) > 0 {
attrs = append(attrs, string(token))
}
}
return attrs, nil
}
|