HttpClientManager.cs 18 KB

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