github.com/apptainer/singularity@v3.1.1+incompatible/internal/pkg/util/user/identity.go (about)

     1  /*
     2    Copyright (c) 2018, Sylabs, Inc. All rights reserved.
     3  
     4    This software is licensed under a 3-clause BSD license.  Please
     5    consult LICENSE.md file distributed with the sources of this project regarding
     6    your rights to use or distribute this software.
     7  */
     8  
     9  package user
    10  
    11  import "strconv"
    12  import osuser "os/user"
    13  
    14  // User represents an Unix user account information
    15  type User struct {
    16  	Name  string
    17  	UID   uint32
    18  	GID   uint32
    19  	Gecos string
    20  	Dir   string
    21  	Shell string
    22  }
    23  
    24  // Group represents an Unix group information
    25  type Group struct {
    26  	Name string
    27  	GID  uint32
    28  }
    29  
    30  func convertUser(user *osuser.User) (*User, error) {
    31  	uid, err := strconv.ParseUint(user.Uid, 10, 32)
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  	gid, err := strconv.ParseUint(user.Gid, 10, 32)
    36  	if err != nil {
    37  		return nil, err
    38  	}
    39  	u := &User{
    40  		Name:  user.Username,
    41  		UID:   uint32(uid),
    42  		GID:   uint32(gid),
    43  		Dir:   user.HomeDir,
    44  		Gecos: user.Name,
    45  		Shell: "/bin/sh",
    46  	}
    47  	return u, nil
    48  }
    49  
    50  func convertGroup(group *osuser.Group) (*Group, error) {
    51  	gid, err := strconv.ParseUint(group.Gid, 10, 32)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	return &Group{Name: group.Name, GID: uint32(gid)}, nil
    56  }
    57  
    58  // GetPwUID returns a pointer to User structure associated with user uid
    59  func GetPwUID(uid uint32) (*User, error) {
    60  	u, err := osuser.LookupId(strconv.FormatUint(uint64(uid), 10))
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  	return convertUser(u)
    65  }
    66  
    67  // GetPwNam returns a pointer to User structure associated with user name
    68  func GetPwNam(name string) (*User, error) {
    69  	u, err := osuser.Lookup(name)
    70  	if err != nil {
    71  		return nil, err
    72  	}
    73  	return convertUser(u)
    74  }
    75  
    76  // GetGrGID returns a pointer to Group structure associated with groud gid
    77  func GetGrGID(gid uint32) (*Group, error) {
    78  	g, err := osuser.LookupGroupId(strconv.FormatUint(uint64(gid), 10))
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  	return convertGroup(g)
    83  }
    84  
    85  // GetGrNam returns a pointer to Group structure associated with group name
    86  func GetGrNam(name string) (*Group, error) {
    87  	g, err := osuser.LookupGroup(name)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	return convertGroup(g)
    92  }