Debian Codegraph @

libgo/go/os/user/cgo_listgroups_unix.go

raw
1 // Copyright 2016 The Go 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 //go:build (dragonfly || darwin || freebsd || hurd || (!android && linux) || netbsd || openbsd || (solaris && !illumos)) && cgo && !osusergo
6
7 package user
8
9 import (
10 "fmt"
11 "strconv"
12 "syscall"
13 "unsafe"
14 )
15
16 const maxGroups = 2048
17
18 func listGroups(u *User) ([]string, error) {
19 ug, err := strconv.Atoi(u.Gid)
20 if err != nil {
21 return nil, fmt.Errorf("user: list groups for %s: invalid gid %q", u.Username, u.Gid)
22 }
23 userGID := syscall.Gid_t(ug)
24 nameC := make([]byte, len(u.Username)+1)
25 copy(nameC, u.Username)
26
27 n := int32(256)
28 gidsC := make([]syscall.Gid_t, n)
29 rv := getGroupList((*byte)(unsafe.Pointer(&nameC[0])), userGID, &gidsC[0], &n)
30 if rv == -1 {
31 // Mac is the only Unix that does not set n properly when rv == -1, so
32 // we need to use different logic for Mac vs. the other OS's.
33 if err := groupRetry(u.Username, nameC, userGID, &gidsC, &n); err != nil {
34 return nil, err
35 }
36 }
37 gidsC = gidsC[:n]
38 gids := make([]string, 0, n)
39 for _, g := range gidsC[:n] {
40 gids = append(gids, strconv.Itoa(int(g)))
41 }
42 return gids, nil
43 }