HttpListenerHost.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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)
  182. {
  183. try
  184. {
  185. ex = GetActualException(ex);
  186. if (logExceptionStackTrace)
  187. {
  188. _logger.LogError(ex, "Error processing request");
  189. }
  190. else
  191. {
  192. _logger.LogError("Error processing request: {0}", 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. var errContent = NormalizeExceptionMessage(ex.Message);
  202. httpRes.ContentType = "text/plain";
  203. httpRes.ContentLength = errContent.Length;
  204. await httpRes.WriteAsync(errContent).ConfigureAwait(false);
  205. }
  206. catch (Exception errorEx)
  207. {
  208. _logger.LogError(errorEx, "Error this.ProcessRequest(context)(Exception while writing error to the response)");
  209. }
  210. }
  211. private string NormalizeExceptionMessage(string msg)
  212. {
  213. if (msg == null)
  214. {
  215. return string.Empty;
  216. }
  217. // Strip any information we don't want to reveal
  218. msg = msg.Replace(_config.ApplicationPaths.ProgramSystemPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  219. msg = msg.Replace(_config.ApplicationPaths.ProgramDataPath, string.Empty, StringComparison.OrdinalIgnoreCase);
  220. return msg;
  221. }
  222. /// <summary>
  223. /// Shut down the Web Service
  224. /// </summary>
  225. public void Stop()
  226. {
  227. List<IWebSocketConnection> connections;
  228. lock (_webSocketConnections)
  229. {
  230. connections = _webSocketConnections.ToList();
  231. _webSocketConnections.Clear();
  232. }
  233. foreach (var connection in connections)
  234. {
  235. try
  236. {
  237. connection.Dispose();
  238. }
  239. catch (Exception ex)
  240. {
  241. _logger.LogError(ex, "Error disposing connection");
  242. }
  243. }
  244. }
  245. public static string RemoveQueryStringByKey(string url, string key)
  246. {
  247. var uri = new Uri(url);
  248. // this gets all the query string key value pairs as a collection
  249. var newQueryString = QueryHelpers.ParseQuery(uri.Query);
  250. var originalCount = newQueryString.Count;
  251. if (originalCount == 0)
  252. {
  253. return url;
  254. }
  255. // this removes the key if exists
  256. newQueryString.Remove(key);
  257. if (originalCount == newQueryString.Count)
  258. {
  259. return url;
  260. }
  261. // this gets the page path from root without QueryString
  262. string pagePathWithoutQueryString = url.Split(new[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0];
  263. return newQueryString.Count > 0
  264. ? QueryHelpers.AddQueryString(pagePathWithoutQueryString, newQueryString.ToDictionary(kv => kv.Key, kv => kv.Value.ToString()))
  265. : pagePathWithoutQueryString;
  266. }
  267. private static string GetUrlToLog(string url)
  268. {
  269. url = RemoveQueryStringByKey(url, "api_key");
  270. return url;
  271. }
  272. private static string NormalizeConfiguredLocalAddress(string address)
  273. {
  274. var add = address.AsSpan().Trim('/');
  275. int index = add.IndexOf('/');
  276. if (index != -1)
  277. {
  278. add = add.Slice(index + 1);
  279. }
  280. return add.TrimStart('/').ToString();
  281. }
  282. private bool ValidateHost(string host)
  283. {
  284. var hosts = _config
  285. .Configuration
  286. .LocalNetworkAddresses
  287. .Select(NormalizeConfiguredLocalAddress)
  288. .ToList();
  289. if (hosts.Count == 0)
  290. {
  291. return true;
  292. }
  293. host = host ?? string.Empty;
  294. if (_networkManager.IsInPrivateAddressSpace(host))
  295. {
  296. hosts.Add("localhost");
  297. hosts.Add("127.0.0.1");
  298. return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
  299. }
  300. return true;
  301. }
  302. private bool ValidateRequest(string remoteIp, bool isLocal)
  303. {
  304. if (isLocal)
  305. {
  306. return true;
  307. }
  308. if (_config.Configuration.EnableRemoteAccess)
  309. {
  310. var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
  311. if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
  312. {
  313. if (_config.Configuration.IsRemoteIPFilterBlacklist)
  314. {
  315. return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  316. }
  317. else
  318. {
  319. return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
  320. }
  321. }
  322. }
  323. else
  324. {
  325. if (!_networkManager.IsInLocalNetwork(remoteIp))
  326. {
  327. return false;
  328. }
  329. }
  330. return true;
  331. }
  332. private bool ValidateSsl(string remoteIp, string urlString)
  333. {
  334. if (_config.Configuration.RequireHttps && _appHost.EnableHttps && !_config.Configuration.IsBehindProxy)
  335. {
  336. if (urlString.IndexOf("https://", StringComparison.OrdinalIgnoreCase) == -1)
  337. {
  338. // These are hacks, but if these ever occur on ipv6 in the local network they could be incorrectly redirected
  339. if (urlString.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) != -1
  340. || urlString.IndexOf("dlna/", StringComparison.OrdinalIgnoreCase) != -1)
  341. {
  342. return true;
  343. }
  344. if (!_networkManager.IsInLocalNetwork(remoteIp))
  345. {
  346. return false;
  347. }
  348. }
  349. }
  350. return true;
  351. }
  352. /// <summary>
  353. /// Overridable method that can be used to implement a custom hnandler
  354. /// </summary>
  355. public async Task RequestHandler(IHttpRequest httpReq, string urlString, string host, string localPath, CancellationToken cancellationToken)
  356. {
  357. var stopWatch = new Stopwatch();
  358. stopWatch.Start();
  359. var httpRes = httpReq.Response;
  360. string urlToLog = null;
  361. string remoteIp = httpReq.RemoteIp;
  362. try
  363. {
  364. if (_disposed)
  365. {
  366. httpRes.StatusCode = 503;
  367. httpRes.ContentType = "text/plain";
  368. await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
  369. return;
  370. }
  371. if (!ValidateHost(host))
  372. {
  373. httpRes.StatusCode = 400;
  374. httpRes.ContentType = "text/plain";
  375. await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
  376. return;
  377. }
  378. if (!ValidateRequest(remoteIp, httpReq.IsLocal))
  379. {
  380. httpRes.StatusCode = 403;
  381. httpRes.ContentType = "text/plain";
  382. await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
  383. return;
  384. }
  385. if (!ValidateSsl(httpReq.RemoteIp, urlString))
  386. {
  387. RedirectToSecureUrl(httpReq, httpRes, urlString);
  388. return;
  389. }
  390. if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase))
  391. {
  392. httpRes.StatusCode = 200;
  393. httpRes.Headers.Add("Access-Control-Allow-Origin", "*");
  394. httpRes.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
  395. httpRes.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization");
  396. httpRes.ContentType = "text/plain";
  397. await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
  398. return;
  399. }
  400. urlToLog = GetUrlToLog(urlString);
  401. if (string.Equals(localPath, "/" + _config.Configuration.BaseUrl + "/", StringComparison.OrdinalIgnoreCase)
  402. || string.Equals(localPath, "/" + _config.Configuration.BaseUrl, StringComparison.OrdinalIgnoreCase))
  403. {
  404. httpRes.Redirect("/" + _config.Configuration.BaseUrl + "/" + _defaultRedirectPath);
  405. return;
  406. }
  407. if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase))
  408. {
  409. httpRes.Redirect(_defaultRedirectPath);
  410. return;
  411. }
  412. if (string.IsNullOrEmpty(localPath))
  413. {
  414. httpRes.Redirect("/" + _defaultRedirectPath);
  415. return;
  416. }
  417. if (!string.IsNullOrEmpty(GlobalResponse))
  418. {
  419. // We don't want the address pings in ApplicationHost to fail
  420. if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
  421. {
  422. httpRes.StatusCode = 503;
  423. httpRes.ContentType = "text/html";
  424. await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
  425. return;
  426. }
  427. }
  428. var handler = GetServiceHandler(httpReq);
  429. if (handler != null)
  430. {
  431. await handler.ProcessRequestAsync(this, httpReq, httpRes, _logger, cancellationToken).ConfigureAwait(false);
  432. }
  433. else
  434. {
  435. await ErrorHandler(new FileNotFoundException(), httpReq, false).ConfigureAwait(false);
  436. }
  437. }
  438. catch (Exception ex) when (ex is SocketException || ex is IOException || ex is OperationCanceledException)
  439. {
  440. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  441. }
  442. catch (SecurityException ex)
  443. {
  444. await ErrorHandler(ex, httpReq, false).ConfigureAwait(false);
  445. }
  446. catch (Exception ex)
  447. {
  448. var logException = !string.Equals(ex.GetType().Name, "SocketException", StringComparison.OrdinalIgnoreCase);
  449. await ErrorHandler(ex, httpReq, logException).ConfigureAwait(false);
  450. }
  451. finally
  452. {
  453. stopWatch.Stop();
  454. var elapsed = stopWatch.Elapsed;
  455. if (elapsed.TotalMilliseconds > 500)
  456. {
  457. _logger.LogWarning("HTTP Response {StatusCode} to {RemoteIp}. Time (slow): {Elapsed:g}. {Url}", httpRes.StatusCode, remoteIp, elapsed, urlToLog);
  458. }
  459. }
  460. }
  461. // Entry point for HttpListener
  462. public ServiceHandler GetServiceHandler(IHttpRequest httpReq)
  463. {
  464. var pathInfo = httpReq.PathInfo;
  465. pathInfo = ServiceHandler.GetSanitizedPathInfo(pathInfo, out string contentType);
  466. var restPath = ServiceController.GetRestPathForRequest(httpReq.HttpMethod, pathInfo);
  467. if (restPath != null)
  468. {
  469. return new ServiceHandler(restPath, contentType);
  470. }
  471. _logger.LogError("Could not find handler for {PathInfo}", pathInfo);
  472. return null;
  473. }
  474. private void RedirectToSecureUrl(IHttpRequest httpReq, HttpResponse httpRes, string url)
  475. {
  476. if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
  477. {
  478. var builder = new UriBuilder(uri)
  479. {
  480. Port = _config.Configuration.PublicHttpsPort,
  481. Scheme = "https"
  482. };
  483. url = builder.Uri.ToString();
  484. }
  485. httpRes.Redirect(url);
  486. }
  487. /// <summary>
  488. /// Adds the rest handlers.
  489. /// </summary>
  490. /// <param name="services">The services.</param>
  491. /// <param name="listeners"></param>
  492. /// <param name="urlPrefixes"></param>
  493. public void Init(IEnumerable<IService> services, IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
  494. {
  495. _webSocketListeners = listeners.ToArray();
  496. UrlPrefixes = urlPrefixes.ToArray();
  497. ServiceController = new ServiceController();
  498. var types = services.Select(r => r.GetType());
  499. ServiceController.Init(this, types);
  500. ResponseFilters = new Action<IRequest, HttpResponse, object>[]
  501. {
  502. new ResponseFilter(_logger).FilterResponse
  503. };
  504. }
  505. public RouteAttribute[] GetRouteAttributes(Type requestType)
  506. {
  507. var routes = requestType.GetTypeInfo().GetCustomAttributes<RouteAttribute>(true).ToList();
  508. var clone = routes.ToList();
  509. foreach (var route in clone)
  510. {
  511. routes.Add(new RouteAttribute(NormalizeCustomRoutePath(_config.Configuration.BaseUrl, route.Path), route.Verbs)
  512. {
  513. Notes = route.Notes,
  514. Priority = route.Priority,
  515. Summary = route.Summary
  516. });
  517. routes.Add(new RouteAttribute(NormalizeEmbyRoutePath(route.Path), route.Verbs)
  518. {
  519. Notes = route.Notes,
  520. Priority = route.Priority,
  521. Summary = route.Summary
  522. });
  523. routes.Add(new RouteAttribute(NormalizeMediaBrowserRoutePath(route.Path), route.Verbs)
  524. {
  525. Notes = route.Notes,
  526. Priority = route.Priority,
  527. Summary = route.Summary
  528. });
  529. }
  530. return routes.ToArray();
  531. }
  532. public Func<string, object> GetParseFn(Type propertyType)
  533. {
  534. return _funcParseFn(propertyType);
  535. }
  536. public void SerializeToJson(object o, Stream stream)
  537. {
  538. _jsonSerializer.SerializeToStream(o, stream);
  539. }
  540. public void SerializeToXml(object o, Stream stream)
  541. {
  542. _xmlSerializer.SerializeToStream(o, stream);
  543. }
  544. public Task<object> DeserializeXml(Type type, Stream stream)
  545. {
  546. return Task.FromResult(_xmlSerializer.DeserializeFromStream(type, stream));
  547. }
  548. public Task<object> DeserializeJson(Type type, Stream stream)
  549. {
  550. return _jsonSerializer.DeserializeFromStreamAsync(stream, type);
  551. }
  552. public Task ProcessWebSocketRequest(HttpContext context)
  553. {
  554. return _socketListener.ProcessWebSocketRequest(context);
  555. }
  556. // this method was left for compatibility with third party clients
  557. private static string NormalizeEmbyRoutePath(string path)
  558. {
  559. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  560. {
  561. return "/emby" + path;
  562. }
  563. return "emby/" + path;
  564. }
  565. // this method was left for compatibility with third party clients
  566. private static string NormalizeMediaBrowserRoutePath(string path)
  567. {
  568. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  569. {
  570. return "/mediabrowser" + path;
  571. }
  572. return "mediabrowser/" + path;
  573. }
  574. private static string NormalizeCustomRoutePath(string baseUrl, string path)
  575. {
  576. if (path.StartsWith("/", StringComparison.OrdinalIgnoreCase))
  577. {
  578. return "/" + baseUrl + path;
  579. }
  580. return baseUrl + "/" + path;
  581. }
  582. /// <inheritdoc />
  583. public void Dispose()
  584. {
  585. Dispose(true);
  586. GC.SuppressFinalize(this);
  587. }
  588. protected virtual void Dispose(bool disposing)
  589. {
  590. if (_disposed) return;
  591. if (disposing)
  592. {
  593. Stop();
  594. }
  595. _disposed = true;
  596. }
  597. /// <summary>
  598. /// Processes the web socket message received.
  599. /// </summary>
  600. /// <param name="result">The result.</param>
  601. private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
  602. {
  603. if (_disposed)
  604. {
  605. return Task.CompletedTask;
  606. }
  607. _logger.LogDebug("Websocket message received: {0}", result.MessageType);
  608. IEnumerable<Task> GetTasks()
  609. {
  610. foreach (var x in _webSocketListeners)
  611. {
  612. yield return x.ProcessMessageAsync(result);
  613. }
  614. }
  615. return Task.WhenAll(GetTasks());
  616. }
  617. }
  618. }