2
0

HttpListenerHost.cs 25 KB

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