Source file src/os/user/lookup_stubs.go

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

View as plain text