WebSocketConnection.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using System;
  2. using System.Buffers;
  3. using System.IO.Pipelines;
  4. using System.Net;
  5. using System.Net.WebSockets;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions.Json;
  11. using MediaBrowser.Controller.Net;
  12. using MediaBrowser.Model.Net;
  13. using MediaBrowser.Model.Session;
  14. using Microsoft.AspNetCore.Http;
  15. using Microsoft.Extensions.Logging;
  16. namespace Emby.Server.Implementations.HttpServer
  17. {
  18. /// <summary>
  19. /// Class WebSocketConnection.
  20. /// </summary>
  21. public class WebSocketConnection : IWebSocketConnection, IDisposable
  22. {
  23. /// <summary>
  24. /// The logger.
  25. /// </summary>
  26. private readonly ILogger<WebSocketConnection> _logger;
  27. /// <summary>
  28. /// The json serializer options.
  29. /// </summary>
  30. private readonly JsonSerializerOptions _jsonOptions;
  31. /// <summary>
  32. /// The socket.
  33. /// </summary>
  34. private readonly WebSocket _socket;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="WebSocketConnection" /> class.
  37. /// </summary>
  38. /// <param name="logger">The logger.</param>
  39. /// <param name="socket">The socket.</param>
  40. /// <param name="remoteEndPoint">The remote end point.</param>
  41. /// <param name="query">The query.</param>
  42. public WebSocketConnection(
  43. ILogger<WebSocketConnection> logger,
  44. WebSocket socket,
  45. IPAddress? remoteEndPoint,
  46. IQueryCollection query)
  47. {
  48. _logger = logger;
  49. _socket = socket;
  50. RemoteEndPoint = remoteEndPoint;
  51. QueryString = query;
  52. _jsonOptions = JsonDefaults.Options;
  53. LastActivityDate = DateTime.Now;
  54. }
  55. /// <inheritdoc />
  56. public event EventHandler<EventArgs>? Closed;
  57. /// <summary>
  58. /// Gets or sets the remote end point.
  59. /// </summary>
  60. public IPAddress? RemoteEndPoint { get; }
  61. /// <summary>
  62. /// Gets or sets the receive action.
  63. /// </summary>
  64. /// <value>The receive action.</value>
  65. public Func<WebSocketMessageInfo, Task>? OnReceive { get; set; }
  66. /// <summary>
  67. /// Gets the last activity date.
  68. /// </summary>
  69. /// <value>The last activity date.</value>
  70. public DateTime LastActivityDate { get; private set; }
  71. /// <inheritdoc />
  72. public DateTime LastKeepAliveDate { get; set; }
  73. /// <summary>
  74. /// Gets or sets the query string.
  75. /// </summary>
  76. /// <value>The query string.</value>
  77. public IQueryCollection QueryString { get; }
  78. /// <summary>
  79. /// Gets the state.
  80. /// </summary>
  81. /// <value>The state.</value>
  82. public WebSocketState State => _socket.State;
  83. /// <summary>
  84. /// Sends a message asynchronously.
  85. /// </summary>
  86. /// <typeparam name="T"></typeparam>
  87. /// <param name="message">The message.</param>
  88. /// <param name="cancellationToken">The cancellation token.</param>
  89. /// <returns>Task.</returns>
  90. public Task SendAsync<T>(WebSocketMessage<T> message, CancellationToken cancellationToken)
  91. {
  92. var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
  93. return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken);
  94. }
  95. /// <inheritdoc />
  96. public async Task ProcessAsync(CancellationToken cancellationToken = default)
  97. {
  98. var pipe = new Pipe();
  99. var writer = pipe.Writer;
  100. ValueWebSocketReceiveResult receiveresult;
  101. do
  102. {
  103. // Allocate at least 512 bytes from the PipeWriter
  104. Memory<byte> memory = writer.GetMemory(512);
  105. try
  106. {
  107. receiveresult = await _socket.ReceiveAsync(memory, cancellationToken).ConfigureAwait(false);
  108. }
  109. catch (WebSocketException ex)
  110. {
  111. _logger.LogWarning("WS {IP} error receiving data: {Message}", RemoteEndPoint, ex.Message);
  112. break;
  113. }
  114. int bytesRead = receiveresult.Count;
  115. if (bytesRead == 0)
  116. {
  117. break;
  118. }
  119. // Tell the PipeWriter how much was read from the Socket
  120. writer.Advance(bytesRead);
  121. // Make the data available to the PipeReader
  122. FlushResult flushResult = await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
  123. if (flushResult.IsCompleted)
  124. {
  125. // The PipeReader stopped reading
  126. break;
  127. }
  128. LastActivityDate = DateTime.UtcNow;
  129. if (receiveresult.EndOfMessage)
  130. {
  131. await ProcessInternal(pipe.Reader).ConfigureAwait(false);
  132. }
  133. } while (
  134. (_socket.State == WebSocketState.Open || _socket.State == WebSocketState.Connecting)
  135. && receiveresult.MessageType != WebSocketMessageType.Close);
  136. Closed?.Invoke(this, EventArgs.Empty);
  137. if (_socket.State == WebSocketState.Open
  138. || _socket.State == WebSocketState.CloseReceived
  139. || _socket.State == WebSocketState.CloseSent)
  140. {
  141. await _socket.CloseAsync(
  142. WebSocketCloseStatus.NormalClosure,
  143. string.Empty,
  144. cancellationToken).ConfigureAwait(false);
  145. }
  146. }
  147. private async Task ProcessInternal(PipeReader reader)
  148. {
  149. ReadResult result = await reader.ReadAsync().ConfigureAwait(false);
  150. ReadOnlySequence<byte> buffer = result.Buffer;
  151. if (OnReceive == null)
  152. {
  153. // Tell the PipeReader how much of the buffer we have consumed
  154. reader.AdvanceTo(buffer.End);
  155. return;
  156. }
  157. WebSocketMessage<object>? stub;
  158. long bytesConsumed = 0;
  159. try
  160. {
  161. stub = DeserializeWebSocketMessage(buffer, out bytesConsumed);
  162. }
  163. catch (JsonException ex)
  164. {
  165. // Tell the PipeReader how much of the buffer we have consumed
  166. reader.AdvanceTo(buffer.End);
  167. _logger.LogError(ex, "Error processing web socket message: {Data}", Encoding.UTF8.GetString(buffer));
  168. return;
  169. }
  170. if (stub == null)
  171. {
  172. _logger.LogError("Error processing web socket message");
  173. return;
  174. }
  175. // Tell the PipeReader how much of the buffer we have consumed
  176. reader.AdvanceTo(buffer.GetPosition(bytesConsumed));
  177. _logger.LogDebug("WS {IP} received message: {@Message}", RemoteEndPoint, stub);
  178. if (stub.MessageType == SessionMessageType.KeepAlive)
  179. {
  180. await SendKeepAliveResponse().ConfigureAwait(false);
  181. }
  182. else
  183. {
  184. await OnReceive(
  185. new WebSocketMessageInfo
  186. {
  187. MessageType = stub.MessageType,
  188. Data = stub.Data?.ToString(), // Data can be null
  189. Connection = this
  190. }).ConfigureAwait(false);
  191. }
  192. }
  193. internal WebSocketMessage<object>? DeserializeWebSocketMessage(ReadOnlySequence<byte> bytes, out long bytesConsumed)
  194. {
  195. var jsonReader = new Utf8JsonReader(bytes);
  196. var ret = JsonSerializer.Deserialize<WebSocketMessage<object>>(ref jsonReader, _jsonOptions);
  197. bytesConsumed = jsonReader.BytesConsumed;
  198. return ret;
  199. }
  200. private Task SendKeepAliveResponse()
  201. {
  202. LastKeepAliveDate = DateTime.UtcNow;
  203. return SendAsync(
  204. new WebSocketMessage<string>
  205. {
  206. MessageId = Guid.NewGuid(),
  207. MessageType = SessionMessageType.KeepAlive
  208. }, CancellationToken.None);
  209. }
  210. /// <inheritdoc />
  211. public void Dispose()
  212. {
  213. Dispose(true);
  214. GC.SuppressFinalize(this);
  215. }
  216. /// <summary>
  217. /// Releases unmanaged and - optionally - managed resources.
  218. /// </summary>
  219. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  220. protected virtual void Dispose(bool dispose)
  221. {
  222. if (dispose)
  223. {
  224. _socket.Dispose();
  225. }
  226. }
  227. }
  228. }