HttpClientManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. => SendAsync(options, new HttpMethod(httpMethod));
  159. /// <summary>
  160. /// send as an asynchronous operation.
  161. /// </summary>
  162. /// <param name="options">The options.</param>
  163. /// <param name="httpMethod">The HTTP method.</param>
  164. /// <returns>Task{HttpResponseInfo}.</returns>
  165. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
  166. {
  167. if (options.CacheMode == CacheMode.None)
  168. {
  169. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  170. }
  171. var url = options.Url;
  172. var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
  173. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  174. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  175. if (response != null)
  176. {
  177. return response;
  178. }
  179. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  180. if (response.StatusCode == HttpStatusCode.OK)
  181. {
  182. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  183. }
  184. return response;
  185. }
  186. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  187. {
  188. if (File.Exists(responseCachePath)
  189. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  190. {
  191. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  192. return new HttpResponseInfo
  193. {
  194. ResponseUrl = url,
  195. Content = stream,
  196. StatusCode = HttpStatusCode.OK,
  197. ContentLength = stream.Length
  198. };
  199. }
  200. return null;
  201. }
  202. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  203. {
  204. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  205. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  206. {
  207. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  208. response.Content.Position = 0;
  209. }
  210. }
  211. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
  212. {
  213. ValidateParams(options);
  214. options.CancellationToken.ThrowIfCancellationRequested();
  215. var client = GetHttpClient(options.Url);
  216. var httpWebRequest = GetRequestMessage(options, httpMethod);
  217. if (options.RequestContentBytes != null
  218. || !string.IsNullOrEmpty(options.RequestContent)
  219. || httpMethod == HttpMethod.Post)
  220. {
  221. if (options.RequestContentBytes != null)
  222. {
  223. httpWebRequest.Content = new ByteArrayContent(options.RequestContentBytes);
  224. }
  225. else if (options.RequestContent != null)
  226. {
  227. httpWebRequest.Content = new StringContent(
  228. options.RequestContent,
  229. null,
  230. options.RequestContentType);
  231. }
  232. else
  233. {
  234. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  235. }
  236. }
  237. if (options.LogRequest)
  238. {
  239. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
  240. }
  241. options.CancellationToken.ThrowIfCancellationRequested();
  242. if (!options.BufferContent)
  243. {
  244. var response = await client.SendAsync(httpWebRequest, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false);
  245. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  246. options.CancellationToken.ThrowIfCancellationRequested();
  247. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  248. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  249. {
  250. Content = stream,
  251. StatusCode = response.StatusCode,
  252. ContentType = response.Content.Headers.ContentType?.MediaType,
  253. ContentLength = response.Content.Headers.ContentLength,
  254. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  255. };
  256. }
  257. using (var response = await client.SendAsync(httpWebRequest, HttpCompletionOption.ResponseHeadersRead, options.CancellationToken).ConfigureAwait(false))
  258. {
  259. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  260. options.CancellationToken.ThrowIfCancellationRequested();
  261. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  262. {
  263. var memoryStream = new MemoryStream();
  264. await stream.CopyToAsync(memoryStream, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  265. memoryStream.Position = 0;
  266. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  267. {
  268. Content = memoryStream,
  269. StatusCode = response.StatusCode,
  270. ContentType = response.Content.Headers.ContentType?.MediaType,
  271. ContentLength = memoryStream.Length,
  272. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  273. };
  274. }
  275. }
  276. }
  277. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  278. => SendAsync(options, HttpMethod.Post);
  279. /// <summary>
  280. /// Downloads the contents of a given url into a temporary location
  281. /// </summary>
  282. /// <param name="options">The options.</param>
  283. /// <returns>Task{System.String}.</returns>
  284. public async Task<string> GetTempFile(HttpRequestOptions options)
  285. {
  286. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  287. return response.TempFilePath;
  288. }
  289. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  290. {
  291. ValidateParams(options);
  292. Directory.CreateDirectory(_appPaths.TempDirectory);
  293. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  294. if (options.Progress == null)
  295. {
  296. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  297. }
  298. options.CancellationToken.ThrowIfCancellationRequested();
  299. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  300. options.Progress.Report(0);
  301. if (options.LogRequest)
  302. {
  303. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  304. }
  305. var client = GetHttpClient(options.Url);
  306. try
  307. {
  308. options.CancellationToken.ThrowIfCancellationRequested();
  309. using (var response = (await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false)))
  310. {
  311. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  312. options.CancellationToken.ThrowIfCancellationRequested();
  313. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  314. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  315. {
  316. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  317. }
  318. options.Progress.Report(100);
  319. var responseInfo = new HttpResponseInfo(response.Headers, response.Content.Headers)
  320. {
  321. TempFilePath = tempFile,
  322. StatusCode = response.StatusCode,
  323. ContentType = response.Content.Headers.ContentType?.MediaType,
  324. ContentLength = response.Content.Headers.ContentLength
  325. };
  326. return responseInfo;
  327. }
  328. }
  329. catch (Exception ex)
  330. {
  331. if (File.Exists(tempFile))
  332. {
  333. File.Delete(tempFile);
  334. }
  335. throw GetException(ex, options);
  336. }
  337. }
  338. private Exception GetException(Exception ex, HttpRequestOptions options)
  339. {
  340. if (ex is HttpException)
  341. {
  342. return ex;
  343. }
  344. var webException = ex as WebException
  345. ?? ex.InnerException as WebException;
  346. if (webException != null)
  347. {
  348. if (options.LogErrors)
  349. {
  350. _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
  351. }
  352. var exception = new HttpException(webException.Message, webException);
  353. using (var response = webException.Response as HttpWebResponse)
  354. {
  355. if (response != null)
  356. {
  357. exception.StatusCode = response.StatusCode;
  358. }
  359. }
  360. if (!exception.StatusCode.HasValue)
  361. {
  362. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  363. webException.Status == WebExceptionStatus.ConnectFailure)
  364. {
  365. exception.IsTimedOut = true;
  366. }
  367. }
  368. return exception;
  369. }
  370. var operationCanceledException = ex as OperationCanceledException
  371. ?? ex.InnerException as OperationCanceledException;
  372. if (operationCanceledException != null)
  373. {
  374. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  375. }
  376. if (options.LogErrors)
  377. {
  378. _logger.LogError(ex, "Error getting response from {Url}", options.Url);
  379. }
  380. return ex;
  381. }
  382. private void ValidateParams(HttpRequestOptions options)
  383. {
  384. if (string.IsNullOrEmpty(options.Url))
  385. {
  386. throw new ArgumentNullException(nameof(options));
  387. }
  388. }
  389. /// <summary>
  390. /// Gets the host from URL.
  391. /// </summary>
  392. /// <param name="url">The URL.</param>
  393. /// <returns>System.String.</returns>
  394. private static string GetHostFromUrl(string url)
  395. {
  396. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  397. if (index != -1)
  398. {
  399. url = url.Substring(index + 3);
  400. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  401. if (!string.IsNullOrWhiteSpace(host))
  402. {
  403. return host;
  404. }
  405. }
  406. return url;
  407. }
  408. /// <summary>
  409. /// Throws the cancellation exception.
  410. /// </summary>
  411. /// <param name="options">The options.</param>
  412. /// <param name="cancellationToken">The cancellation token.</param>
  413. /// <param name="exception">The exception.</param>
  414. /// <returns>Exception.</returns>
  415. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  416. {
  417. // If the HttpClient's timeout is reached, it will cancel the Task internally
  418. if (!cancellationToken.IsCancellationRequested)
  419. {
  420. var msg = string.Format("Connection to {0} timed out", options.Url);
  421. if (options.LogErrors)
  422. {
  423. _logger.LogError(msg);
  424. }
  425. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  426. return new HttpException(msg, exception)
  427. {
  428. IsTimedOut = true
  429. };
  430. }
  431. return exception;
  432. }
  433. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  434. {
  435. if (response.IsSuccessStatusCode)
  436. {
  437. return;
  438. }
  439. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  440. _logger.LogError("HTTP request failed with message: {Message}", msg);
  441. throw new HttpException(response.ReasonPhrase)
  442. {
  443. StatusCode = response.StatusCode
  444. };
  445. }
  446. }
  447. }