...

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	// +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	
    30		homeDir, _ := os.UserHomeDir()
    31		u = &User{
    32			Uid:      uid,
    33			Gid:      currentGID(),
    34			Username: os.Getenv("USER"),
    35			Name:     "", // ignored
    36			HomeDir:  homeDir,
    37		}
    38		// On NaCL and Android, return a dummy user instead of failing.
    39		switch runtime.GOOS {
    40		case "nacl":
    41			if u.Uid == "" {
    42				u.Uid = "1"
    43			}
    44			if u.Username == "" {
    45				u.Username = "nacl"
    46			}
    47		case "android":
    48			if u.Uid == "" {
    49				u.Uid = "1"
    50			}
    51			if u.Username == "" {
    52				u.Username = "android"
    53			}
    54		}
    55		// cgo isn't available, but if we found the minimum information
    56		// without it, use it:
    57		if u.Uid != "" && u.Username != "" && u.HomeDir != "" {
    58			return u, nil
    59		}
    60		var missing string
    61		if u.Username == "" {
    62			missing = "$USER"
    63		}
    64		if u.HomeDir == "" {
    65			if missing != "" {
    66				missing += ", "
    67			}
    68			missing += "$HOME"
    69		}
    70		return u, fmt.Errorf("user: Current requires cgo or %s set in environment", missing)
    71	}
    72	
    73	func listGroups(*User) ([]string, error) {
    74		if runtime.GOOS == "android" || runtime.GOOS == "aix" {
    75			return nil, errors.New(fmt.Sprintf("user: GroupIds not implemented on %s", runtime.GOOS))
    76		}
    77		return nil, errors.New("user: GroupIds requires cgo")
    78	}
    79	
    80	func currentUID() string {
    81		if id := os.Getuid(); id >= 0 {
    82			return strconv.Itoa(id)
    83		}
    84		// Note: Windows returns -1, but this file isn't used on
    85		// Windows anyway, so this empty return path shouldn't be
    86		// used.
    87		return ""
    88	}
    89	
    90	func currentGID() string {
    91		if id := os.Getgid(); id >= 0 {
    92			return strconv.Itoa(id)
    93		}
    94		return ""
    95	}
    96	

View as plain text