Files
windows-rdp-keylogger/internal/hiddenlog/hiddenlog_windows.go
T

46 lines
1.5 KiB
Go
Executable File

// Package hiddenlog redirects process output to a log file when the
// process has no attached console — e.g. built with -ldflags -H=windowsgui
// (see build-host.ps1 -Hidden) — so status messages that would normally go
// to a console aren't silently discarded.
package hiddenlog
import (
"log"
"os"
"golang.org/x/sys/windows"
)
var (
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
procGetConsoleWindow = kernel32.NewProc("GetConsoleWindow")
)
// Redirected reports whether EnableIfHeadless actually redirected output.
// Callers can use this to change behavior that depends on having an
// interactive console (e.g. skip a prompt that could never be answered).
var Redirected bool
// EnableIfHeadless checks whether this process has an attached console; if
// not, it redirects stdout, stderr, and the log package's output to
// logPath (created/appended), so a -H=windowsgui build's output still
// lands somewhere. Safe to call on a normal console build — it's a no-op
// there, since a console is already attached.
func EnableIfHeadless(logPath string) {
hwnd, _, _ := procGetConsoleWindow.Call()
if hwnd != 0 {
return // a console is attached; leave stdout/stderr alone
}
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return // nowhere to log the failure to redirect logging; give up quietly
}
os.Stdout = f
os.Stderr = f
log.SetOutput(f)
log.SetFlags(log.LstdFlags)
Redirected = true
}