gitlab.com/apertussolutions/u-root@v7.0.0+incompatible/cmds/core/id/users.go (about) 1 // Copyright 2017-2018 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build !plan9 6 7 package main 8 9 import ( 10 "bufio" 11 "fmt" 12 "os" 13 "strconv" 14 "strings" 15 ) 16 17 // Users manages a user database, typically loaded from /etc/passwd 18 type Users struct { 19 uidToUser map[int]string 20 userToUID map[string]int 21 userToGID map[int]int 22 } 23 24 // GetUID returns the UID of a username 25 func (u *Users) GetUID(name string) (int, error) { 26 if v, ok := u.userToUID[name]; ok { 27 return v, nil 28 } 29 return -1, fmt.Errorf("unknown user name: %s", name) 30 } 31 32 // GetGID returns the primary GID of a UID 33 func (u *Users) GetGID(uid int) (int, error) { 34 if v, ok := u.userToGID[uid]; ok { 35 return v, nil 36 } 37 return -1, fmt.Errorf("unknown uid: %d", uid) 38 } 39 40 // GetUser returns the username of a UID 41 func (u *Users) GetUser(uid int) (string, error) { 42 if v, ok := u.uidToUser[uid]; ok { 43 return v, nil 44 } 45 return "", fmt.Errorf("unkown uid: %d", uid) 46 } 47 48 // NewUsers is a factory for Users. file is the file to read the database from. 49 func NewUsers(file string) (u *Users, e error) { 50 u = &Users{} 51 u.uidToUser = make(map[int]string) 52 u.userToUID = make(map[string]int) 53 u.userToGID = make(map[int]int) 54 55 passwdFile, err := os.Open(file) 56 if err != nil { 57 return u, err 58 } 59 60 // Read from passwdFile for the users name 61 var passwdInfo []string 62 63 passwdScanner := bufio.NewScanner(passwdFile) 64 65 for passwdScanner.Scan() { 66 txt := passwdScanner.Text() 67 if len(txt) == 0 || txt[0] == '#' { // skip empty lines and comments 68 continue 69 } 70 passwdInfo = strings.Split(txt, ":") 71 userNum, err := strconv.Atoi(passwdInfo[2]) 72 if err != nil { 73 return nil, err 74 } 75 groupNum, err := strconv.Atoi(passwdInfo[3]) 76 if err != nil { 77 return nil, err 78 } 79 80 u.uidToUser[userNum] = passwdInfo[0] 81 u.userToUID[passwdInfo[0]] = userNum 82 u.userToGID[userNum] = groupNum 83 } 84 85 return 86 }