2
0

HttpClientManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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(options.RequestContent);
  261. }
  262. else
  263. {
  264. httpWebRequest.Content = new ByteArrayContent(Array.Empty<byte>());
  265. }
  266. // TODO: add correct content type
  267. /*
  268. var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  269. if (options.AppendCharsetToMimeType)
  270. {
  271. contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\"";
  272. }
  273. httpWebRequest.Headers.Add(HeaderNames.ContentType, contentType);*/
  274. }
  275. if (options.LogRequest)
  276. {
  277. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
  278. }
  279. options.CancellationToken.ThrowIfCancellationRequested();
  280. if (!options.BufferContent)
  281. {
  282. var response = await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false);
  283. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  284. options.CancellationToken.ThrowIfCancellationRequested();
  285. var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  286. return new HttpResponseInfo(response.Headers)
  287. {
  288. Content = stream,
  289. StatusCode = response.StatusCode,
  290. ContentType = response.Content.Headers.ContentType?.MediaType,
  291. ContentLength = stream.Length,
  292. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  293. };
  294. }
  295. using (var response = await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false))
  296. {
  297. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  298. options.CancellationToken.ThrowIfCancellationRequested();
  299. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  300. {
  301. var memoryStream = new MemoryStream();
  302. await stream.CopyToAsync(memoryStream, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  303. memoryStream.Position = 0;
  304. return new HttpResponseInfo(response.Headers)
  305. {
  306. Content = memoryStream,
  307. StatusCode = response.StatusCode,
  308. ContentType = response.Content.Headers.ContentType?.MediaType,
  309. ContentLength = memoryStream.Length,
  310. ResponseUrl = response.Content.Headers.ContentLocation?.ToString()
  311. };
  312. }
  313. }
  314. }
  315. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  316. => SendAsync(options, HttpMethod.Post);
  317. /// <summary>
  318. /// Downloads the contents of a given url into a temporary location
  319. /// </summary>
  320. /// <param name="options">The options.</param>
  321. /// <returns>Task{System.String}.</returns>
  322. public async Task<string> GetTempFile(HttpRequestOptions options)
  323. {
  324. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  325. return response.TempFilePath;
  326. }
  327. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  328. {
  329. ValidateParams(options);
  330. Directory.CreateDirectory(_appPaths.TempDirectory);
  331. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  332. if (options.Progress == null)
  333. {
  334. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  335. }
  336. options.CancellationToken.ThrowIfCancellationRequested();
  337. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  338. options.Progress.Report(0);
  339. if (options.LogRequest)
  340. {
  341. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  342. }
  343. var client = GetHttpClient(options.Url);
  344. try
  345. {
  346. options.CancellationToken.ThrowIfCancellationRequested();
  347. using (var response = (await client.SendAsync(httpWebRequest, options.CancellationToken).ConfigureAwait(false)))
  348. {
  349. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  350. options.CancellationToken.ThrowIfCancellationRequested();
  351. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  352. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  353. {
  354. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  355. }
  356. options.Progress.Report(100);
  357. var responseInfo = new HttpResponseInfo(response.Headers)
  358. {
  359. TempFilePath = tempFile,
  360. StatusCode = response.StatusCode,
  361. ContentType = response.Content.Headers.ContentType?.MediaType,
  362. ContentLength = response.Content.Headers.ContentLength
  363. };
  364. return responseInfo;
  365. }
  366. }
  367. catch (Exception ex)
  368. {
  369. if (File.Exists(tempFile))
  370. {
  371. File.Delete(tempFile);
  372. }
  373. throw GetException(ex, options);
  374. }
  375. }
  376. private Exception GetException(Exception ex, HttpRequestOptions options)
  377. {
  378. if (ex is HttpException)
  379. {
  380. return ex;
  381. }
  382. var webException = ex as WebException
  383. ?? ex.InnerException as WebException;
  384. if (webException != null)
  385. {
  386. if (options.LogErrors)
  387. {
  388. _logger.LogError(webException, "Error {Status} getting response from {Url}", webException.Status, options.Url);
  389. }
  390. var exception = new HttpException(webException.Message, webException);
  391. using (var response = webException.Response as HttpWebResponse)
  392. {
  393. if (response != null)
  394. {
  395. exception.StatusCode = response.StatusCode;
  396. }
  397. }
  398. if (!exception.StatusCode.HasValue)
  399. {
  400. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  401. webException.Status == WebExceptionStatus.ConnectFailure)
  402. {
  403. exception.IsTimedOut = true;
  404. }
  405. }
  406. return exception;
  407. }
  408. var operationCanceledException = ex as OperationCanceledException
  409. ?? ex.InnerException as OperationCanceledException;
  410. if (operationCanceledException != null)
  411. {
  412. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  413. }
  414. if (options.LogErrors)
  415. {
  416. _logger.LogError(ex, "Error getting response from {Url}", options.Url);
  417. }
  418. return ex;
  419. }
  420. private void ValidateParams(HttpRequestOptions options)
  421. {
  422. if (string.IsNullOrEmpty(options.Url))
  423. {
  424. throw new ArgumentNullException(nameof(options));
  425. }
  426. }
  427. /// <summary>
  428. /// Gets the host from URL.
  429. /// </summary>
  430. /// <param name="url">The URL.</param>
  431. /// <returns>System.String.</returns>
  432. private static string GetHostFromUrl(string url)
  433. {
  434. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  435. if (index != -1)
  436. {
  437. url = url.Substring(index + 3);
  438. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  439. if (!string.IsNullOrWhiteSpace(host))
  440. {
  441. return host;
  442. }
  443. }
  444. return url;
  445. }
  446. /// <summary>
  447. /// Throws the cancellation exception.
  448. /// </summary>
  449. /// <param name="options">The options.</param>
  450. /// <param name="cancellationToken">The cancellation token.</param>
  451. /// <param name="exception">The exception.</param>
  452. /// <returns>Exception.</returns>
  453. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  454. {
  455. // If the HttpClient's timeout is reached, it will cancel the Task internally
  456. if (!cancellationToken.IsCancellationRequested)
  457. {
  458. var msg = string.Format("Connection to {0} timed out", options.Url);
  459. if (options.LogErrors)
  460. {
  461. _logger.LogError(msg);
  462. }
  463. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  464. return new HttpException(msg, exception)
  465. {
  466. IsTimedOut = true
  467. };
  468. }
  469. return exception;
  470. }
  471. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  472. {
  473. if (response.IsSuccessStatusCode)
  474. {
  475. return;
  476. }
  477. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  478. _logger.LogError("HTTP request failed with message: {Message}", msg);
  479. throw new HttpException(response.ReasonPhrase)
  480. {
  481. StatusCode = response.StatusCode
  482. };
  483. }
  484. }
  485. }