github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/go/src/os/user/listgroups_unix.go (about) 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 || (!android && linux) || netbsd || openbsd || (solaris && !illumos)) && cgo && !osusergo 6 // +build dragonfly darwin freebsd !android,linux netbsd openbsd solaris,!illumos 7 // +build cgo 8 // +build !osusergo 9 10 package user 11 12 import ( 13 "fmt" 14 "strconv" 15 "unsafe" 16 ) 17 18 /* 19 #include <unistd.h> 20 #include <sys/types.h> 21 */ 22 import "C" 23 24 const maxGroups = 2048 25 26 func listGroups(u *User) ([]string, error) { 27 ug, err := strconv.Atoi(u.Gid) 28 if err != nil { 29 return nil, fmt.Errorf("user: list groups for %s: invalid gid %q", u.Username, u.Gid) 30 } 31 userGID := C.gid_t(ug) 32 nameC := make([]byte, len(u.Username)+1) 33 copy(nameC, u.Username) 34 35 n := C.int(256) 36 gidsC := make([]C.gid_t, n) 37 rv := getGroupList((*C.char)(unsafe.Pointer(&nameC[0])), userGID, &gidsC[0], &n) 38 if rv == -1 { 39 // Mac is the only Unix that does not set n properly when rv == -1, so 40 // we need to use different logic for Mac vs. the other OS's. 41 if err := groupRetry(u.Username, nameC, userGID, &gidsC, &n); err != nil { 42 return nil, err 43 } 44 } 45 gidsC = gidsC[:n] 46 gids := make([]string, 0, n) 47 for _, g := range gidsC[:n] { 48 gids = append(gids, strconv.Itoa(int(g))) 49 } 50 return gids, nil 51 }