jellyfin/Emby.Server.Implementations/HttpServer/WebSocketConnection.cs

265 lines
8.6 KiB
C#
Raw Normal View History

#nullable enable
using System;
2019-12-17 15:15:02 -07:00
using System.Buffers;
using System.IO.Pipelines;
using System.Net;
using System.Net.WebSockets;
2019-12-17 15:15:02 -07:00
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
2019-12-17 15:15:02 -07:00
using MediaBrowser.Common.Json;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
2013-02-20 18:33:05 -07:00
2018-09-12 10:26:21 -07:00
namespace Emby.Server.Implementations.HttpServer
2013-02-20 18:33:05 -07:00
{
/// <summary>
2019-11-01 10:38:54 -07:00
/// Class WebSocketConnection.
2013-02-20 18:33:05 -07:00
/// </summary>
public class WebSocketConnection : IWebSocketConnection
2013-02-20 18:33:05 -07:00
{
/// <summary>
2019-11-01 10:38:54 -07:00
/// The logger.
2013-02-20 18:33:05 -07:00
/// </summary>
2020-06-05 17:15:56 -07:00
private readonly ILogger<WebSocketConnection> _logger;
2013-02-20 18:33:05 -07:00
2013-02-24 14:53:54 -07:00
/// <summary>
2019-12-17 15:15:02 -07:00
/// The json serializer options.
2013-02-24 14:53:54 -07:00
/// </summary>
2019-12-17 15:15:02 -07:00
private readonly JsonSerializerOptions _jsonOptions;
/// <summary>
/// The socket.
2013-10-02 18:22:50 -07:00
/// </summary>
2019-12-17 15:15:02 -07:00
private readonly WebSocket _socket;
2016-10-06 11:55:01 -07:00
2013-02-20 18:33:05 -07:00
/// <summary>
/// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
2013-02-20 18:33:05 -07:00
/// <param name="socket">The socket.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <param name="query">The query.</param>
public WebSocketConnection(
ILogger<WebSocketConnection> logger,
WebSocket socket,
IPAddress? remoteEndPoint,
IQueryCollection query)
2013-02-20 18:33:05 -07:00
{
_logger = logger;
2013-02-20 18:33:05 -07:00
_socket = socket;
RemoteEndPoint = remoteEndPoint;
QueryString = query;
2014-05-17 11:37:40 -07:00
2019-12-17 15:15:02 -07:00
_jsonOptions = JsonDefaults.GetOptions();
LastActivityDate = DateTime.Now;
2014-05-17 11:37:40 -07:00
}
2019-11-01 10:38:54 -07:00
/// <inheritdoc />
public event EventHandler<EventArgs>? Closed;
2019-11-01 10:38:54 -07:00
/// <summary>
/// Gets or sets the remote end point.
2019-11-01 10:38:54 -07:00
/// </summary>
public IPAddress? RemoteEndPoint { get; }
2019-11-01 10:38:54 -07:00
/// <summary>
/// Gets or sets the receive action.
/// </summary>
/// <value>The receive action.</value>
public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
2019-11-01 10:38:54 -07:00
/// <summary>
/// Gets the last activity date.
/// </summary>
/// <value>The last activity date.</value>
public DateTime LastActivityDate { get; private set; }
2020-04-17 04:47:00 -07:00
/// <inheritdoc />
public DateTime LastKeepAliveDate { get; set; }
2019-11-01 10:38:54 -07:00
/// <summary>
/// Gets or sets the query string.
/// </summary>
/// <value>The query string.</value>
public IQueryCollection QueryString { get; }
2019-11-01 10:38:54 -07:00
/// <summary>
/// Gets the state.
/// </summary>
/// <value>The state.</value>
public WebSocketState State => _socket.State;
2013-02-20 18:33:05 -07:00
/// <summary>
2019-12-17 15:15:02 -07:00
/// Sends a message asynchronously.
2013-02-20 18:33:05 -07:00
/// </summary>
2019-12-17 15:15:02 -07:00
/// <typeparam name="T"></typeparam>
/// <param name="message">The message.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
2014-05-17 11:37:40 -07:00
{
2019-12-17 15:15:02 -07:00
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
2013-02-20 18:33:05 -07:00
}
2019-12-17 15:15:02 -07:00
/// <inheritdoc />
public async Task ProcessAsync(CancellationToken cancellationToken = default)
2013-02-20 18:33:05 -07:00
{
2019-12-17 15:15:02 -07:00
var pipe = new Pipe();
var writer = pipe.Writer;
2013-05-25 17:53:51 -07:00
2019-12-17 15:15:02 -07:00
ValueWebSocketReceiveResult receiveresult;
do
{
2019-12-17 15:15:02 -07:00
// Allocate at least 512 bytes from the PipeWriter
Memory<byte> memory = writer.GetMemory(512);
2019-12-27 07:42:59 -07:00
try
{
receiveresult = await _socket.ReceiveAsync(memory, cancellationToken);
}
catch (WebSocketException ex)
{
_logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
break;
}
2015-03-08 17:36:02 -07:00
2019-12-17 15:15:02 -07:00
int bytesRead = receiveresult.Count;
if (bytesRead == 0)
{
break;
2019-12-17 15:15:02 -07:00
}
// Tell the PipeWriter how much was read from the Socket
writer.Advance(bytesRead);
// Make the data available to the PipeReader
FlushResult flushResult = await writer.FlushAsync();
if (flushResult.IsCompleted)
{
// The PipeReader stopped reading
break;
}
LastActivityDate = DateTime.UtcNow;
2019-12-17 15:15:02 -07:00
if (receiveresult.EndOfMessage)
{
await ProcessInternal(pipe.Reader).ConfigureAwait(false);
}
2019-12-27 07:56:20 -07:00
} while (
(_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
&& receiveresult.MessageType != WebSocketMessageType.Close);
2019-12-17 15:15:02 -07:00
Closed?.Invoke(this, EventArgs.Empty);
2019-12-27 07:56:20 -07:00
if (_socket.State == WebSocketState.Open
|| _socket.State == WebSocketState.CloseReceived
|| _socket.State == WebSocketState.CloseSent)
2015-03-08 17:36:02 -07:00
{
2019-12-27 07:56:20 -07:00
await _socket.CloseAsync(
WebSocketCloseStatus.NormalClosure,
string.Empty,
cancellationToken).ConfigureAwait(false);
2015-03-08 17:36:02 -07:00
}
}
2013-02-20 18:33:05 -07:00
2019-12-17 15:15:02 -07:00
private async Task ProcessInternal(PipeReader reader)
{
2019-12-27 06:42:53 -07:00
ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
ReadOnlySequence<byte> buffer = result.Buffer;
if (OnReceive == null)
{
2019-12-27 06:42:53 -07:00
// Tell the PipeReader how much of the buffer we have consumed
reader.AdvanceTo(buffer.End);
return;
}
2019-12-27 06:42:53 -07:00
WebSocketMessage<object> stub;
try
{
2019-12-17 15:15:02 -07:00
if (buffer.IsSingleSegment)
2020-04-17 04:47:00 -07:00
{
2019-12-17 15:15:02 -07:00
stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buffer.FirstSpan, _jsonOptions);
2020-04-17 04:47:00 -07:00
}
2020-04-21 14:37:37 -07:00
else
2020-04-17 04:47:00 -07:00
{
2019-12-17 15:15:02 -07:00
var buf = ArrayPool<byte>.Shared.Rent(Convert.ToInt32(buffer.Length));
try
{
buffer.CopyTo(buf);
stub = JsonSerializer.Deserialize<WebSocketMessage<object>>(buf, _jsonOptions);
}
finally
{
ArrayPool<byte>.Shared.Return(buf);
}
2020-04-17 04:47:00 -07:00
}
}
2019-12-17 15:15:02 -07:00
catch (JsonException ex)
{
2019-12-27 06:42:53 -07:00
// Tell the PipeReader how much of the buffer we have consumed
reader.AdvanceTo(buffer.End);
2018-12-20 05:11:26 -07:00
_logger.LogError(ex, "Error processing web socket message");
2019-12-27 06:42:53 -07:00
return;
}
2016-10-07 08:08:13 -07:00
2019-12-27 06:42:53 -07:00
// Tell the PipeReader how much of the buffer we have consumed
reader.AdvanceTo(buffer.End);
2013-02-24 14:53:54 -07:00
2019-12-29 06:53:04 -07:00
_logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
2013-02-20 18:33:05 -07:00
2019-12-27 06:42:53 -07:00
var info = new WebSocketMessageInfo
2019-12-17 15:15:02 -07:00
{
2019-12-27 06:42:53 -07:00
MessageType = stub.MessageType,
Data = stub.Data?.ToString(), // Data can be null
Connection = this
};
2013-02-20 18:33:05 -07:00
if (info.MessageType.Equals("KeepAlive", StringComparison.Ordinal))
2014-07-19 21:46:29 -07:00
{
2020-05-26 02:37:52 -07:00
await SendKeepAliveResponse();
2014-07-19 21:46:29 -07:00
}
else
2013-02-20 18:33:05 -07:00
{
await OnReceive(info).ConfigureAwait(false);
2013-02-20 18:33:05 -07:00
}
}
2020-05-26 02:37:52 -07:00
private Task SendKeepAliveResponse()
2020-04-17 04:47:00 -07:00
{
LastKeepAliveDate = DateTime.UtcNow;
return SendAsync(
new WebSocketMessage<string>
{
MessageId = Guid.NewGuid(),
MessageType = "KeepAlive"
}, CancellationToken.None);
2020-04-17 04:47:00 -07:00
}
2019-11-01 10:38:54 -07:00
/// <inheritdoc />
2013-02-20 18:33:05 -07:00
public void Dispose()
{
Dispose(true);
2019-11-01 10:38:54 -07:00
GC.SuppressFinalize(this);
2013-02-20 18:33:05 -07: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)
{
if (dispose)
{
_socket.Dispose();
}
}
}
}