HttpClientManager.cs 21 KB

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