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.
5 // +build darwin freebsd linux netbsd openbsd
20 #include <sys/types.h>
24 static int mygetpwuid_r(int uid, struct passwd *pwd,
25 char *buf, size_t buflen, struct passwd **result) {
26 return getpwuid_r(uid, pwd, buf, buflen, result);
31 func libc_getpwnam_r(name *byte, pwd *syscall.Passwd, buf *byte, buflen syscall.Size_t, result **syscall.Passwd) int
34 func libc_getpwuid_r(uid syscall.Uid_t, pwd *syscall.Passwd, buf *byte, buflen syscall.Size_t, result **syscall.Passwd) int
36 // bytePtrToString takes a NUL-terminated array of bytes and convert
38 func bytePtrToString(p *byte) string {
39 a := (*[10000]byte)(unsafe.Pointer(p))
47 func current() (*User, error) {
48 return lookupUnix(syscall.Getuid(), "", false)
51 func lookup(username string) (*User, error) {
52 return lookupUnix(-1, username, true)
55 func lookupId(uid string) (*User, error) {
56 i, e := strconv.Atoi(uid)
60 return lookupUnix(i, "", false)
63 func lookupUnix(uid int, username string, lookupByName bool) (*User, error) {
64 var pwd syscall.Passwd
65 var result *syscall.Passwd
67 // FIXME: Should let buf grow if necessary.
69 buf := make([]byte, bufSize)
71 p := syscall.StringBytePtr(username)
72 syscall.Entersyscall()
73 rv := libc_getpwnam_r(p,
80 return nil, fmt.Errorf("user: lookup username %s: %s", username, syscall.GetErrno())
83 return nil, UnknownUserError(username)
86 syscall.Entersyscall()
87 rv := libc_getpwuid_r(syscall.Uid_t(uid),
94 return nil, fmt.Errorf("user: lookup userid %d: %s", uid, syscall.GetErrno())
97 return nil, UnknownUserIdError(uid)
101 Uid: strconv.Itoa(int(pwd.Pw_uid)),
102 Gid: strconv.Itoa(int(pwd.Pw_gid)),
103 Username: bytePtrToString((*byte)(unsafe.Pointer(pwd.Pw_name))),
104 Name: bytePtrToString((*byte)(unsafe.Pointer(pwd.Pw_gecos))),
105 HomeDir: bytePtrToString((*byte)(unsafe.Pointer(pwd.Pw_dir))),
107 // The pw_gecos field isn't quite standardized. Some docs
108 // say: "It is expected to be a comma separated list of
109 // personal data where the first item is the full name of the
111 if i := strings.Index(u.Name, ","); i >= 0 {