WebSocketSharpListener.cs 8.4 KB

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