2
0

HttpClientManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Net;
  14. using Microsoft.Extensions.Logging;
  15. using Microsoft.Net.Http.Headers;
  16. namespace Emby.Server.Implementations.HttpClientManager
  17. {
  18. /// <summary>
  19. /// Class HttpClientManager
  20. /// </summary>
  21. public class HttpClientManager : IHttpClient
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IApplicationPaths _appPaths;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly Func<string> _defaultUserAgentFn;
  27. /// <summary>
  28. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  29. /// DON'T dispose it after use.
  30. /// </summary>
  31. /// <value>The HTTP clients.</value>
  32. private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  35. /// </summary>
  36. public HttpClientManager(
  37. IApplicationPaths appPaths,
  38. ILogger<HttpClientManager> logger,
  39. IFileSystem fileSystem,
  40. Func<string> defaultUserAgentFn)
  41. {
  42. if (appPaths == null)
  43. {
  44. throw new ArgumentNullException(nameof(appPaths));
  45. }
  46. if (logger == null)
  47. {
  48. throw new ArgumentNullException(nameof(logger));
  49. }
  50. _logger = logger;
  51. _fileSystem = fileSystem;
  52. _appPaths = appPaths;
  53. _defaultUserAgentFn = defaultUserAgentFn;
  54. }
  55. /// <summary>
  56. /// Gets the correct http client for the given url.
  57. /// </summary>
  58. /// <param name="url">The url.</param>
  59. /// <returns>HttpClient.</returns>
  60. private HttpClient GetHttpClient(string url)
  61. {
  62. var key = GetHostFromUrl(url);
  63. if (!_httpClients.TryGetValue(key, out var client))
  64. {
  65. client = new HttpClient()
  66. {
  67. BaseAddress = new Uri(url)
  68. };
  69. _httpClients.TryAdd(key, client);
  70. }
  71. return client;
  72. }
  73. private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
  74. {
  75. string url = options.Url;
  76. var uriAddress = new Uri(url);
  77. string userInfo = uriAddress.UserInfo;
  78. if (!string.IsNullOrWhiteSpace(userInfo))
  79. {
  80. _logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  81. url = url.Replace(userInfo + '@', string.Empty);
  82. }
  83. var request = new HttpRequestMessage(method, url);
  84. AddRequestHeaders(request, options);
  85. switch (options.DecompressionMethod)
  86. {
  87. case CompressionMethod.Deflate | CompressionMethod.Gzip:
  88. request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
  89. break;
  90. case CompressionMethod.Deflate:
  91. request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
  92. break;
  93. case CompressionMethod.Gzip:
  94. request.Headers.Add(HeaderNames.AcceptEncoding, "gzip");
  95. break;
  96. default:
  97. break;
  98. }
  99. if (options.EnableKeepAlive)
  100. {
  101. request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
  102. }
  103. //request.Headers.Add(HeaderNames.CacheControl, "no-cache");
  104. /*
  105. if (!string.IsNullOrWhiteSpace(userInfo))
  106. {
  107. var parts = userInfo.Split(':');
  108. if (parts.Length == 2)
  109. {
  110. request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
  111. }
  112. }
  113. */
  114. return request;
  115. }
  116. private void AddRequestHeaders(HttpRequestMessage request, HttpRequestOptions options)
  117. {
  118. var hasUserAgent = false;
  119. foreach (var header in options.RequestHeaders)
  120. {
  121. if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
  122. {
  123. hasUserAgent = true;
  124. }
  125. request.Headers.Add(header.Key, header.Value);
  126. }
  127. if (!hasUserAgent && options.EnableDefaultUserAgent)
  128. {
  129. request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
  130. }
  131. }
  132. /// <summary>
  133. /// Gets the response internal.
  134. /// </summary>
  135. /// <param name="options">The options.</param>
  136. /// <returns>Task{HttpResponseInfo}.</returns>
  137. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  138. => SendAsync(options, HttpMethod.Get);
  139. /// <summary>
  140. /// Performs a GET request and returns the resulting stream
  141. /// </summary>
  142. /// <param name="options">The options.</param>
  143. /// <returns>Task{Stream}.</returns>
  144. public async Task<Stream> Get(HttpRequestOptions options)
  145. {
  146. var response = await GetResponse(options).ConfigureAwait(false);
  147. return response.Content;
  148. }
  149. /// <summary>
  150. /// send as an asynchronous operation.
  151. /// </summary>
  152. /// <param name="options">The options.</param>
  153. /// <param name="httpMethod">The HTTP method.</param>
  154. /// <returns>Task{HttpResponseInfo}.</returns>
  155. public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  156. {
  157. var httpMethod2 = GetHttpMethod(httpMethod);
  158. return SendAsync(options, httpMethod2);
  159. }
  160. /// <summary>
  161. /// send as an asynchronous operation.
  162. /// </summary>
  163. /// <param name="options">The options.</param>
  164. /// <param name="httpMethod">The HTTP method.</param>
  165. /// <returns>Task{HttpResponseInfo}.</returns>
  166. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  167. {
  168. if (options.CacheMode == CacheMode.None)
  169. {
  170. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  171. }
  172. var url = options.Url;
  173. var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
  174. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  175. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  176. if (response != null)
  177. {
  178. return response;
  179. }
  180. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  181. if (response.StatusCode == HttpStatusCode.OK)
  182. {
  183. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  184. }
  185. return response;
  186. }
  187. private HttpMethod GetHttpMethod(string httpMethod)
  188. {
  189. if (httpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
  190. {
  191. return HttpMethod.Delete;
  192. }
  193. else if (httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
  194. {
  195. return HttpMethod.Get;
  196. }
  197. else if (httpMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
  198. {
  199. return HttpMethod.Head;
  200. }
  201. else if (httpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
  202. {
  203. return HttpMethod.Options;
  204. }
  205. else if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
  206. {
  207. return HttpMethod.Post;
  208. }
  209. else if (httpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
  210. {
  211. return HttpMethod.Put;
  212. }
  213. else if (httpMethod.Equals("TRACE", StringComparison.OrdinalIgnoreCase))
  214. {
  215. return HttpMethod.Trace;
  216. }
  217. throw new ArgumentException("Invalid HTTP method", nameof(httpMethod));
  218. }
  219. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  220. {
  221. if (File.Exists(responseCachePath)
  222. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  223. {
  224. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  225. return new HttpResponseInfo
  226. {
  227. ResponseUrl = url,
  228. Content = stream,
  229. StatusCode = HttpStatusCode.OK,
  230. ContentLength = stream.Length
  231. };
  232. }
  233. return null;
  234. }
  235. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  236. {
  237. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  238. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  239. {
  240. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  241. response.Content.Position = 0;
  242. }
  243. }
  244. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  245. {
  246. ValidateParams(options);
  247. options.CancellationToken.ThrowIfCancellationRequested();
  248. var client = GetHttpClient(options.Url);
  249. var httpWebRequest = GetRequestMessage(options, httpMethod);
  250. if (options.RequestContentBytes != null
  251. || !string.IsNullOrEmpty(options.RequestContent)
  252. || httpMethod == HttpMethod.Post)
  253. {
  254. if (options.RequestContentBytes != null)
  255. {
  256. httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
  257. }
  258. else if (options.RequestContent != null)
  259. {
  260. httpWebRequest.Content = new StringContent(
  261. options.RequestContent,
  262. null,
  263. options.RequestContentType);
  264. }
  265. else
  266. {
  267. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  268. }
  269. }
  270. if (options.LogRequest)
  271. {
  272. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
  273. }
  274. options.CancellationToken.ThrowIfCancellationRequested();
  275. if (!options.BufferContent)
  276. {
  277. var response = await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false);
  278. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  279. options.CancellationToken.ThrowIfCancellationRequested();
  280. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  281. return new HttpResponseInfo(response.Headers)
  282. {
  283. Content = stream,
  284. StatusCode = response.StatusCode,
  285. ContentType = response.Content.Headers.ContentType?.MediaType,
  286. ContentLength = stream.Length,
  287. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  288. };
  289. }
  290. using (var response = await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false))
  291. {
  292. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  293. options.CancellationToken.ThrowIfCancellationRequested();
  294. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  295. {
  296. var memoryStream = new MemoryStream();
  297. await stream.CopyToAsync(memoryStream, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  298. memoryStream.Position = 0;
  299. return new HttpResponseInfo(response.Headers)
  300. {
  301. Content = memoryStream,
  302. StatusCode = response.StatusCode,
  303. ContentType = response.Content.Headers.ContentType?.MediaType,
  304. ContentLength = memoryStream.Length,
  305. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  306. };
  307. }
  308. }
  309. }
  310. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  311. => SendAsync(options, HttpMethod.Post);
  312. /// <summary>
  313. /// Downloads the contents of a given url into a temporary location
  314. /// </summary>
  315. /// <param name="options">The options.</param>
  316. /// <returns>Task{System.String}.</returns>
  317. public async Task<string> GetTempFile(HttpRequestOptions options)
  318. {
  319. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  320. return response.TempFilePath;
  321. }
  322. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  323. {
  324. ValidateParams(options);
  325. Directory.CreateDirectory(_appPaths.TempDirectory);
  326. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  327. if (options.Progress == null)
  328. {
  329. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  330. }
  331. options.CancellationToken.ThrowIfCancellationRequested();
  332. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  333. options.Progress.Report(0);
  334. if (options.LogRequest)
  335. {
  336. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  337. }
  338. var client = GetHttpClient(options.Url);
  339. try
  340. {
  341. options.CancellationToken.ThrowIfCancellationRequested();
  342. using (var response = (await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false)))
  343. {
  344. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  345. options.CancellationToken.ThrowIfCancellationRequested();
  346. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  347. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  348. {
  349. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  350. }
  351. options.Progress.Report(100);
  352. var responseInfo = new HttpResponseInfo(response.Headers)
  353. {
  354. TempFilePath = tempFile,
  355. StatusCode = response.StatusCode,
  356. ContentType = response.Content.Headers.ContentType?.MediaType,
  357. ContentLength = response.Content.Headers.ContentLength
  358. };
  359. return responseInfo;
  360. }
  361. }
  362. catch (Exception ex)
  363. {
  364. if (File.Exists(tempFile))
  365. {
  366. File.Delete(tempFile);
  367. }
  368. throw GetException(ex, options);
  369. }
  370. }
  371. private Exception GetException(Exception ex, HttpRequestOptions options)
  372. {
  373. if (ex is HttpException)
  374. {
  375. return ex;
  376. }
  377. var webException = ex as WebException
  378. ?? ex.InnerException as WebException;
  379. if (webException != null)
  380. {
  381. if (options.LogErrors)
  382. {
  383. _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
  384. }
  385. var exception = new HttpException(webException.Message, webException);
  386. using (var response = webException.Response as HttpWebResponse)
  387. {
  388. if (response != null)
  389. {
  390. exception.StatusCode = response.StatusCode;
  391. }
  392. }
  393. if (!exception.StatusCode.HasValue)
  394. {
  395. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  396. webException.Status == WebExceptionStatus.ConnectFailure)
  397. {
  398. exception.IsTimedOut = true;
  399. }
  400. }
  401. return exception;
  402. }
  403. var operationCanceledException = ex as OperationCanceledException
  404. ?? ex.InnerException as OperationCanceledException;
  405. if (operationCanceledException != null)
  406. {
  407. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  408. }
  409. if (options.LogErrors)
  410. {
  411. _logger.LogError(ex, "Error getting response from {Url}", options.Url);
  412. }
  413. return ex;
  414. }
  415. private void ValidateParams(HttpRequestOptions options)
  416. {
  417. if (string.IsNullOrEmpty(options.Url))
  418. {
  419. throw new ArgumentNullException(nameof(options));
  420. }
  421. }
  422. /// <summary>
  423. /// Gets the host from URL.
  424. /// </summary>
  425. /// <param name="url">The URL.</param>
  426. /// <returns>System.String.</returns>
  427. private static string GetHostFromUrl(string url)
  428. {
  429. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  430. if (index != -1)
  431. {
  432. url = url.Substring(index + 3);
  433. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  434. if (!string.IsNullOrWhiteSpace(host))
  435. {
  436. return host;
  437. }
  438. }
  439. return url;
  440. }
  441. /// <summary>
  442. /// Throws the cancellation exception.
  443. /// </summary>
  444. /// <param name="options">The options.</param>
  445. /// <param name="cancellationToken">The cancellation token.</param>
  446. /// <param name="exception">The exception.</param>
  447. /// <returns>Exception.</returns>
  448. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  449. {
  450. // If the HttpClient's timeout is reached, it will cancel the Task internally
  451. if (!cancellationToken.IsCancellationRequested)
  452. {
  453. var msg = string.Format("Connection to {0} timed out", options.Url);
  454. if (options.LogErrors)
  455. {
  456. _logger.LogError(msg);
  457. }
  458. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  459. return new HttpException(msg, exception)
  460. {
  461. IsTimedOut = true
  462. };
  463. }
  464. return exception;
  465. }
  466. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  467. {
  468. if (response.IsSuccessStatusCode)
  469. {
  470. return;
  471. }
  472. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  473. _logger.LogError("HTTP request failed with message: {Message}", msg);
  474. throw new HttpException(response.ReasonPhrase)
  475. {
  476. StatusCode = response.StatusCode
  477. };
  478. }
  479. }
  480. }