WebSocketConnection.cs 8.8 KB

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