github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/os/user/lookup_stubs.go (about)

     1  // Copyright 2011 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 !cgo,!windows,!plan9 android osusergo,!windows,!plan9
     6  
     7  package user
     8  
     9  import (
    10  	"errors"
    11  	"fmt"
    12  	"os"
    13  	"runtime"
    14  	"strconv"
    15  )
    16  
    17  func init() {
    18  	groupImplemented = false
    19  }
    20  
    21  func current() (*User, error) {
    22  	uid := currentUID()
    23  	// $USER and /etc/passwd may disagree; prefer the latter if we can get it.
    24  	// See issue 27524 for more information.
    25  	u, err := lookupUserId(uid)
    26  	if err == nil {
    27  		return u, nil
    28  	}
    29  	u = &User{
    30  		Uid:      uid,
    31  		Gid:      currentGID(),
    32  		Username: os.Getenv("USER"),
    33  		Name:     "", // ignored
    34  		HomeDir:  os.Getenv("HOME"),
    35  	}
    36  	// On NaCL and Android, return a dummy user instead of failing.
    37  	switch runtime.GOOS {
    38  	case "nacl":
    39  		if u.Uid == "" {
    40  			u.Uid = "1"
    41  		}
    42  		if u.Username == "" {
    43  			u.Username = "nacl"
    44  		}
    45  		if u.HomeDir == "" {
    46  			u.HomeDir = "/"
    47  		}
    48  	case "android":
    49  		if u.Uid == "" {
    50  			u.Uid = "1"
    51  		}
    52  		if u.Username == "" {
    53  			u.Username = "android"
    54  		}
    55  		if u.HomeDir == "" {
    56  			u.HomeDir = "/sdcard"
    57  		}
    58  	}
    59  	// cgo isn't available, but if we found the minimum information
    60  	// without it, use it:
    61  	if u.Uid != "" && u.Username != "" && u.HomeDir != "" {
    62  		return u, nil
    63  	}
    64  	return u, fmt.Errorf("user: Current not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
    65  }
    66  
    67  func listGroups(*User) ([]string, error) {
    68  	if runtime.GOOS == "android" || runtime.GOOS == "aix" {
    69  		return nil, errors.New(fmt.Sprintf("user: GroupIds not implemented on %s", runtime.GOOS))
    70  	}
    71  	return nil, errors.New("user: GroupIds requires cgo")
    72  }
    73  
    74  func currentUID() string {
    75  	if id := os.Getuid(); id >= 0 {
    76  		return strconv.Itoa(id)
    77  	}
    78  	// Note: Windows returns -1, but this file isn't used on
    79  	// Windows anyway, so this empty return path shouldn't be
    80  	// used.
    81  	return ""
    82  }
    83  
    84  func currentGID() string {
    85  	if id := os.Getgid(); id >= 0 {
    86  		return strconv.Itoa(id)
    87  	}
    88  	return ""
    89  }