2019-12-26 14:57:46 -05:00
|
|
|
using System;
|
2019-12-17 17:15:02 -05:00
|
|
|
using System.Buffers;
|
|
|
|
using System.IO.Pipelines;
|
|
|
|
using System.Net;
|
2019-01-13 14:20:41 -05:00
|
|
|
using System.Net.WebSockets;
|
2021-01-12 19:11:12 -05:00
|
|
|
using System.Text;
|
2019-12-17 17:15:02 -05:00
|
|
|
using System.Text.Json;
|
2019-01-13 14:20:41 -05:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
2021-06-19 12:02:33 -04:00
|
|
|
using Jellyfin.Extensions.Json;
|
2014-12-27 13:06:32 -05:00
|
|
|
using MediaBrowser.Controller.Net;
|
2023-06-29 07:44:36 -04:00
|
|
|
using MediaBrowser.Controller.Net.WebSocketMessages;
|
2023-07-02 18:14:44 -04:00
|
|
|
using MediaBrowser.Controller.Net.WebSocketMessages.Outbound;
|
2020-09-25 03:25:59 -04:00
|
|
|
using MediaBrowser.Model.Session;
|
2023-06-09 11:11:22 -04:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2019-01-13 14:20:41 -05:00
|
|
|
using Microsoft.Extensions.Logging;
|
2013-02-20 20:33:05 -05:00
|
|
|
|
2018-09-12 13:26:21 -04:00
|
|
|
namespace Emby.Server.Implementations.HttpServer
|
2013-02-20 20:33:05 -05:00
|
|
|
{
|
|
|
|
/// <summary>
|
2019-11-01 13:38:54 -04:00
|
|
|
/// Class WebSocketConnection.
|
2013-02-20 20:33:05 -05:00
|
|
|
/// </summary>
|
2022-07-24 12:35:46 -04:00
|
|
|
public class WebSocketConnection : IWebSocketConnection
|
2013-02-20 20:33:05 -05:00
|
|
|
{
|
|
|
|
/// <summary>
|
2019-11-01 13:38:54 -04:00
|
|
|
/// The logger.
|
2013-02-20 20:33:05 -05:00
|
|
|
/// </summary>
|
2020-06-05 20:15:56 -04:00
|
|
|
private readonly ILogger<WebSocketConnection> _logger;
|
2013-02-20 20:33:05 -05:00
|
|
|
|
2013-02-24 16:53:54 -05:00
|
|
|
/// <summary>
|
2019-12-17 17:15:02 -05:00
|
|
|
/// The json serializer options.
|
2013-02-24 16:53:54 -05:00
|
|
|
/// </summary>
|
2019-12-17 17:15:02 -05:00
|
|
|
private readonly JsonSerializerOptions _jsonOptions;
|
2013-02-25 22:43:04 -05:00
|
|
|
|
|
|
|
/// <summary>
|
2019-12-10 10:22:03 -05:00
|
|
|
/// The socket.
|
2013-10-02 21:22:50 -04:00
|
|
|
/// </summary>
|
2019-12-17 17:15:02 -05:00
|
|
|
private readonly WebSocket _socket;
|
2016-10-06 14:55:01 -04:00
|
|
|
|
2022-07-24 12:35:46 -04:00
|
|
|
private bool _disposed = false;
|
|
|
|
|
2013-02-20 20:33:05 -05:00
|
|
|
/// <summary>
|
|
|
|
/// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
|
|
|
|
/// </summary>
|
2019-12-26 14:57:46 -05:00
|
|
|
/// <param name="logger">The logger.</param>
|
2013-02-20 20:33:05 -05:00
|
|
|
/// <param name="socket">The socket.</param>
|
2023-06-09 11:11:22 -04:00
|
|
|
/// <param name="authorizationInfo">The authorization information.</param>
|
2013-02-20 20:33:05 -05:00
|
|
|
/// <param name="remoteEndPoint">The remote end point.</param>
|
2019-12-26 14:57:46 -05:00
|
|
|
public WebSocketConnection(
|
|
|
|
ILogger<WebSocketConnection> logger,
|
|
|
|
WebSocket socket,
|
2023-06-09 11:11:22 -04:00
|
|
|
AuthorizationInfo authorizationInfo,
|
2022-01-01 11:59:25 -05:00
|
|
|
IPAddress? remoteEndPoint)
|
2013-02-20 20:33:05 -05:00
|
|
|
{
|
2019-12-26 14:57:46 -05:00
|
|
|
_logger = logger;
|
2013-02-20 20:33:05 -05:00
|
|
|
_socket = socket;
|
2023-06-09 11:11:22 -04:00
|
|
|
AuthorizationInfo = authorizationInfo;
|
2013-02-20 20:33:05 -05:00
|
|
|
RemoteEndPoint = remoteEndPoint;
|
2014-05-17 14:37:40 -04:00
|
|
|
|
2021-03-08 23:57:38 -05:00
|
|
|
_jsonOptions = JsonDefaults.Options;
|
2019-12-26 14:57:46 -05:00
|
|
|
LastActivityDate = DateTime.Now;
|
2014-05-17 14:37:40 -04:00
|
|
|
}
|
|
|
|
|
2019-11-01 13:38:54 -04:00
|
|
|
/// <inheritdoc />
|
2019-12-26 14:57:46 -05:00
|
|
|
public event EventHandler<EventArgs>? Closed;
|
2019-11-01 13:38:54 -04:00
|
|
|
|
2023-06-09 11:11:22 -04:00
|
|
|
/// <inheritdoc />
|
|
|
|
public AuthorizationInfo AuthorizationInfo { get; }
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
2019-12-26 14:57:46 -05:00
|
|
|
public IPAddress? RemoteEndPoint { get; }
|
2019-11-01 13:38:54 -04:00
|
|
|
|
2023-06-09 11:11:22 -04:00
|
|
|
/// <inheritdoc />
|
2019-12-26 14:57:46 -05:00
|
|
|
public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
|
2019-11-01 13:38:54 -04:00
|
|
|
|
2023-06-09 11:11:22 -04:00
|
|
|
/// <inheritdoc />
|
2019-11-01 13:38:54 -04:00
|
|
|
public DateTime LastActivityDate { get; private set; }
|
|
|
|
|
2020-04-17 07:47:00 -04:00
|
|
|
/// <inheritdoc />
|
|
|
|
public DateTime LastKeepAliveDate { get; set; }
|
|
|
|
|
2023-06-09 11:11:22 -04:00
|
|
|
/// <inheritdoc />
|
2019-11-01 13:38:54 -04:00
|
|
|
public WebSocketState State => _socket.State;
|
|
|
|
|
2023-07-02 18:14:44 -04:00
|
|
|
/// <inheritdoc />
|
|
|
|
public Task SendAsync(OutboundWebSocketMessage message, CancellationToken cancellationToken)
|
2023-06-29 07:44:36 -04:00
|
|
|
{
|
|
|
|
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
|
|
|
|
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
|
|
|
|
}
|
|
|
|
|
2023-07-02 18:14:44 -04:00
|
|
|
/// <inheritdoc />
|
|
|
|
public Task SendAsync<T>(OutboundWebSocketMessage<T> message, CancellationToken cancellationToken)
|
2014-05-17 14:37:40 -04:00
|
|
|
{
|
2019-12-17 17:15:02 -05:00
|
|
|
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
|
|
|
|
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
|
2013-02-20 20:33:05 -05:00
|
|
|
}
|
|
|
|
|
2019-12-17 17:15:02 -05:00
|
|
|
/// <inheritdoc />
|
2023-06-09 11:11:22 -04:00
|
|
|
public async Task ReceiveAsync(CancellationToken cancellationToken = default)
|
2013-02-20 20:33:05 -05:00
|
|
|
{
|
2019-12-17 17:15:02 -05:00
|
|
|
var pipe = new Pipe();
|
|
|
|
var writer = pipe.Writer;
|
2013-05-25 20:53:51 -04:00
|
|
|
|
2019-12-17 17:15:02 -05:00
|
|
|
ValueWebSocketReceiveResult receiveresult;
|
|
|
|
do
|
2013-02-25 22:43:04 -05:00
|
|
|
{
|
2019-12-17 17:15:02 -05:00
|
|
|
// Allocate at least 512 bytes from the PipeWriter
|
|
|
|
Memory<byte> memory = writer.GetMemory(512);
|
2019-12-27 09:42:59 -05:00
|
|
|
try
|
|
|
|
{
|
2020-08-01 09:03:33 -04:00
|
|
|
receiveresult = await _socket.ReceiveAsync(memory, cancellationToken).ConfigureAwait(false);
|
2019-12-27 09:42:59 -05:00
|
|
|
}
|
|
|
|
catch (WebSocketException ex)
|
|
|
|
{
|
|
|
|
_logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
|
|
|
|
break;
|
|
|
|
}
|
2015-03-08 20:36:02 -04:00
|
|
|
|
2019-12-17 17:15:02 -05:00
|
|
|
int bytesRead = receiveresult.Count;
|
|
|
|
if (bytesRead == 0)
|
|
|
|
{
|
2019-12-26 14:57:46 -05:00
|
|
|
break;
|
2019-12-17 17:15:02 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Tell the PipeWriter how much was read from the Socket
|
|
|
|
writer.Advance(bytesRead);
|
|
|
|
|
|
|
|
// Make the data available to the PipeReader
|
2021-01-12 19:11:12 -05:00
|
|
|
FlushResult flushResult = await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
|
2019-12-17 17:15:02 -05:00
|
|
|
if (flushResult.IsCompleted)
|
|
|
|
{
|
|
|
|
// The PipeReader stopped reading
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2019-12-26 14:57:46 -05:00
|
|
|
LastActivityDate = DateTime.UtcNow;
|
|
|
|
|
2019-12-17 17:15:02 -05:00
|
|
|
if (receiveresult.EndOfMessage)
|
|
|
|
{
|
|
|
|
await ProcessInternal(pipe.Reader).ConfigureAwait(false);
|
|
|
|
}
|
2021-10-02 14:03:47 -04:00
|
|
|
}
|
|
|
|
while ((_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
|
2019-12-27 09:56:20 -05:00
|
|
|
&& receiveresult.MessageType != WebSocketMessageType.Close);
|
2019-12-17 17:15:02 -05:00
|
|
|
|
|
|
|
Closed?.Invoke(this, EventArgs.Empty);
|
|
|
|
|
2019-12-27 09:56:20 -05:00
|
|
|
if (_socket.State == WebSocketState.Open
|
|
|
|
|| _socket.State == WebSocketState.CloseReceived
|
|
|
|
|| _socket.State == WebSocketState.CloseSent)
|
2015-03-08 20:36:02 -04:00
|
|
|
{
|
2019-12-27 09:56:20 -05:00
|
|
|
await _socket.CloseAsync(
|
|
|
|
WebSocketCloseStatus.NormalClosure,
|
|
|
|
string.Empty,
|
|
|
|
cancellationToken).ConfigureAwait(false);
|
2015-03-08 20:36:02 -04:00
|
|
|
}
|
|
|
|
}
|
2013-02-20 20:33:05 -05:00
|
|
|
|
2019-12-17 17:15:02 -05:00
|
|
|
private async Task ProcessInternal(PipeReader reader)
|
2013-09-05 17:34:46 -04:00
|
|
|
{
|
2019-12-27 08:42:53 -05:00
|
|
|
ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
|
|
|
|
ReadOnlySequence<byte> buffer = result.Buffer;
|
2013-09-05 17:34:46 -04:00
|
|
|
|
2022-12-05 09:00:20 -05:00
|
|
|
if (OnReceive is null)
|
2013-09-07 11:59:29 -04:00
|
|
|
{
|
2019-12-27 08:42:53 -05:00
|
|
|
// Tell the PipeReader how much of the buffer we have consumed
|
|
|
|
reader.AdvanceTo(buffer.End);
|
2013-09-07 11:59:29 -04:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-07-02 18:14:44 -04:00
|
|
|
InboundWebSocketMessage<object>? stub;
|
2021-04-17 04:27:58 -04:00
|
|
|
long bytesConsumed;
|
2013-09-05 17:34:46 -04:00
|
|
|
try
|
|
|
|
{
|
2021-01-12 19:11:12 -05:00
|
|
|
stub = DeserializeWebSocketMessage(buffer, out bytesConsumed);
|
2013-09-05 17:34:46 -04:00
|
|
|
}
|
2019-12-17 17:15:02 -05:00
|
|
|
catch (JsonException ex)
|
2013-09-05 17:34:46 -04:00
|
|
|
{
|
2019-12-27 08:42:53 -05:00
|
|
|
// Tell the PipeReader how much of the buffer we have consumed
|
|
|
|
reader.AdvanceTo(buffer.End);
|
2021-01-12 19:11:12 -05:00
|
|
|
_logger.LogError(ex, "Error processing web socket message: {Data}", Encoding.UTF8.GetString(buffer));
|
2019-12-27 08:42:53 -05:00
|
|
|
return;
|
2013-09-05 17:34:46 -04:00
|
|
|
}
|
2016-10-07 11:08:13 -04:00
|
|
|
|
2022-12-05 09:00:20 -05:00
|
|
|
if (stub is null)
|
2020-08-25 10:11:50 -04:00
|
|
|
{
|
|
|
|
_logger.LogError("Error processing web socket message");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-12-27 08:42:53 -05:00
|
|
|
// Tell the PipeReader how much of the buffer we have consumed
|
2021-01-12 19:11:12 -05:00
|
|
|
reader.AdvanceTo(buffer.GetPosition(bytesConsumed));
|
2013-02-24 16:53:54 -05:00
|
|
|
|
2019-12-29 08:53:04 -05:00
|
|
|
_logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
|
2013-02-20 20:33:05 -05:00
|
|
|
|
2021-01-12 19:11:12 -05:00
|
|
|
if (stub.MessageType == SessionMessageType.KeepAlive)
|
2014-07-20 00:46:29 -04:00
|
|
|
{
|
2020-08-01 09:03:33 -04:00
|
|
|
await SendKeepAliveResponse().ConfigureAwait(false);
|
2014-07-20 00:46:29 -04:00
|
|
|
}
|
2020-05-15 12:59:35 -04:00
|
|
|
else
|
2013-02-20 20:33:05 -05:00
|
|
|
{
|
2021-01-12 19:11:12 -05:00
|
|
|
await OnReceive(
|
|
|
|
new WebSocketMessageInfo
|
|
|
|
{
|
|
|
|
MessageType = stub.MessageType,
|
|
|
|
Data = stub.Data?.ToString(), // Data can be null
|
|
|
|
Connection = this
|
|
|
|
}).ConfigureAwait(false);
|
2013-02-20 20:33:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-02 18:14:44 -04:00
|
|
|
internal InboundWebSocketMessage<object>? DeserializeWebSocketMessage(ReadOnlySequence<byte> bytes, out long bytesConsumed)
|
2021-01-12 19:11:12 -05:00
|
|
|
{
|
|
|
|
var jsonReader = new Utf8JsonReader(bytes);
|
2023-07-02 18:14:44 -04:00
|
|
|
var ret = JsonSerializer.Deserialize<InboundWebSocketMessage<object>>(ref jsonReader, _jsonOptions);
|
2021-01-12 19:11:12 -05:00
|
|
|
bytesConsumed = jsonReader.BytesConsumed;
|
|
|
|
return ret;
|
|
|
|
}
|
|
|
|
|
2020-05-26 05:37:52 -04:00
|
|
|
private Task SendKeepAliveResponse()
|
2020-04-17 07:47:00 -04:00
|
|
|
{
|
|
|
|
LastKeepAliveDate = DateTime.UtcNow;
|
2020-06-11 12:51:47 -04:00
|
|
|
return SendAsync(
|
2023-07-02 18:14:44 -04:00
|
|
|
new OutboundKeepAliveMessage(),
|
2021-12-24 12:28:27 -05:00
|
|
|
CancellationToken.None);
|
2020-04-17 07:47:00 -04:00
|
|
|
}
|
|
|
|
|
2019-11-01 13:38:54 -04:00
|
|
|
/// <inheritdoc />
|
2013-02-20 20:33:05 -05:00
|
|
|
public void Dispose()
|
|
|
|
{
|
|
|
|
Dispose(true);
|
2019-11-01 13:38:54 -04:00
|
|
|
GC.SuppressFinalize(this);
|
2013-02-20 20:33:05 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Releases unmanaged and - optionally - managed resources.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
|
|
|
protected virtual void Dispose(bool dispose)
|
|
|
|
{
|
2022-07-24 12:35:46 -04:00
|
|
|
if (_disposed)
|
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2013-02-20 20:33:05 -05:00
|
|
|
if (dispose)
|
|
|
|
{
|
|
|
|
_socket.Dispose();
|
|
|
|
}
|
2022-07-24 12:35:46 -04:00
|
|
|
|
|
|
|
_disposed = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public async ValueTask DisposeAsync()
|
|
|
|
{
|
|
|
|
await DisposeAsyncCore().ConfigureAwait(false);
|
|
|
|
Dispose(false);
|
|
|
|
GC.SuppressFinalize(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Used to perform asynchronous cleanup of managed resources or for cascading calls to <see cref="DisposeAsync"/>.
|
|
|
|
/// </summary>
|
|
|
|
/// <returns>A ValueTask.</returns>
|
|
|
|
protected virtual async ValueTask DisposeAsyncCore()
|
|
|
|
{
|
|
|
|
if (_socket.State == WebSocketState.Open)
|
|
|
|
{
|
|
|
|
await _socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "System Shutdown", CancellationToken.None).ConfigureAwait(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
_socket.Dispose();
|
2013-02-20 20:33:05 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|