mirror of
https://github.com/Devolutions/IronRDP.git
synced 2026-11-23 00:14:10 +00:00
4982320bff
`Framed.ReadPdu` copied the whole buffer into a new array on every `FindSize` call. An active-stage PDU announces its length in its first bytes (four for TPKT, at most three for fast-path), so `Framed` now probes only the first four buffered bytes into a reusable array; `ReadByHint` keeps the full copy because connection-time PDUs are few and small. New members, alongside the existing ones: - `ReadPdu(CancellationToken)`, and `CancellationToken` overloads of `ReadExact` and both `ReadByHint`. - `TryReadBufferedPdu(out (Action, byte[]))`: takes the next PDU when it is already buffered, without reading the stream, so a consumer can flush rendering only when nothing more is pending. - `ReadPduSync()`: a blocking read for a dedicated read thread. A cancelled read stops waiting but leaves the stream read in flight; the next read, asynchronous or synchronous, finishes it first, so bytes are neither lost nor read twice. Every read reports a stream that ends before the PDU is complete as `IronRdpLibException(EndOfFile)`, where `ReadExact` and `ReadByHint` threw a plain `Exception`. `Connection.Connect`, `RDCleanPathConnection.ConnectRDCleanPath`/`ConnectVmConnectRDCleanPath` and `Connection.SingleSequenceStep` take an optional `CancellationToken` and pass it to the hint reads, the TCP connect and the TLS handshake. Consumers: - The Avalonia example cancels the connection sequence and the read loop through one token on window close or session end, and uses `TryReadBufferedPdu` to present the bitmap only once no further PDU is buffered, so a burst of updates draws once. - `ConnectExample` uses the cancellable read with a timeout instead of `Task.WhenAny`, which left a read pending. - Devolutions/IronSessions `RdpSession` uses `TryReadBufferedPdu` to flush rendering only when the socket is quiet, `ReadPdu(CancellationToken)` for disconnect and timeout, the cancellable `ReadByHint` during the connection sequence, and `ReadPduSync` for a dedicated read thread on Mono (Android/iOS), where awaiting every read hopped pool threads. `ReadPduSync` has no consumer in this repository on purpose: the examples are async end to end. `ffi/INTENT.md` records the probe width, the `ReadByHint` split, the EOF policy and the read regime. Smoke tests cover header-only sizing for TPKT and both fast-path length encodings, several PDUs in one read, a partial PDU left buffered, the sync read across split reads, EOF inside a PDU body on every read path, and a cancelled read whose in-flight stream read the next read finishes.
190 lines
6.9 KiB
C#
190 lines
6.9 KiB
C#
using SixLabors.ImageSharp;
|
||
using SixLabors.ImageSharp.PixelFormats;
|
||
|
||
namespace Devolutions.IronRdp.ConnectExample
|
||
{
|
||
class Program
|
||
{
|
||
static async Task Main(string[] args)
|
||
{
|
||
Log.InitWithEnv();
|
||
|
||
var arguments = ParseArguments(args);
|
||
|
||
if (arguments == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
var serverName = arguments["--serverName"];
|
||
var username = arguments["--username"];
|
||
var password = arguments["--password"];
|
||
var domain = arguments["--domain"];
|
||
|
||
try
|
||
{
|
||
var (res, framed) = await Connection.Connect(buildConfig(username, password, domain, 1980, 1080), serverName, null);
|
||
var decodedImage = DecodedImage.New(PixelFormat.RgbA32, res.DesktopSize.Width, res.DesktopSize.Height);
|
||
var activeState = ActiveStage.New(res);
|
||
var keepLooping = true;
|
||
while (keepLooping)
|
||
{
|
||
Action action;
|
||
byte[] payload;
|
||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
||
try
|
||
{
|
||
(action, payload) = await framed.ReadPdu(timeout.Token);
|
||
}
|
||
catch (OperationCanceledException)
|
||
{
|
||
Console.WriteLine("Timeout");
|
||
break;
|
||
}
|
||
Console.WriteLine($"Action: {action}");
|
||
var outputIterator = activeState.Process(decodedImage, action, payload);
|
||
|
||
while (!outputIterator.IsEmpty())
|
||
{
|
||
using var output = outputIterator.Next()!; // outputIterator.Next() is not null since outputIterator.IsEmpty() is false
|
||
Console.WriteLine($"Output type: {output.GetType()}");
|
||
if (output.EnumType == ActiveStageOutputType.Terminate)
|
||
{
|
||
Console.WriteLine("Connection terminated.");
|
||
keepLooping = false;
|
||
}
|
||
|
||
if (output.EnumType == ActiveStageOutputType.ResponseFrame)
|
||
{
|
||
using var responseFrame = output.ResponseFrame!;
|
||
byte[] responseFrameBytes = new byte[responseFrame.Size];
|
||
responseFrame.Fill(responseFrameBytes);
|
||
await framed.Write(responseFrameBytes);
|
||
}
|
||
}
|
||
}
|
||
|
||
saveImage(decodedImage, "output.png");
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
Console.WriteLine($"An error occurred: {e.Message}\n\nStackTrace:\n{e.StackTrace}");
|
||
}
|
||
}
|
||
|
||
private static void saveImage(DecodedImage decodedImage, string v)
|
||
{
|
||
int width = decodedImage.Width;
|
||
int height = decodedImage.Height;
|
||
var bytes = new byte[decodedImage.DataSize];
|
||
decodedImage.FillData(bytes);
|
||
|
||
using Image<Rgba32> image = new Image<Rgba32>(width, height);
|
||
|
||
// We’ll mutate this struct instead of creating a new one for performance reasons.
|
||
Rgba32 color = new Rgba32(0, 0, 0);
|
||
|
||
for (int col = 0; col < width; ++col)
|
||
{
|
||
for (int row = 0; row < height; ++row)
|
||
{
|
||
var idx = (row * width + col) * 4;
|
||
|
||
color.R = bytes[idx];
|
||
color.G = bytes[idx + 1];
|
||
color.B = bytes[idx + 2];
|
||
|
||
image[col, row] = color;
|
||
}
|
||
}
|
||
|
||
// Save the image as bitmap.
|
||
image.Save("./output.bmp");
|
||
}
|
||
|
||
static Dictionary<string, string>? ParseArguments(string[] args)
|
||
{
|
||
if (args.Length == 0 || Array.Exists(args, arg => arg == "--help"))
|
||
{
|
||
PrintHelp();
|
||
return null;
|
||
}
|
||
|
||
var arguments = new Dictionary<string, string>();
|
||
string? lastKey = null;
|
||
foreach (var arg in args)
|
||
{
|
||
if (arg.StartsWith("--"))
|
||
{
|
||
if (lastKey != null)
|
||
{
|
||
Console.WriteLine($"Error: Missing value for {lastKey}.");
|
||
PrintHelp();
|
||
return null;
|
||
}
|
||
if (!IsValidArgument(arg))
|
||
{
|
||
Console.WriteLine($"Error: Unknown argument {arg}.");
|
||
PrintHelp();
|
||
return null;
|
||
}
|
||
lastKey = arg;
|
||
}
|
||
else
|
||
{
|
||
if (lastKey == null)
|
||
{
|
||
Console.WriteLine("Error: Value without a preceding flag.");
|
||
PrintHelp();
|
||
return null;
|
||
}
|
||
arguments[lastKey] = arg;
|
||
lastKey = null;
|
||
}
|
||
}
|
||
|
||
if (lastKey != null)
|
||
{
|
||
Console.WriteLine($"Error: Missing value for {lastKey}.");
|
||
PrintHelp();
|
||
return null;
|
||
}
|
||
|
||
return arguments;
|
||
}
|
||
|
||
static bool IsValidArgument(string argument)
|
||
{
|
||
var validArguments = new List<string> { "--serverName", "--username", "--password", "--domain" };
|
||
return validArguments.Contains(argument);
|
||
}
|
||
|
||
static void PrintHelp()
|
||
{
|
||
Console.WriteLine("Usage: dotnet run -- [OPTIONS]");
|
||
Console.WriteLine("Options:");
|
||
Console.WriteLine(" --serverName <serverName> The name of the server to connect to.");
|
||
Console.WriteLine(" --username <username> The username for connection.");
|
||
Console.WriteLine(" --password <password> The password for connection.");
|
||
Console.WriteLine(" --domain <domain> The domain of the server.");
|
||
Console.WriteLine(" --help Show this message and exit.");
|
||
}
|
||
|
||
private static Config buildConfig(string username, string password, string domain, int width, int height)
|
||
{
|
||
ConfigBuilder configBuilder = ConfigBuilder.New();
|
||
|
||
configBuilder.WithUsernameAndPassword(username, password);
|
||
configBuilder.Domain = domain;
|
||
configBuilder.SetDesktopSize((ushort)height, (ushort)width);
|
||
configBuilder.ClientName = "IronRdp";
|
||
configBuilder.ClientDir = "C:\\";
|
||
configBuilder.PerformanceFlags = PerformanceFlags.NewDefault();
|
||
|
||
return configBuilder.Build();
|
||
}
|
||
|
||
}
|
||
}
|