HttpListenerHost.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Sockets;
  7. using System.Reflection;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Emby.Server.Implementations.Configuration;
  11. using Emby.Server.Implementations.Net;
  12. using Emby.Server.Implementations.Services;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Common.Net;
  15. using MediaBrowser.Controller;
  16. using MediaBrowser.Controller.Configuration;
  17. using MediaBrowser.Controller.Net;
  18. using MediaBrowser.Model.Events;
  19. using MediaBrowser.Model.Extensions;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Model.Services;
  22. using Microsoft.AspNetCore.Http;
  23. using Microsoft.AspNetCore.Http.Internal;
  24. using Microsoft.AspNetCore.WebUtilities;
  25. using Microsoft.Extensions.Configuration;
  26. using Microsoft.Extensions.Logging;
  27. using ServiceStack.Text.Jsv;
  28. namespace Emby.Server.Implementations.HttpServer
  29. {
  30. public class HttpListenerHost : IHttpServer, IDisposable
  31. {
  32. private readonly ILogger _logger;
  33. private readonly IServerConfigurationManager _config;
  34. private readonly INetworkManager _networkManager;
  35. private readonly IServerApplicationHost _appHost;
  36. private readonly IJsonSerializer _jsonSerializer;
  37. private readonly IXmlSerializer _xmlSerializer;
  38. private readonly IHttpListener _socketListener;
  39. private readonly Func<Type, Func<string, object>> _funcParseFn;
  40. private readonly string _defaultRedirectPath;
  41. private readonly Dictionary<Type, Type> ServiceOperationsMap = new Dictionary<Type, Type>();
  42. private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
  43. private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>();
  44. private bool _disposed = false;
  45. public HttpListenerHost(
  46. IServerApplicationHost applicationHost,
  47. ILogger<HttpListenerHost> logger,
  48. IServerConfigurationManager config,
  49. IConfiguration configuration,
  50. INetworkManager networkManager,
  51. IJsonSerializer jsonSerializer,
  52. IXmlSerializer xmlSerializer,
  53. IHttpListener socketListener)
  54. {
  55. _appHost = applicationHost;
  56. _logger = logger;
  57. _config = config;
  58. _defaultRedirectPath = configuration["HttpListenerHost:DefaultRedirectPath"];
  59. _networkManager = networkManager;
  60. _jsonSerializer = jsonSerializer;
  61. _xmlSerializer = xmlSerializer;
  62. _socketListener = socketListener;
  63. _socketListener.WebSocketConnected = OnWebSocketConnected;
  64. _funcParseFn = t => s => JsvReader.GetParseFn(t)(s);
  65. Instance = this;
  66. ResponseFilters = Array.Empty<Action<IRequest, HttpResponse, object>>();
  67. }
  68. public Action<IRequest, HttpResponse, object>[] ResponseFilters { get; set; }
  69. public static HttpListenerHost Instance { get; protected set; }
  70. public string[] UrlPrefixes { get; private set; }
  71. public string GlobalResponse { get; set; }
  72. public ServiceController ServiceController { get; private set; }
  73. public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;
  74. public object CreateInstance(Type type)
  75. {
  76. return _appHost.CreateInstance(type);
  77. }
  78. /// <summary>
  79. /// Applies the request filters. Returns whether or not the request has been handled
  80. /// and no more processing should be done.
  81. /// </summary>
  82. /// <returns></returns>
  83. public void ApplyRequestFilters(IRequest req, HttpResponse res, object requestDto)
  84. {
  85. //Exec all RequestFilter attributes with Priority < 0
  86. var attributes = GetRequestFilterAttributes(requestDto.GetType());
  87. int count = attributes.Count;
  88. int i = 0;
  89. for (; i < count && attributes[i].Priority < 0; i++)
  90. {
  91. var attribute = attributes[i];
  92. attribute.RequestFilter(req, res, requestDto);
  93. }
  94. //Exec remaining RequestFilter attributes with Priority >= 0
  95. for (; i < count && attributes[i].Priority >= 0; i++)
  96. {
  97. var attribute = attributes[i];
  98. attribute.RequestFilter(req, res, requestDto);
  99. }
  100. }
  101. public Type GetServiceTypeByRequest(Type requestType)
  102. {
  103. ServiceOperationsMap.TryGetValue(requestType, out var serviceType);
  104. return serviceType;
  105. }
  106. public void AddServiceInfo(Type serviceType, Type requestType)
  107. {
  108. ServiceOperationsMap[requestType] = serviceType;
  109. }
  110. private List<IHasRequestFilter> GetRequestFilterAttributes(Type requestDtoType)
  111. {
  112. var attributes = requestDtoType.GetCustomAttributes(true).OfType<IHasRequestFilter>().ToList();
  113. var serviceType = GetServiceTypeByRequest(requestDtoType);
  114. if (serviceType != null)
  115. {
  116. attributes.AddRange(serviceType.GetCustomAttributes(true).OfType<IHasRequestFilter>());
  117. }
  118. attributes.Sort((x, y) => x.Priority - y.Priority);
  119. return attributes;
  120. }
  121. private void OnWebSocketConnected(WebSocketConnectEventArgs e)
  122. {
  123. if (_disposed)
  124. {
  125. return;
  126. }
  127. var connection = new WebSocketConnection(e.WebSocket, e.Endpoint, _jsonSerializer, _logger)
  128. {
  129. OnReceive = ProcessWebSocketMessageReceived,
  130. Url = e.Url,
  131. QueryString = e.QueryString ?? new QueryCollection()
  132. };
  133. connection.Closed += OnConnectionClosed;
  134. lock (_webSocketConnections)
  135. {
  136. _webSocketConnections.Add(connection);
  137. }
  138. WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));
  139. }
  140. private void OnConnectionClosed(object sender, EventArgs e)
  141. {
  142. lock (_webSocketConnections)
  143. {
  144. _webSocketConnections.Remove((IWebSocketConnection)sender);
  145. }
  146. }
  147. private static Exception GetActualException(Exception ex)
  148. {
  149. if (ex is AggregateException agg)
  150. {
  151. var inner = agg.InnerException;
  152. if (inner != null)
  153. {
  154. return GetActualException(inner);
  155. }
  156. else
  157. {
  158. var inners = agg.InnerExceptions;
  159. if (inners != null && inners.Count > 0)
  160. {
  161. return GetActualException(inners[0]);
  162. }
  163. }
  164. }
  165. return ex;
  166. }
  167. private int GetStatusCode(Exception ex)
  168. {
  169. switch (ex)
  170. {
  171. case ArgumentException _: return 400;
  172. case SecurityException _: return 401;
  173. case DirectoryNotFoundException _:
  174. case FileNotFoundException _:
  175. case ResourceNotFoundException _: return 404;
  176. case MethodNotAllowedException _: return 405;
  177. case RemoteServiceUnavailableException _: return 502;
  178. default: return 500;
  179. }
  180. }
  181. private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage)
  182. {
  183. try
  184. {
  185. ex = GetActualException(ex);
  186. if (logExceptionStackTrace)
  187. {
  188. _logger.LogError(ex, "Error processing request");
  189. }
  190. else if (logExceptionMessage)
  191. {
  192. _logger.LogError(ex.Message);
  193. }
  194. var httpRes = httpReq.Response;
  195. if (httpRes.HasStarted)
  196. {
  197. return;
  198. }
  199. var statusCode = GetStatusCode(ex);
  200. httpRes.StatusCode = statusCode;
  201. httpRes.ContentType = "text/html";
  202. await httpRes.WriteAsync(NormalizeExceptionMessage(ex.Message)).ConfigureAwait(false);
  203. }
  204. catch (Exception errorEx)
  205. {
  206. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
  207. }
  208. }
  209. private string NormalizeExceptionMessage(string msg)
  210. {
  211. if (msg == null)
  212. {
  213. return string.Empty;
  214. }
  215. // Strip any information we don't want to reveal
  216. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  217. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  218. return msg;
  219. }
  220. /// <summary>
  221. /// Shut down the Web Service
  222. /// </summary>
  223. public void Stop()
  224. {
  225. List<IWebSocketConnection> connections;
  226. lock (_webSocketConnections)
  227. {
  228. connections = _webSocketConnections.ToList();
  229. _webSocketConnections.Clear();
  230. }
  231. foreach (var connection in connections)
  232. {
  233. try
  234. {
  235. connection.Dispose();
  236. }
  237. catch
  238. {
  239. }
  240. }
  241. }
  242. public static string RemoveQueryStringByKey(string url, string key)
  243. {
  244. var uri = new Uri(url);
  245. // this gets all the query string key value pairs as a collection
  246. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  247. var originalCount = newQueryString.Count;
  248. if (originalCount == 0)
  249. {
  250. return url;
  251. }
  252. // this removes the key if exists
  253. newQueryString.Remove(key);
  254. if (originalCount == newQueryString.Count)
  255. {
  256. return url;
  257. }
  258. // this gets the page path from root without QueryString
  259. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  260. return newQueryString.Count > 0
  261. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  262. : pagePathWithoutQueryString;
  263. }
  264. private static string GetUrlToLog(string url)
  265. {
  266. url = RemoveQueryStringByKey(url, "api_key");
  267. return url;
  268. }
  269. private static string NormalizeConfiguredLocalAddress(string address)
  270. {
  271. var add = address.AsSpan().Trim('/');
  272. int index = add.IndexOf('/');
  273. if (index != -1)
  274. {
  275. add = add.Slice(index + 1);
  276. }
  277. return add.TrimStart('/').ToString();
  278. }
  279. private bool ValidateHost(string host)
  280. {
  281. var hosts = _config
  282. .Configuration
  283. .LocalNetworkAddresses
  284. .Select(NormalizeConfiguredLocalAddress)
  285. .ToList();
  286. if (hosts.Count == 0)
  287. {
  288. return true;
  289. }
  290. host = host ?? string.Empty;
  291. if (_networkManager.IsInPrivateAddressSpace(host))
  292. {
  293. hosts.Add("localhost");
  294. hosts.Add("127.0.0.1");
  295. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  296. }
  297. return true;
  298. }
  299. private bool ValidateRequest(string remoteIp, bool isLocal)
  300. {
  301. if (isLocal)
  302. {
  303. return true;
  304. }
  305. if (_config.Configuration.EnableRemoteAccess)
  306. {
  307. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  308. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  309. {
  310. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  311. {
  312. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  313. }
  314. else
  315. {
  316. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  317. }
  318. }
  319. }
  320. else
  321. {
  322. if (!_networkManager.IsInLocalNetwork(remoteIp))
  323. {
  324. return false;
  325. }
  326. }
  327. return true;
  328. }
  329. private bool ValidateSsl(string remoteIp, string urlString)
  330. {
  331. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  332. {
  333. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  334. {
  335. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  336. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  337. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  338. {
  339. return true;
  340. }
  341. if (!_networkManager.IsInLocalNetwork(remoteIp))
  342. {
  343. return false;
  344. }
  345. }
  346. }
  347. return true;
  348. }
  349. /// <summary>
  350. /// Overridable method that can be used to implement a custom hnandler
  351. /// </summary>
  352. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  353. {
  354. var stopWatch = new Stopwatch();
  355. stopWatch.Start();
  356. var httpRes = httpReq.Response;
  357. string urlToLog = null;
  358. string remoteIp = httpReq.RemoteIp;
  359. try
  360. {
  361. if (_disposed)
  362. {
  363. httpRes.StatusCode = 503;
  364. httpRes.ContentType = "text/plain";
  365. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  366. return;
  367. }
  368. if (!ValidateHost(host))
  369. {
  370. httpRes.StatusCode = 400;
  371. httpRes.ContentType = "text/plain";
  372. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  373. return;
  374. }
  375. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  376. {
  377. httpRes.StatusCode = 403;
  378. httpRes.ContentType = "text/plain";
  379. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  380. return;
  381. }
  382. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  383. {
  384. RedirectToSecureUrl(httpReq, httpRes, urlString);
  385. return;
  386. }
  387. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  388. {
  389. httpRes.StatusCode = 200;
  390. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  391. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  392. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  393. httpRes.ContentType = "text/plain";
  394. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  395. return;
  396. }
  397. urlToLog = GetUrlToLog(urlString);
  398. if (string.Equals(localPath, "/" + _config.Configuration.BaseUrl + "/", StringComparison.OrdinalIgnoreCase)
  399. || string.Equals(localPath, "/" + _config.Configuration.BaseUrl, StringComparison.OrdinalIgnoreCase))
  400. {
  401. httpRes.Redirect("/" + _config.Configuration.BaseUrl + "/" + _defaultRedirectPath);
  402. return;
  403. }
  404. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  405. {
  406. httpRes.Redirect(_defaultRedirectPath);
  407. return;
  408. }
  409. if (string.IsNullOrEmpty(localPath))
  410. {
  411. httpRes.Redirect("/" + _defaultRedirectPath);
  412. return;
  413. }
  414. if (!string.IsNullOrEmpty(GlobalResponse))
  415. {
  416. // We don't want the address pings in ApplicationHost to fail
  417. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  418. {
  419. httpRes.StatusCode = 503;
  420. httpRes.ContentType = "text/html";
  421. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  422. return;
  423. }
  424. }
  425. var handler = GetServiceHandler(httpReq);
  426. if (handler != null)
  427. {
  428. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  429. }
  430. else
  431. {
  432. await ErrorHandler(new FileNotFoundException(), httpReq, false, false).ConfigureAwait(false);
  433. }
  434. }
  435. catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
  436. {
  437. await ErrorHandler(ex, httpReq, false, false).ConfigureAwait(false);
  438. }
  439. catch (SecurityException ex)
  440. {
  441. await ErrorHandler(ex, httpReq, false, true).ConfigureAwait(false);
  442. }
  443. catch (Exception ex)
  444. {
  445. var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
  446. await ErrorHandler(ex, httpReq, logException, false).ConfigureAwait(false);
  447. }
  448. finally
  449. {
  450. stopWatch.Stop();
  451. var elapsed = stopWatch.Elapsed;
  452. if (elapsed.TotalMilliseconds > 500)
  453. {
  454. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  455. }
  456. }
  457. }
  458. // Entry point for HttpListener
  459. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  460. {
  461. var pathInfo = httpReq.PathInfo;
  462. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  463. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  464. if (restPath != null)
  465. {
  466. return new ServiceHandler(restPath, contentType);
  467. }
  468. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  469. return null;
  470. }
  471. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  472. {
  473. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  474. {
  475. var builder = new UriBuilder(uri)
  476. {
  477. Port = _config.Configuration.PublicHttpsPort,
  478. Scheme = "https"
  479. };
  480. url = builder.Uri.ToString();
  481. }
  482. httpRes.Redirect(url);
  483. }
  484. /// <summary>
  485. /// Adds the rest handlers.
  486. /// </summary>
  487. /// <param name="services">The services.</param>
  488. /// <param name="listeners"></param>
  489. /// <param name="urlPrefixes"></param>
  490. public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  491. {
  492. _webSocketListeners = listeners.ToArray();
  493. UrlPrefixes = urlPrefixes.ToArray();
  494. ServiceController = new ServiceController();
  495. var types = services.Select(r => r.GetType());
  496. ServiceController.Init(this, types);
  497. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  498. {
  499. new ResponseFilter(_logger).FilterResponse
  500. };
  501. }
  502. public RouteAttribute[] GetRouteAttributes(Type requestType)
  503. {
  504. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  505. var clone = routes.ToList();
  506. foreach (var route in clone)
  507. {
  508. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(_config.Configuration.BaseUrl, route.Path), route.Verbs)
  509. {
  510. Notes = route.Notes,
  511. Priority = route.Priority,
  512. Summary = route.Summary
  513. });
  514. routes.Add(new RouteAttribute(NormalizeOldRoutePath(route.Path), route.Verbs)
  515. {
  516. Notes = route.Notes,
  517. Priority = route.Priority,
  518. Summary = route.Summary
  519. });
  520. }
  521. return routes.ToArray();
  522. }
  523. public Func<string, object> GetParseFn(Type propertyType)
  524. {
  525. return _funcParseFn(propertyType);
  526. }
  527. public void SerializeToJson(object o, Stream stream)
  528. {
  529. _jsonSerializer.SerializeToStream(o, stream);
  530. }
  531. public void SerializeToXml(object o, Stream stream)
  532. {
  533. _xmlSerializer.SerializeToStream(o, stream);
  534. }
  535. public Task<object> DeserializeXml(Type type, Stream stream)
  536. {
  537. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  538. }
  539. public Task<object> DeserializeJson(Type type, Stream stream)
  540. {
  541. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  542. }
  543. public Task ProcessWebSocketRequest(HttpContext context)
  544. {
  545. return _socketListener.ProcessWebSocketRequest(context);
  546. }
  547. // this method was left for compatibility with third party clients
  548. private static string NormalizeOldRoutePath(string path)
  549. {
  550. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  551. {
  552. return "/emby" + path;
  553. }
  554. return "emby/" + path;
  555. }
  556. private static string NormalizeCustomRoutePath(string baseUrl, string path)
  557. {
  558. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  559. {
  560. return "/" + baseUrl + path;
  561. }
  562. return baseUrl + "/" + path;
  563. }
  564. /// <inheritdoc />
  565. public void Dispose()
  566. {
  567. Dispose(true);
  568. GC.SuppressFinalize(this);
  569. }
  570. protected virtual void Dispose(bool disposing)
  571. {
  572. if (_disposed) return;
  573. if (disposing)
  574. {
  575. Stop();
  576. }
  577. _disposed = true;
  578. }
  579. /// <summary>
  580. /// Processes the web socket message received.
  581. /// </summary>
  582. /// <param name="result">The result.</param>
  583. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  584. {
  585. if (_disposed)
  586. {
  587. return Task.CompletedTask;
  588. }
  589. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  590. IEnumerable<Task> GetTasks()
  591. {
  592. foreach (var x in _webSocketListeners)
  593. {
  594. yield return x.ProcessMessageAsync(result);
  595. }
  596. }
  597. return Task.WhenAll(GetTasks());
  598. }
  599. }
  600. }