github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/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  // +build dragonfly darwin freebsd !android,linux netbsd openbsd
     6  
     7  package user
     8  
     9  import (
    10  	"fmt"
    11  	"strconv"
    12  	"unsafe"
    13  )
    14  
    15  /*
    16  #include <unistd.h>
    17  #include <sys/types.h>
    18  */
    19  import "C"
    20  
    21  func listGroups(u *User) ([]string, error) {
    22  	ug, err := strconv.Atoi(u.Gid)
    23  	if err != nil {
    24  		return nil, fmt.Errorf("user: list groups for %s: invalid gid %q", u.Username, u.Gid)
    25  	}
    26  	userGID := C.gid_t(ug)
    27  	nameC := make([]byte, len(u.Username)+1)
    28  	copy(nameC, u.Username)
    29  
    30  	n := C.int(256)
    31  	gidsC := make([]C.gid_t, n)
    32  	rv := getGroupList((*C.char)(unsafe.Pointer(&nameC[0])), userGID, &gidsC[0], &n)
    33  	if rv == -1 {
    34  		// More than initial buffer, but now n contains the correct size.
    35  		const maxGroups = 2048
    36  		if n > maxGroups {
    37  			return nil, fmt.Errorf("user: list groups for %s: member of more than %d groups", u.Username, maxGroups)
    38  		}
    39  		gidsC = make([]C.gid_t, n)
    40  		rv := getGroupList((*C.char)(unsafe.Pointer(&nameC[0])), userGID, &gidsC[0], &n)
    41  		if rv == -1 {
    42  			return nil, fmt.Errorf("user: list groups for %s failed (changed groups?)", u.Username)
    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  }