Skip to content

Commit

Permalink
Merge pull request #7 from golang/master
Browse files Browse the repository at this point in the history
glog: avoid calling user.Current() on windows (golang#69)
  • Loading branch information
hankji authored Jul 17, 2024
2 parents d78d2d2 + 9730314 commit 5641cab
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 4 deletions.
6 changes: 2 additions & 4 deletions glog_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"fmt"
"io"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
Expand Down Expand Up @@ -68,9 +67,8 @@ func init() {
host = shortHostname(h)
}

current, err := user.Current()
if err == nil {
userName = current.Username
if u := lookupUser(); u != "" {
userName = u
}
// Sanitize userName since it is used to construct file paths.
userName = strings.Map(func(r rune) rune {
Expand Down
12 changes: 12 additions & 0 deletions glog_file_nonwindows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build !windows

package glog

import "os/user"

func lookupUser() string {
if current, err := user.Current(); err == nil {
return current.Username
}
return ""
}
30 changes: 30 additions & 0 deletions glog_file_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//go:build windows

package glog

import (
"syscall"
)

// This follows the logic in the standard library's user.Current() function, except
// that it leaves out the potentially expensive calls required to look up the user's
// display name in Active Directory.
func lookupUser() string {
token, err := syscall.OpenCurrentProcessToken()
if err != nil {
return ""
}
defer token.Close()
tokenUser, err := token.GetTokenUser()
if err != nil {
return ""
}
username, _, accountType, err := tokenUser.User.Sid.LookupAccount("")
if err != nil {
return ""
}
if accountType != syscall.SidTypeUser {
return ""
}
return username
}

0 comments on commit 5641cab

Please sign in to comment.