| |
| |
| |
|
|
| |
|
|
| package user |
|
|
| import ( |
| "bufio" |
| "bytes" |
| "errors" |
| "fmt" |
| "io" |
| "os" |
| "strconv" |
| ) |
|
|
| func listGroupsFromReader(u *User, r io.Reader) ([]string, error) { |
| if u.Username == "" { |
| return nil, errors.New("user: list groups: empty username") |
| } |
| primaryGid, err := strconv.Atoi(u.Gid) |
| if err != nil { |
| return nil, fmt.Errorf("user: list groups for %s: invalid gid %q", u.Username, u.Gid) |
| } |
|
|
| userCommas := []byte("," + u.Username + ",") |
| userFirst := userCommas[1:] |
| userLast := userCommas[:len(userCommas)-1] |
| userOnly := userCommas[1 : len(userCommas)-1] |
|
|
| |
| groups := []string{u.Gid} |
|
|
| rd := bufio.NewReader(r) |
| done := false |
| for !done { |
| line, err := rd.ReadBytes('\n') |
| if err != nil { |
| if err == io.EOF { |
| done = true |
| } else { |
| return groups, err |
| } |
| } |
|
|
| |
| |
|
|
| |
| |
| |
| line = bytes.TrimSpace(line) |
| if len(line) == 0 || line[0] == '#' || |
| |
| |
| |
| line[0] == '+' || line[0] == '-' { |
| continue |
| } |
|
|
| |
| |
| |
| |
| |
| listIdx := bytes.LastIndexByte(line, ':') |
| if listIdx == -1 || listIdx == len(line)-1 { |
| |
| continue |
| } |
| if bytes.Count(line[:listIdx], colon) != 2 { |
| |
| continue |
| } |
| list := line[listIdx+1:] |
| |
| if !(bytes.Equal(list, userOnly) || bytes.HasPrefix(list, userFirst) || bytes.HasSuffix(list, userLast) || bytes.Contains(list, userCommas)) { |
| continue |
| } |
|
|
| |
| parts := bytes.Split(line[:listIdx], colon) |
| if len(parts) != 3 || len(parts[0]) == 0 { |
| continue |
| } |
| gid := string(parts[2]) |
| |
| numGid, err := strconv.Atoi(gid) |
| if err != nil || numGid == primaryGid { |
| continue |
| } |
|
|
| groups = append(groups, gid) |
| } |
|
|
| return groups, nil |
| } |
|
|
| func listGroups(u *User) ([]string, error) { |
| f, err := os.Open(groupFile) |
| if err != nil { |
| return nil, err |
| } |
| defer f.Close() |
|
|
| return listGroupsFromReader(u, f) |
| } |
|
|