WebSocketSharpListener.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Emby.Server.Implementations.HttpServer;
  7. using Emby.Server.Implementations.Net;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Model.Services;
  10. using Microsoft.Extensions.Logging;
  11. namespace Jellyfin.Server.SocketSharp
  12. {
  13. public class WebSocketSharpListener : IHttpListener
  14. {
  15. private HttpListener _listener;
  16. private readonly ILogger _logger;
  17. private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
  18. private CancellationToken _disposeCancellationToken;
  19. public WebSocketSharpListener(
  20. ILogger logger)
  21. {
  22. _logger = logger;
  23. _disposeCancellationToken = _disposeCancellationTokenSource.Token;
  24. }
  25. public Func<Exception, IRequest, bool, bool, Task> ErrorHandler { get; set; }
  26. public Func<IHttpRequest, string, string, string, CancellationToken, Task> RequestHandler { get; set; }
  27. public Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
  28. public Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
  29. public void Start(IEnumerable<string> urlPrefixes)
  30. {
  31. // TODO
  32. //if (_listener == null)
  33. //{
  34. // _listener = new HttpListener(_logger, _cryptoProvider, _socketFactory, _streamHelper, _fileSystem, _environment);
  35. //}
  36. //_listener.EnableDualMode = _enableDualMode;
  37. //if (_certificate != null)
  38. //{
  39. // _listener.LoadCert(_certificate);
  40. //}
  41. //_logger.LogInformation("Adding HttpListener prefixes {Prefixes}", urlPrefixes);
  42. //_listener.Prefixes.AddRange(urlPrefixes);
  43. //_listener.OnContext = async c => await InitTask(c, _disposeCancellationToken).ConfigureAwait(false);
  44. //_listener.Start();
  45. if (_listener == null)
  46. {
  47. _listener = new HttpListener();
  48. }
  49. _logger.LogInformation("Adding HttpListener prefixes {Prefixes}", urlPrefixes);
  50. //foreach (var urlPrefix in urlPrefixes)
  51. //{
  52. // _listener.Prefixes.Add(urlPrefix);
  53. //}
  54. _listener.Prefixes.Add("http://localhost:8096/");
  55. _listener.Start();
  56. // TODO how to do this in netcore?
  57. _listener.BeginGetContext(async c => await InitTask(c, _disposeCancellationToken).ConfigureAwait(false),
  58. null);
  59. }
  60. private static void LogRequest(ILogger logger, HttpListenerRequest request)
  61. {
  62. var url = request.Url.ToString();
  63. logger.LogInformation(
  64. "{0} {1}. UserAgent: {2}",
  65. request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod,
  66. url,
  67. request.UserAgent ?? string.Empty);
  68. }
  69. private Task InitTask(IAsyncResult asyncResult, CancellationToken cancellationToken)
  70. {
  71. var context = _listener.EndGetContext(asyncResult);
  72. _listener.BeginGetContext(async c => await InitTask(c, _disposeCancellationToken).ConfigureAwait(false), null);
  73. IHttpRequest httpReq = null;
  74. var request = context.Request;
  75. try
  76. {
  77. if (request.IsWebSocketRequest)
  78. {
  79. LogRequest(_logger, request);
  80. return ProcessWebSocketRequest(context);
  81. }
  82. httpReq = GetRequest(context);
  83. }
  84. catch (Exception ex)
  85. {
  86. _logger.LogError(ex, "Error processing request");
  87. httpReq = httpReq ?? GetRequest(context);
  88. return ErrorHandler(ex, httpReq, true, true);
  89. }
  90. var uri = request.Url;
  91. return RequestHandler(httpReq, uri.OriginalString, uri.Host, uri.LocalPath, cancellationToken);
  92. }
  93. private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
  94. {
  95. try
  96. {
  97. var endpoint = ctx.Request.RemoteEndPoint.ToString();
  98. var url = ctx.Request.RawUrl;
  99. var queryString = new QueryParamCollection(ctx.Request.QueryString);
  100. var connectingArgs = new WebSocketConnectingEventArgs
  101. {
  102. Url = url,
  103. QueryString = queryString,
  104. Endpoint = endpoint
  105. };
  106. WebSocketConnecting?.Invoke(connectingArgs);
  107. if (connectingArgs.AllowConnection)
  108. {
  109. _logger.LogDebug("Web socket connection allowed");
  110. var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
  111. if (WebSocketConnected != null)
  112. {
  113. SharpWebSocket socket = null; //new SharpWebSocket(webSocketContext.WebSocket, _logger);
  114. await socket.ConnectAsServerAsync().ConfigureAwait(false);
  115. WebSocketConnected(new WebSocketConnectEventArgs
  116. {
  117. Url = url,
  118. QueryString = queryString,
  119. WebSocket = null, // socket,
  120. Endpoint = endpoint
  121. });
  122. await socket.StartReceive().ConfigureAwait(false);
  123. }
  124. }
  125. else
  126. {
  127. _logger.LogWarning("Web socket connection not allowed");
  128. TryClose(ctx, 401);
  129. }
  130. }
  131. catch (Exception ex)
  132. {
  133. _logger.LogError(ex, "AcceptWebSocketAsync error");
  134. TryClose(ctx, 500);
  135. }
  136. }
  137. private void TryClose(HttpListenerContext ctx, int statusCode)
  138. {
  139. try
  140. {
  141. ctx.Response.StatusCode = statusCode;
  142. ctx.Response.Close();
  143. }
  144. catch (Exception ex)
  145. {
  146. _logger.LogError(ex, "Error closing web socket response");
  147. }
  148. }
  149. private IHttpRequest GetRequest(HttpListenerContext httpContext)
  150. {
  151. var urlSegments = httpContext.Request.Url.Segments;
  152. var operationName = urlSegments[urlSegments.Length - 1];
  153. var req = new WebSocketSharpRequest(httpContext, operationName, _logger);
  154. return req;
  155. }
  156. public Task Stop()
  157. {
  158. _disposeCancellationTokenSource.Cancel();
  159. _listener?.Close();
  160. return Task.CompletedTask;
  161. }
  162. /// <summary>
  163. /// Releases the unmanaged resources and disposes of the managed resources used.
  164. /// </summary>
  165. public void Dispose()
  166. {
  167. Dispose(true);
  168. GC.SuppressFinalize(this);
  169. }
  170. private bool _disposed;
  171. /// <summary>
  172. /// Releases the unmanaged resources and disposes of the managed resources used.
  173. /// </summary>
  174. /// <param name="disposing">Whether or not the managed resources should be disposed</param>
  175. protected virtual void Dispose(bool disposing)
  176. {
  177. if (_disposed)
  178. {
  179. return;
  180. }
  181. if (disposing)
  182. {
  183. Stop().GetAwaiter().GetResult();
  184. }
  185. _disposed = true;
  186. }
  187. }
  188. }