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