diff options
Diffstat (limited to 'internal/users.go')
-rw-r--r-- | internal/users.go | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/internal/users.go b/internal/users.go new file mode 100644 index 0000000..e7a25a3 --- /dev/null +++ b/internal/users.go @@ -0,0 +1,53 @@ +package internal + +import ( + "bufio" + "errors" + "io" + "os" + "path/filepath" + "strings" +) + +// ListUsersWithHomeSubdir provides a list of user names on the current host. +// +// The users returned will only be those with a specifically named subdirectory +// of their home dir, which has the given permission bits. +func ListUsersWithHomeSubdir(subdir string, required_perms os.FileMode) ([]string, error) { + file, err := os.Open("/etc/passwd") + if err != nil { + return nil, err + } + defer func() { + _ = file.Close() + }() + + users := []string{} + rdr := bufio.NewReader(file) + for { + line, err := rdr.ReadString('\n') + isEOF := errors.Is(err, io.EOF) + if err != nil && !isEOF { + return nil, err + } + + if len(line) != 0 && line[0] == '#' { + continue + } + + spl := strings.Split(line, ":") + home := spl[len(spl)-2] + st, err := os.Stat(filepath.Join(home, subdir)) + if err != nil || !st.IsDir() || st.Mode()&required_perms != required_perms { + continue + } + + users = append(users, spl[0]) + + if isEOF { + break + } + } + + return users, nil +} |