HttpClientManager.cs 23 KB

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