Files
Febe/src/Febe.Web/Connection/RemoteViewSocket.cs
T

350 lines
14 KiB
C#

using System.Buffers;
using System.Net.WebSockets;
using System.Text.Json;
using Febe.Web.Api;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Web.Connection;
/// <summary>
/// <c>/api/vista</c>: the remote view over a WebSocket (PROTOCOLLO.md, spec §4.1, §11). The security middleware has
/// already checked the session and the <c>Origin</c> (spec §13.1) before this runs. Frames go out as binary messages,
/// meta as text; mouse, keys and back/reload come in as small JSON text messages and go to the browser. Nothing that
/// comes in is ever logged: it contains what Alberto types.
/// </summary>
public static class RemoteViewSocket
{
public const string Path = "/api/vista";
/// <summary>Largest message accepted from the page; larger ones close the view.</summary>
public const int MaxMessageBytes = 4096;
/// <summary>Close code when the view was opened again elsewhere (the newest wins).</summary>
public const int CloseReplaced = 4001;
/// <summary>Close code when the browser stopped or is restarting.</summary>
public const int CloseBrowserStopped = 4002;
public static void Map(IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.Map(Path, HandleAsync);
}
public static async Task HandleAsync(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
var options = context.RequestServices.GetRequiredService<FebeWebOptions>();
if (options.Edition == FebeEdition.Desktop && !options.Demo)
{
await RefuseAsync(context, StatusCodes.Status404NotFound, "Sul desktop il browser di Febe ha la sua finestra: la vista remota c'è solo nel contenitore.").ConfigureAwait(false);
return;
}
if (!context.WebSockets.IsWebSocketRequest)
{
await RefuseAsync(context, StatusCodes.Status400BadRequest, "La vista remota si apre solo con una connessione WebSocket.").ConfigureAwait(false);
return;
}
if (context.RequestServices.GetService<IRemoteViewHost>() is not { } host)
{
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, "La vista remota non è disponibile: il browser di Febe non è in funzione.").ConfigureAwait(false);
return;
}
IRemoteViewConnection connection;
try
{
connection = await host.OpenAsync(context.RequestAborted).ConfigureAwait(false);
}
catch (RemoteViewUnavailableException ex)
{
await RefuseAsync(context, StatusCodes.Status503ServiceUnavailable, ex.Message).ConfigureAwait(false);
return;
}
await using (connection.ConfigureAwait(false))
{
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
{
KeepAliveInterval = TimeSpan.FromSeconds(20),
DangerousEnableCompression = false,
}).ConfigureAwait(false);
await RunAsync(socket, connection, context.RequestAborted).ConfigureAwait(false);
}
}
/// <summary>Pumps one view until either side closes it.</summary>
internal static async Task RunAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken aborted)
{
using var stop = CancellationTokenSource.CreateLinkedTokenSource(aborted);
var sender = Task.Run(() => SendLoopAsync(socket, connection, stop.Token), CancellationToken.None);
var closeStatus = WebSocketCloseStatus.NormalClosure;
var closeText = "Vista chiusa";
try
{
if (!await ReceiveLoopAsync(socket, connection, stop.Token).ConfigureAwait(false))
{
closeStatus = WebSocketCloseStatus.MessageTooBig;
closeText = "Messaggio troppo lungo";
}
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException)
{
// The page went away.
}
finally
{
await stop.CancelAsync().ConfigureAwait(false);
try
{
await sender.ConfigureAwait(false);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
}
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
await socket.CloseOutputAsync(closeStatus, closeText, timeout.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or ObjectDisposedException)
{
}
}
}
private static async Task SendLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
{
await foreach (var output in connection.ReadAsync(ct).ConfigureAwait(false))
{
switch (output)
{
case RemoteViewMeta meta:
await socket.SendAsync(MetaJson(meta), WebSocketMessageType.Text, endOfMessage: true, ct).ConfigureAwait(false);
break;
case RemoteViewFrame frame:
await socket.SendAsync(frame.Jpeg, WebSocketMessageType.Binary, endOfMessage: true, ct).ConfigureAwait(false);
break;
}
}
// The server ended the view (another tab, browser stopped, shutdown): tell the page why.
if (!ct.IsCancellationRequested && socket.State == WebSocketState.Open)
{
var (status, text) = connection.Ended switch
{
RemoteViewEnd.Replaced => ((WebSocketCloseStatus)CloseReplaced, "Vista aperta in un'altra finestra"),
RemoteViewEnd.ShuttingDown => (WebSocketCloseStatus.EndpointUnavailable, "Febe si sta fermando"),
_ => ((WebSocketCloseStatus)CloseBrowserStopped, "Il browser si è fermato"),
};
await socket.CloseOutputAsync(status, text, ct).ConfigureAwait(false);
}
}
/// <summary>
/// Reads the page's messages until it closes. Returns false when a message was too long: the caller closes the
/// view (only one task may send at a time, and the frames are being sent by another).
/// </summary>
private static async Task<bool> ReceiveLoopAsync(WebSocket socket, IRemoteViewConnection connection, CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(MaxMessageBytes + 1);
try
{
while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
{
var length = 0;
ValueWebSocketReceiveResult result;
do
{
if (length >= MaxMessageBytes + 1)
{
return false;
}
result = await socket.ReceiveAsync(buffer.AsMemory(length, MaxMessageBytes + 1 - length), ct).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
return true;
}
length += result.Count;
}
while (!result.EndOfMessage);
if (length > MaxMessageBytes)
{
return false;
}
if (result.MessageType != WebSocketMessageType.Text)
{
continue;
}
await DispatchAsync(buffer.AsMemory(0, length), connection, ct).ConfigureAwait(false);
}
return true;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
}
}
/// <summary>Parses one message of the page and forwards it. Unknown or malformed messages are dropped silently.</summary>
internal static async Task DispatchAsync(ReadOnlyMemory<byte> message, IRemoteViewConnection connection, CancellationToken ct)
{
object? input;
try
{
input = Parse(message);
}
catch (JsonException)
{
return;
}
try
{
switch (input)
{
case RemoteViewMouse mouse:
await connection.MouseAsync(mouse, ct).ConfigureAwait(false);
break;
case RemoteViewKey key:
await connection.KeyAsync(key, ct).ConfigureAwait(false);
break;
case RemoteViewNavigation navigation:
await connection.NavigateAsync(navigation, ct).ConfigureAwait(false);
break;
}
}
catch (Exception ex) when (ex is not OperationCanceledException && ex is not OutOfMemoryException)
{
// A lost gesture (no frame yet, browser restarting): the page simply tries again. Never logged: it may
// be a key of a password.
}
}
/// <summary>
/// The input messages of PROTOCOLLO.md: <c>mouse</c>, <c>key</c>, <c>navigate</c>. Returns null for anything else
/// (unknown type or action, missing fields, values out of range).
/// </summary>
internal static object? Parse(ReadOnlyMemory<byte> message)
{
using var document = JsonDocument.Parse(message, new JsonDocumentOptions { MaxDepth = 3 });
var root = document.RootElement;
if (root.ValueKind != JsonValueKind.Object || Text(root, "type", 16) is not { } type)
{
return null;
}
var action = Text(root, "action", 16);
switch (type)
{
case "mouse":
{
RemoteViewMouseAction? kind = action switch
{
"move" => RemoteViewMouseAction.Move,
"down" => RemoteViewMouseAction.Down,
"up" => RemoteViewMouseAction.Up,
"wheel" => RemoteViewMouseAction.Wheel,
_ => null,
};
if (kind is null || Number(root, "x") is not { } x || Number(root, "y") is not { } y || x is < 0 or > 1 || y is < 0 or > 1)
{
return null;
}
var button = Text(root, "button", 16) switch
{
"left" => RemoteViewButton.Left,
"middle" => RemoteViewButton.Middle,
"right" => RemoteViewButton.Right,
_ => kind is RemoteViewMouseAction.Down or RemoteViewMouseAction.Up ? RemoteViewButton.Left : RemoteViewButton.None,
};
var clicks = (int)Math.Clamp(Number(root, "clickCount") ?? 1, 1, 3);
var dx = Math.Clamp(Number(root, "deltaX") ?? 0, -5000, 5000);
var dy = Math.Clamp(Number(root, "deltaY") ?? 0, -5000, 5000);
return new RemoteViewMouse(kind.Value, x, y, button, clicks, dx, dy);
}
case "key":
{
RemoteViewKeyAction? kind = action switch
{
"down" => RemoteViewKeyAction.Down,
"up" => RemoteViewKeyAction.Up,
"char" => RemoteViewKeyAction.Char,
_ => null,
};
var key = Text(root, "key", 64) ?? string.Empty;
var code = Text(root, "code", 64) ?? string.Empty;
var text = Text(root, "text", 32);
var modifiers = (int)Math.Clamp(Number(root, "modifiers") ?? 0, 0, 15);
if (kind is null || (kind == RemoteViewKeyAction.Char ? string.IsNullOrEmpty(text) : key.Length == 0))
{
return null;
}
return new RemoteViewKey(kind.Value, key, code, string.IsNullOrEmpty(text) ? null : text, modifiers);
}
case "navigate":
return action switch
{
"back" => RemoteViewNavigation.Back,
"reload" => RemoteViewNavigation.Reload,
_ => null,
};
default:
return null;
}
}
/// <summary>The meta message as UTF-8 JSON.</summary>
internal static ReadOnlyMemory<byte> MetaJson(RemoteViewMeta meta)
{
var buffer = new ArrayBufferWriter<byte>(256);
using (var writer = new Utf8JsonWriter(buffer))
{
writer.WriteStartObject();
writer.WriteString("type", "meta");
writer.WriteNumber("width", meta.Width);
writer.WriteNumber("height", meta.Height);
writer.WriteString("url", meta.Url);
writer.WriteEndObject();
}
return buffer.WrittenMemory;
}
private static string? Text(JsonElement root, string name, int maxLength) =>
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String && value.GetString() is { } s && s.Length <= maxLength
? s
: null;
private static double? Number(JsonElement root, string name) =>
root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var d) && double.IsFinite(d)
? d
: null;
private static Task RefuseAsync(HttpContext context, int status, string message)
{
context.Response.StatusCode = status;
return context.Response.WriteAsJsonAsync(new ProblemDto(message), FebeJsonContext.Default.ProblemDto);
}
}