HttpClientManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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.LogRequest)
  300. {
  301. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
  302. }
  303. try
  304. {
  305. options.CancellationToken.ThrowIfCancellationRequested();
  306. /*if (!options.BufferContent)
  307. {
  308. var response = await client.HttpClient.SendAsync(httpWebRequest).ConfigureAwait(false);
  309. await EnsureSuccessStatusCode(client, response, options).ConfigureAwait(false);
  310. options.CancellationToken.ThrowIfCancellationRequested();
  311. return GetResponseInfo(response, await response.Content.ReadAsStreamAsync().ConfigureAwait(false), response.Content.Headers.ContentLength, response);
  312. }*/
  313. using (var response = await client.SendAsync(httpWebRequest).ConfigureAwait(false))
  314. {
  315. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  316. options.CancellationToken.ThrowIfCancellationRequested();
  317. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  318. {
  319. var memoryStream = new MemoryStream();
  320. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  321. memoryStream.Position = 0;
  322. return GetResponseInfo(response, memoryStream, memoryStream.Length, null);
  323. }
  324. }
  325. }
  326. catch (OperationCanceledException ex)
  327. {
  328. throw GetCancellationException(options, options.CancellationToken, ex);
  329. }
  330. }
  331. private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, Stream content, long? contentLength, IDisposable disposable)
  332. {
  333. var responseInfo = new HttpResponseInfo(disposable)
  334. {
  335. Content = content,
  336. StatusCode = httpResponse.StatusCode,
  337. ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
  338. ContentLength = contentLength,
  339. ResponseUrl = httpResponse.Content.Headers.ContentLocation?.ToString()
  340. };
  341. if (httpResponse.Headers != null)
  342. {
  343. SetHeaders(httpResponse.Content.Headers, responseInfo);
  344. }
  345. return responseInfo;
  346. }
  347. private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, string tempFile, long? contentLength)
  348. {
  349. var responseInfo = new HttpResponseInfo
  350. {
  351. TempFilePath = tempFile,
  352. StatusCode = httpResponse.StatusCode,
  353. ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
  354. ContentLength = contentLength
  355. };
  356. if (httpResponse.Headers != null)
  357. {
  358. SetHeaders(httpResponse.Content.Headers, responseInfo);
  359. }
  360. return responseInfo;
  361. }
  362. private static void SetHeaders(HttpContentHeaders headers, HttpResponseInfo responseInfo)
  363. {
  364. foreach (var key in headers)
  365. {
  366. responseInfo.Headers[key.Key] = string.Join(", ", key.Value);
  367. }
  368. }
  369. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  370. {
  371. return SendAsync(options, HttpMethod.Post);
  372. }
  373. /// <summary>
  374. /// Downloads the contents of a given url into a temporary location
  375. /// </summary>
  376. /// <param name="options">The options.</param>
  377. /// <returns>Task{System.String}.</returns>
  378. public async Task<string> GetTempFile(HttpRequestOptions options)
  379. {
  380. using (var response = await GetTempFileResponse(options).ConfigureAwait(false))
  381. {
  382. return response.TempFilePath;
  383. }
  384. }
  385. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  386. {
  387. ValidateParams(options);
  388. Directory.CreateDirectory(_appPaths.TempDirectory);
  389. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  390. if (options.Progress == null)
  391. {
  392. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  393. }
  394. options.CancellationToken.ThrowIfCancellationRequested();
  395. var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
  396. options.Progress.Report(0);
  397. if (options.LogRequest)
  398. {
  399. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  400. }
  401. var client = GetHttpClient(options.Url, options.EnableHttpCompression);
  402. try
  403. {
  404. options.CancellationToken.ThrowIfCancellationRequested();
  405. using (var response = (await client.SendAsync(httpWebRequest).ConfigureAwait(false)))
  406. {
  407. await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
  408. options.CancellationToken.ThrowIfCancellationRequested();
  409. using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  410. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  411. {
  412. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  413. }
  414. options.Progress.Report(100);
  415. var contentLength = response.Content.Headers.ContentLength;
  416. return GetResponseInfo(response, tempFile, contentLength);
  417. }
  418. }
  419. catch (Exception ex)
  420. {
  421. if (File.Exists(tempFile))
  422. {
  423. File.Delete(tempFile);
  424. }
  425. throw GetException(ex, options);
  426. }
  427. }
  428. private Exception GetException(Exception ex, HttpRequestOptions options)
  429. {
  430. if (ex is HttpException)
  431. {
  432. return ex;
  433. }
  434. var webException = ex as WebException
  435. ?? ex.InnerException as WebException;
  436. if (webException != null)
  437. {
  438. if (options.LogErrors)
  439. {
  440. _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
  441. }
  442. var exception = new HttpException(webException.Message, webException);
  443. using (var response = webException.Response as HttpWebResponse)
  444. {
  445. if (response != null)
  446. {
  447. exception.StatusCode = response.StatusCode;
  448. }
  449. }
  450. if (!exception.StatusCode.HasValue)
  451. {
  452. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  453. webException.Status == WebExceptionStatus.ConnectFailure)
  454. {
  455. exception.IsTimedOut = true;
  456. }
  457. }
  458. return exception;
  459. }
  460. var operationCanceledException = ex as OperationCanceledException
  461. ?? ex.InnerException as OperationCanceledException;
  462. if (operationCanceledException != null)
  463. {
  464. return GetCancellationException(options, options.CancellationToken, operationCanceledException);
  465. }
  466. if (options.LogErrors)
  467. {
  468. _logger.LogError(ex, "Error getting response from {url}", options.Url);
  469. }
  470. return ex;
  471. }
  472. private void ValidateParams(HttpRequestOptions options)
  473. {
  474. if (string.IsNullOrEmpty(options.Url))
  475. {
  476. throw new ArgumentNullException(nameof(options));
  477. }
  478. }
  479. /// <summary>
  480. /// Gets the host from URL.
  481. /// </summary>
  482. /// <param name="url">The URL.</param>
  483. /// <returns>System.String.</returns>
  484. private static string GetHostFromUrl(string url)
  485. {
  486. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  487. if (index != -1)
  488. {
  489. url = url.Substring(index + 3);
  490. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  491. if (!string.IsNullOrWhiteSpace(host))
  492. {
  493. return host;
  494. }
  495. }
  496. return url;
  497. }
  498. /// <summary>
  499. /// Throws the cancellation exception.
  500. /// </summary>
  501. /// <param name="options">The options.</param>
  502. /// <param name="cancellationToken">The cancellation token.</param>
  503. /// <param name="exception">The exception.</param>
  504. /// <returns>Exception.</returns>
  505. private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
  506. {
  507. // If the HttpClient's timeout is reached, it will cancel the Task internally
  508. if (!cancellationToken.IsCancellationRequested)
  509. {
  510. var msg = string.Format("Connection to {0} timed out", options.Url);
  511. if (options.LogErrors)
  512. {
  513. _logger.LogError(msg);
  514. }
  515. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  516. return new HttpException(msg, exception)
  517. {
  518. IsTimedOut = true
  519. };
  520. }
  521. return exception;
  522. }
  523. private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
  524. {
  525. if (response.IsSuccessStatusCode)
  526. {
  527. return;
  528. }
  529. var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  530. _logger.LogError(msg);
  531. throw new HttpException(response.ReasonPhrase)
  532. {
  533. StatusCode = response.StatusCode
  534. };
  535. }
  536. }
  537. }