This repository has been archived by the owner on Dec 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lookup.go
122 lines (100 loc) · 2.09 KB
/
lookup.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package passwduser
import (
"bufio"
"io"
"os"
"os/user"
"strconv"
"strings"
)
var passwdFilePath = "/etc/passwd"
// Current finds and returns the current user.
func Current() (*User, error) {
uid := strconv.Itoa(os.Getuid())
return LookupID(uid)
}
// Lookup finds a user by her username.
func Lookup(username string) (*User, error) {
passwdFile, err := os.Open(passwdFilePath)
if err != nil {
return nil, err
}
defer func() {
_ = passwdFile.Close()
}()
users, err := parsePasswdFilter(passwdFile, func(u User) bool {
return u.Username == username
})
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, user.UnknownUserError(username)
}
return &users[0], nil
}
// LookupID finds a user by her UID.
func LookupID(uid string) (*User, error) {
uidInt, err := strconv.ParseInt(uid, 10, 32)
if err != nil {
return nil, err
}
passwdFile, err := os.Open(passwdFilePath)
if err != nil {
return nil, err
}
defer func() {
_ = passwdFile.Close()
}()
users, err := parsePasswdFilter(passwdFile, func(u User) bool {
return u.UID == uid
})
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, user.UnknownUserIdError(uidInt)
}
return &users[0], nil
}
// `(*User) GroupIds() ([]string, error)`
// `LookupGroup(name string) (*Group, error)`
// `LookupGroupId(gid string) (*Group, error)`
func parseLine(line string) User {
user := User{}
// see: man 5 passwd
// name:password:UID:GID:GECOS:directory:shell
parts := strings.Split(line, ":")
if len(parts) >= 1 {
user.Username = parts[0]
user.Name = parts[0]
}
if len(parts) >= 3 {
user.UID = parts[2]
}
if len(parts) >= 4 {
user.GID = parts[3]
}
if len(parts) >= 6 {
user.HomeDir = parts[5]
}
return user
}
func parsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) {
out := []User{}
s := bufio.NewScanner(r)
for s.Scan() {
if err := s.Err(); err != nil {
return nil, err
}
line := strings.TrimSpace(s.Text())
if line == "" {
continue
}
p := parseLine(line)
if filter == nil || filter(p) {
out = append(out, p)
}
}
return out, nil
}