...
Run Format

Source file src/os/user/listgroups_unix.go

Documentation: os/user

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

View as plain text