forked from insomniacslk/u-root
-
Notifications
You must be signed in to change notification settings - Fork 1
/
users.go
83 lines (70 loc) · 1.85 KB
/
users.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
// Copyright 2017-2018 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// Users manages a user database, typically loaded from /etc/passwd
type Users struct {
uidToUser map[int]string
userToUID map[string]int
userToGID map[int]int
}
// GetUID returns the UID of a username
func (u *Users) GetUID(name string) (int, error) {
if v, ok := u.userToUID[name]; ok {
return v, nil
}
return -1, fmt.Errorf("unknown user name: %s", name)
}
// GetGID returns the primary GID of a UID
func (u *Users) GetGID(uid int) (int, error) {
if v, ok := u.userToGID[uid]; ok {
return v, nil
}
return -1, fmt.Errorf("unknown uid: %d", uid)
}
// GetUser returns the username of a UID
func (u *Users) GetUser(uid int) (string, error) {
if v, ok := u.uidToUser[uid]; ok {
return v, nil
}
return "", fmt.Errorf("unkown uid: %d", uid)
}
// NewUsers is a factory for Users. file is the file to read the database from.
func NewUsers(file string) (u *Users, e error) {
u = &Users{}
u.uidToUser = make(map[int]string)
u.userToUID = make(map[string]int)
u.userToGID = make(map[int]int)
passwdFile, err := os.Open(file)
if err != nil {
return u, err
}
// Read from passwdFile for the users name
var passwdInfo []string
passwdScanner := bufio.NewScanner(passwdFile)
for passwdScanner.Scan() {
if passwdScanner.Text()[0] == '#' { // skip comments
continue
}
passwdInfo = strings.Split(passwdScanner.Text(), ":")
userNum, err := strconv.Atoi(passwdInfo[2])
if err != nil {
return nil, err
}
groupNum, err := strconv.Atoi(passwdInfo[3])
if err != nil {
return nil, err
}
u.uidToUser[userNum] = passwdInfo[0]
u.userToUID[passwdInfo[0]] = userNum
u.userToGID[userNum] = groupNum
}
return
}