Files

295 lines
8.2 KiB
Go
Raw Permalink Normal View History

package main
import (
"bytes"
"fmt"
"image"
"image/png"
"log"
"net"
"time"
"lanrdp/internal/capture"
"lanrdp/internal/input"
"lanrdp/internal/keylog"
"lanrdp/internal/netguard"
"lanrdp/internal/protocol"
)
func handleSession(conn net.Conn, cfg *config, throttle *netguard.LoginThrottle, normalFPS, streamFPS int, keyframeInterval time.Duration, keylogCh <-chan keylog.KeyEvent) {
defer conn.Close()
remoteIP, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
if !throttle.Allowed(remoteIP) {
log.Printf("%s: rejected, locked out after repeated failed attempts", remoteIP)
return
}
_ = conn.SetReadDeadline(time.Now().Add(15 * time.Second))
t, payload, err := protocol.ReadMessage(conn)
if err != nil || t != protocol.MsgHello {
log.Printf("%s: expected Hello (err=%v type=%v)", remoteIP, err, t)
return
}
hello, err := protocol.DecodeHello(payload)
if err != nil || hello.Version != protocol.ProtocolVersion {
log.Printf("%s: incompatible protocol version", remoteIP)
return
}
t, payload, err = protocol.ReadMessage(conn)
if err != nil || t != protocol.MsgAuthRequest {
log.Printf("%s: expected AuthRequest (err=%v type=%v)", remoteIP, err, t)
return
}
authReq, err := protocol.DecodeAuthRequest(payload)
if err != nil {
log.Printf("%s: bad AuthRequest: %v", remoteIP, err)
return
}
if !protocol.VerifyPassword(authReq.Password, cfg.PasswordHash) {
throttle.RecordFailure(remoteIP)
log.Printf("%s: authentication failed", remoteIP)
_ = protocol.WriteMessage(conn, protocol.MsgAuthResponse, protocol.EncodeAuthResponse(protocol.AuthResponse{
OK: false, FailureReason: "invalid passphrase",
}))
return
}
throttle.RecordSuccess(remoteIP)
width, height := capture.ScreenSize()
if err := protocol.WriteMessage(conn, protocol.MsgAuthResponse, protocol.EncodeAuthResponse(protocol.AuthResponse{
OK: true, ScreenWidth: uint16(width), ScreenHeight: uint16(height),
})); err != nil {
return
}
log.Printf("%s: authenticated, session starting (%dx%d)", remoteIP, width, height)
_ = conn.SetReadDeadline(time.Time{})
// perfCh carries a new target fps from inputLoop (on a MsgSetPerfMode
// from the client) into captureLoop, so the client's Ctrl+Alt+S hotkey
// can change capture cadence mid-session without a reconnect.
perfCh := make(chan int, 1)
errCh := make(chan error, 2)
go captureLoop(conn, errCh, normalFPS, keyframeInterval, perfCh)
go inputLoop(conn, errCh, perfCh, normalFPS, streamFPS)
// If keylogging is enabled, forward captured keystrokes to the client.
if keylogCh != nil {
go func() {
for event := range keylogCh {
eventBytes := protocol.EncodeKeyLogEvent(protocol.KeyLogEvent{
TimestampMs: event.TimestampMs,
VKCode: event.VKCode,
ScanCode: event.ScanCode,
Flags: event.Flags,
WindowTitle: event.WindowTitle,
})
if err := protocol.WriteMessage(conn, protocol.MsgKeyLogEvent, eventBytes); err != nil {
log.Printf("%s: failed to send keylog event: %v", remoteIP, err)
return
}
}
}()
}
err = <-errCh
log.Printf("%s: session ended: %v", remoteIP, err)
}
func captureLoop(conn net.Conn, errCh chan<- error, initialFPS int, keyframeInterval time.Duration, perfCh <-chan int) {
currentFPS := initialFPS
ticker := time.NewTicker(time.Second / time.Duration(currentFPS))
defer ticker.Stop()
var prev *image.RGBA
var prevW, prevH int
var lastKeyframe time.Time
for {
select {
case newFPS := <-perfCh:
if newFPS > 0 && newFPS != currentFPS {
currentFPS = newFPS
ticker.Reset(time.Second / time.Duration(currentFPS))
}
continue
case <-ticker.C:
}
img, err := capture.CaptureScreen()
if err != nil {
errCh <- fmt.Errorf("capture: %w", err)
return
}
bounds := img.Bounds()
if bounds.Dx() != prevW || bounds.Dy() != prevH {
prevW, prevH = bounds.Dx(), bounds.Dy()
if err := protocol.WriteMessage(conn, protocol.MsgResize, protocol.EncodeResize(protocol.Resize{
Width: uint16(prevW), Height: uint16(prevH),
})); err != nil {
errCh <- err
return
}
prev = nil
}
needKeyframe := prev == nil || time.Since(lastKeyframe) > keyframeInterval
if needKeyframe {
if err := sendFrame(conn, protocol.MsgFrameFull, img.Bounds(), img); err != nil {
errCh <- err
return
}
lastKeyframe = time.Now()
prev = img
continue
}
if rect, changed := capture.DirtyRect(prev, img); changed {
sub := img.SubImage(rect).(*image.RGBA)
if err := sendFrame(conn, protocol.MsgFrameDelta, rect, sub); err != nil {
errCh <- err
return
}
}
prev = img
}
}
func sendFrame(conn net.Conn, t protocol.MsgType, rect image.Rectangle, img image.Image) error {
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
return err
}
return protocol.WriteMessage(conn, t, protocol.EncodeFrameUpdate(protocol.FrameUpdate{
X: uint16(rect.Min.X),
Y: uint16(rect.Min.Y),
W: uint16(rect.Dx()),
H: uint16(rect.Dy()),
PNG: buf.Bytes(),
}))
}
func inputLoop(conn net.Conn, errCh chan<- error, perfCh chan<- int, normalFPS, streamFPS int) {
currentMode := protocol.PerfNormal
var xfer *fileTransferState
for {
t, payload, err := protocol.ReadMessage(conn)
if err != nil {
if xfer != nil {
xfer.abort()
}
errCh <- err
return
}
switch t {
case protocol.MsgInputMouse:
m, err := protocol.DecodeInputMouse(payload)
if err == nil {
applyMouse(m)
}
case protocol.MsgInputKey:
k, err := protocol.DecodeInputKey(payload)
if err == nil {
_ = input.KeyEvent(k.VKCode, k.Down)
}
case protocol.MsgSetPerfMode:
mode, err := protocol.DecodeSetPerfMode(payload)
if err == nil {
currentMode = mode
fps := normalFPS
if mode == protocol.PerfStream {
fps = streamFPS
}
select {
case perfCh <- fps:
default: // a change is already pending; the next toggle will retry
}
}
case protocol.MsgFileOffer:
if xfer != nil {
xfer.abort()
xfer = nil
}
if currentMode == protocol.PerfStream {
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
OK: false, Message: "file transfer is disabled while in stream mode",
}))
continue
}
offer, err := protocol.DecodeFileOffer(payload)
if err != nil {
continue
}
xfer, err = startFileTransfer(offer)
if err != nil {
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
OK: false, Message: err.Error(),
}))
xfer = nil
}
case protocol.MsgFileChunk:
if xfer == nil {
continue // stray chunk with no active transfer (e.g. after a rejected offer); ignore
}
if err := xfer.writeChunk(payload); err != nil {
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
OK: false, Message: err.Error(),
}))
xfer.abort()
xfer = nil
}
case protocol.MsgFileComplete:
if xfer == nil {
continue
}
fc, err := protocol.DecodeFileComplete(payload)
if err != nil {
xfer.abort()
xfer = nil
continue
}
ok, msg := xfer.finish(fc.Size)
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{OK: ok, Message: msg}))
xfer = nil
case protocol.MsgPing:
_ = protocol.WriteMessage(conn, protocol.MsgPong, nil)
case protocol.MsgDisconnect:
if xfer != nil {
xfer.abort()
}
errCh <- fmt.Errorf("client disconnected")
return
}
}
}
func applyMouse(m protocol.InputMouse) {
switch m.Action {
case protocol.MouseMove:
_ = input.MouseMove(m.NormX, m.NormY)
case protocol.MouseLeftDown:
_ = input.MouseMove(m.NormX, m.NormY)
_ = input.MouseButtonEvent(input.ButtonLeft, true)
case protocol.MouseLeftUp:
_ = input.MouseButtonEvent(input.ButtonLeft, false)
case protocol.MouseRightDown:
_ = input.MouseMove(m.NormX, m.NormY)
_ = input.MouseButtonEvent(input.ButtonRight, true)
case protocol.MouseRightUp:
_ = input.MouseButtonEvent(input.ButtonRight, false)
case protocol.MouseMiddleDown:
_ = input.MouseMove(m.NormX, m.NormY)
_ = input.MouseButtonEvent(input.ButtonMiddle, true)
case protocol.MouseMiddleUp:
_ = input.MouseButtonEvent(input.ButtonMiddle, false)
case protocol.MouseWheel:
_ = input.MouseWheel(m.WheelDelta)
}
}