HttpClientManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. var response = await client.SendAsync(
  243. httpWebRequest,
  244. options.BufferContent ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
  245. options.CancellationToken).ConfigureAwait(false);
  246. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  247. options.CancellationToken.ThrowIfCancellationRequested();
  248. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  249. return new HttpResponseInfo(response.Headers, response.Content.Headers)
  250. {
  251. Content = stream,
  252. StatusCode = response.StatusCode,
  253. ContentType = response.Content.Headers.ContentType?.MediaType,
  254. ContentLength = response.Content.Headers.ContentLength,
  255. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  256. };
  257. }
  258. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  259. => SendAsync(options, HttpMethod.Post);
  260. /// <summary>
  261. /// Downloads the contents of a given url into a temporary location
  262. /// </summary>
  263. /// <param name="options">The options.</param>
  264. /// <returns>Task{System.String}.</returns>
  265. public async Task<string> GetTempFile(HttpRequestOptions options)
  266. {
  267. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  268. return response.TempFilePath;
  269. }
  270. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  271. {
  272. ValidateParams(options);
  273. Directory.CreateDirectory(_appPaths.TempDirectory);
  274. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  275. if (options.Progress == null)
  276. {
  277. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  278. }
  279. options.CancellationToken.ThrowIfCancellationRequested();
  280. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  281. options.Progress.Report(0);
  282. if (options.LogRequest)
  283. {
  284. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  285. }
  286. var client = GetHttpClient(options.Url);
  287. try
  288. {
  289. options.CancellationToken.ThrowIfCancellationRequested();
  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. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  296. {
  297. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  298. }
  299. options.Progress.Report(100);
  300. var responseInfo = new HttpResponseInfo(response.Headers, response.Content.Headers)
  301. {
  302. TempFilePath = tempFile,
  303. StatusCode = response.StatusCode,
  304. ContentType = response.Content.Headers.ContentType?.MediaType,
  305. ContentLength = response.Content.Headers.ContentLength
  306. };
  307. return responseInfo;
  308. }
  309. }
  310. catch (Exception ex)
  311. {
  312. if (File.Exists(tempFile))
  313. {
  314. File.Delete(tempFile);
  315. }
  316. throw GetException(ex, options);
  317. }
  318. }
  319. private Exception GetException(Exception ex, HttpRequestOptions options)
  320. {
  321. if (ex is HttpException)
  322. {
  323. return ex;
  324. }
  325. var webException = ex as WebException
  326. ?? ex.InnerException as WebException;
  327. if (webException != null)
  328. {
  329. if (options.LogErrors)
  330. {
  331. _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
  332. }
  333. var exception = new HttpException(webException.Message, webException);
  334. using (var response = webException.Response as HttpWebResponse)
  335. {
  336. if (response != null)
  337. {
  338. exception.StatusCode = response.StatusCode;
  339. }
  340. }
  341. if (!exception.StatusCode.HasValue)
  342. {
  343. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  344. webException.Status == WebExceptionStatus.ConnectFailure)
  345. {
  346. exception.IsTimedOut = true;
  347. }
  348. }
  349. return exception;
  350. }
  351. var operationCanceledException = ex as OperationCanceledException
  352. ?? ex.InnerException as OperationCanceledException;
  353. if (operationCanceledException != null)
  354. {
  355. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  356. }
  357. if (options.LogErrors)
  358. {
  359. _logger.LogError(ex, "Error getting response from {Url}", options.Url);
  360. }
  361. return ex;
  362. }
  363. private void ValidateParams(HttpRequestOptions options)
  364. {
  365. if (string.IsNullOrEmpty(options.Url))
  366. {
  367. throw new ArgumentNullException(nameof(options));
  368. }
  369. }
  370. /// <summary>
  371. /// Gets the host from URL.
  372. /// </summary>
  373. /// <param name="url">The URL.</param>
  374. /// <returns>System.String.</returns>
  375. private static string GetHostFromUrl(string url)
  376. {
  377. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  378. if (index != -1)
  379. {
  380. url = url.Substring(index + 3);
  381. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  382. if (!string.IsNullOrWhiteSpace(host))
  383. {
  384. return host;
  385. }
  386. }
  387. return url;
  388. }
  389. /// <summary>
  390. /// Throws the cancellation exception.
  391. /// </summary>
  392. /// <param name="options">The options.</param>
  393. /// <param name="cancellationToken">The cancellation token.</param>
  394. /// <param name="exception">The exception.</param>
  395. /// <returns>Exception.</returns>
  396. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  397. {
  398. // If the HttpClient's timeout is reached, it will cancel the Task internally
  399. if (!cancellationToken.IsCancellationRequested)
  400. {
  401. var msg = string.Format("Connection to {0} timed out", options.Url);
  402. if (options.LogErrors)
  403. {
  404. _logger.LogError(msg);
  405. }
  406. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  407. return new HttpException(msg, exception)
  408. {
  409. IsTimedOut = true
  410. };
  411. }
  412. return exception;
  413. }
  414. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  415. {
  416. if (response.IsSuccessStatusCode)
  417. {
  418. return;
  419. }
  420. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  421. _logger.LogError("HTTP request failed with message: {Message}", msg);
  422. throw new HttpException(response.ReasonPhrase)
  423. {
  424. StatusCode = response.StatusCode
  425. };
  426. }
  427. }
  428. }