HttpClientManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Net.Cache;
  14. using System.Net.Http;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Common.Implementations.HttpClientManager
  20. {
  21. /// <summary>
  22. /// Class HttpClientManager
  23. /// </summary>
  24. public class HttpClientManager : IHttpClient
  25. {
  26. /// <summary>
  27. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  28. /// </summary>
  29. private const int TimeoutSeconds = 30;
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _app paths
  36. /// </summary>
  37. private readonly IApplicationPaths _appPaths;
  38. private readonly IFileSystem _fileSystem;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  41. /// </summary>
  42. /// <param name="appPaths">The app paths.</param>
  43. /// <param name="logger">The logger.</param>
  44. /// <param name="fileSystem">The file system.</param>
  45. /// <exception cref="System.ArgumentNullException">appPaths
  46. /// or
  47. /// logger</exception>
  48. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  49. {
  50. if (appPaths == null)
  51. {
  52. throw new ArgumentNullException("appPaths");
  53. }
  54. if (logger == null)
  55. {
  56. throw new ArgumentNullException("logger");
  57. }
  58. _logger = logger;
  59. _fileSystem = fileSystem;
  60. _appPaths = appPaths;
  61. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  62. ServicePointManager.Expect100Continue = false;
  63. }
  64. /// <summary>
  65. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  66. /// DON'T dispose it after use.
  67. /// </summary>
  68. /// <value>The HTTP clients.</value>
  69. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  70. /// <summary>
  71. /// Gets
  72. /// </summary>
  73. /// <param name="host">The host.</param>
  74. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  75. /// <returns>HttpClient.</returns>
  76. /// <exception cref="System.ArgumentNullException">host</exception>
  77. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  78. {
  79. if (string.IsNullOrEmpty(host))
  80. {
  81. throw new ArgumentNullException("host");
  82. }
  83. HttpClientInfo client;
  84. var key = host + enableHttpCompression;
  85. if (!_httpClients.TryGetValue(key, out client))
  86. {
  87. client = new HttpClientInfo();
  88. _httpClients.TryAdd(key, client);
  89. }
  90. return client;
  91. }
  92. private WebRequest GetMonoRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  93. {
  94. var request = (HttpWebRequest)WebRequest.Create(options.Url);
  95. if (!string.IsNullOrEmpty(options.AcceptHeader))
  96. {
  97. request.Accept = options.AcceptHeader;
  98. }
  99. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  100. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
  101. request.ConnectionGroupName = GetHostFromUrl(options.Url);
  102. request.KeepAlive = true;
  103. request.Method = method;
  104. request.Pipelined = true;
  105. request.Timeout = 20000;
  106. if (!string.IsNullOrEmpty(options.UserAgent))
  107. {
  108. request.UserAgent = options.UserAgent;
  109. }
  110. return request;
  111. }
  112. private PropertyInfo _httpBehaviorPropertyInfo;
  113. private WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  114. {
  115. #if __MonoCS__
  116. return GetMonoRequest(options, method, enableHttpCompression);
  117. #endif
  118. var request = HttpWebRequest.CreateHttp(options.Url);
  119. if (!string.IsNullOrEmpty(options.AcceptHeader))
  120. {
  121. request.Accept = options.AcceptHeader;
  122. }
  123. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  124. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
  125. request.ConnectionGroupName = GetHostFromUrl(options.Url);
  126. request.KeepAlive = true;
  127. request.Method = method;
  128. request.Pipelined = true;
  129. request.Timeout = 20000;
  130. if (!string.IsNullOrEmpty(options.UserAgent))
  131. {
  132. request.UserAgent = options.UserAgent;
  133. }
  134. // This is a hack to prevent KeepAlive from getting disabled internally by the HttpWebRequest
  135. // May need to remove this for mono
  136. var sp = request.ServicePoint;
  137. if (_httpBehaviorPropertyInfo == null)
  138. {
  139. _httpBehaviorPropertyInfo = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
  140. }
  141. _httpBehaviorPropertyInfo.SetValue(sp, (byte)0, null);
  142. return request;
  143. }
  144. /// <summary>
  145. /// Gets the response internal.
  146. /// </summary>
  147. /// <param name="options">The options.</param>
  148. /// <returns>Task{HttpResponseInfo}.</returns>
  149. /// <exception cref="HttpException">
  150. /// </exception>
  151. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  152. {
  153. return SendAsync(options, "GET");
  154. }
  155. /// <summary>
  156. /// Performs a GET request and returns the resulting stream
  157. /// </summary>
  158. /// <param name="options">The options.</param>
  159. /// <returns>Task{Stream}.</returns>
  160. /// <exception cref="HttpException"></exception>
  161. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  162. public async Task<Stream> Get(HttpRequestOptions options)
  163. {
  164. var response = await GetResponse(options).ConfigureAwait(false);
  165. return response.Content;
  166. }
  167. /// <summary>
  168. /// Performs a GET request and returns the resulting stream
  169. /// </summary>
  170. /// <param name="url">The URL.</param>
  171. /// <param name="resourcePool">The resource pool.</param>
  172. /// <param name="cancellationToken">The cancellation token.</param>
  173. /// <returns>Task{Stream}.</returns>
  174. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  175. {
  176. return Get(new HttpRequestOptions
  177. {
  178. Url = url,
  179. ResourcePool = resourcePool,
  180. CancellationToken = cancellationToken,
  181. });
  182. }
  183. /// <summary>
  184. /// Gets the specified URL.
  185. /// </summary>
  186. /// <param name="url">The URL.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task{Stream}.</returns>
  189. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  190. {
  191. return Get(url, null, cancellationToken);
  192. }
  193. /// <summary>
  194. /// send as an asynchronous operation.
  195. /// </summary>
  196. /// <param name="options">The options.</param>
  197. /// <param name="httpMethod">The HTTP method.</param>
  198. /// <returns>Task{HttpResponseInfo}.</returns>
  199. /// <exception cref="HttpException">
  200. /// </exception>
  201. private async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  202. {
  203. ValidateParams(options);
  204. options.CancellationToken.ThrowIfCancellationRequested();
  205. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  206. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  207. {
  208. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true };
  209. }
  210. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  211. if (!string.IsNullOrEmpty(options.RequestContent) || string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  212. {
  213. var content = options.RequestContent ?? string.Empty;
  214. var bytes = Encoding.UTF8.GetBytes(content);
  215. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  216. httpWebRequest.ContentLength = bytes.Length;
  217. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  218. }
  219. if (options.ResourcePool != null)
  220. {
  221. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  222. }
  223. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  224. {
  225. if (options.ResourcePool != null)
  226. {
  227. options.ResourcePool.Release();
  228. }
  229. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  230. }
  231. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  232. try
  233. {
  234. options.CancellationToken.ThrowIfCancellationRequested();
  235. if (!options.BufferContent)
  236. {
  237. var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);
  238. var httpResponse = (HttpWebResponse)response;
  239. EnsureSuccessStatusCode(httpResponse);
  240. options.CancellationToken.ThrowIfCancellationRequested();
  241. return new HttpResponseInfo
  242. {
  243. Content = httpResponse.GetResponseStream(),
  244. StatusCode = httpResponse.StatusCode,
  245. ContentType = httpResponse.ContentType
  246. };
  247. }
  248. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  249. {
  250. var httpResponse = (HttpWebResponse)response;
  251. EnsureSuccessStatusCode(httpResponse);
  252. options.CancellationToken.ThrowIfCancellationRequested();
  253. using (var stream = httpResponse.GetResponseStream())
  254. {
  255. var memoryStream = new MemoryStream();
  256. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  257. memoryStream.Position = 0;
  258. return new HttpResponseInfo
  259. {
  260. Content = memoryStream,
  261. StatusCode = httpResponse.StatusCode,
  262. ContentType = httpResponse.ContentType
  263. };
  264. }
  265. }
  266. }
  267. catch (OperationCanceledException ex)
  268. {
  269. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  270. var httpException = exception as HttpException;
  271. if (httpException != null && httpException.IsTimedOut)
  272. {
  273. client.LastTimeout = DateTime.UtcNow;
  274. }
  275. throw exception;
  276. }
  277. catch (HttpRequestException ex)
  278. {
  279. _logger.ErrorException("Error getting response from " + options.Url, ex);
  280. throw new HttpException(ex.Message, ex);
  281. }
  282. catch (WebException ex)
  283. {
  284. _logger.ErrorException("Error getting response from " + options.Url, ex);
  285. throw new HttpException(ex.Message, ex);
  286. }
  287. catch (Exception ex)
  288. {
  289. _logger.ErrorException("Error getting response from " + options.Url, ex);
  290. throw;
  291. }
  292. finally
  293. {
  294. if (options.ResourcePool != null)
  295. {
  296. options.ResourcePool.Release();
  297. }
  298. }
  299. }
  300. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  301. {
  302. return SendAsync(options, "POST");
  303. }
  304. /// <summary>
  305. /// Performs a POST request
  306. /// </summary>
  307. /// <param name="options">The options.</param>
  308. /// <param name="postData">Params to add to the POST data.</param>
  309. /// <returns>stream on success, null on failure</returns>
  310. /// <exception cref="HttpException">
  311. /// </exception>
  312. /// <exception cref="System.ArgumentNullException">postData</exception>
  313. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  314. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  315. {
  316. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  317. var postContent = string.Join("&", strings.ToArray());
  318. options.RequestContent = postContent;
  319. options.RequestContentType = "application/x-www-form-urlencoded";
  320. var response = await Post(options).ConfigureAwait(false);
  321. return response.Content;
  322. }
  323. /// <summary>
  324. /// Performs a POST request
  325. /// </summary>
  326. /// <param name="url">The URL.</param>
  327. /// <param name="postData">Params to add to the POST data.</param>
  328. /// <param name="resourcePool">The resource pool.</param>
  329. /// <param name="cancellationToken">The cancellation token.</param>
  330. /// <returns>stream on success, null on failure</returns>
  331. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  332. {
  333. return Post(new HttpRequestOptions
  334. {
  335. Url = url,
  336. ResourcePool = resourcePool,
  337. CancellationToken = cancellationToken
  338. }, postData);
  339. }
  340. /// <summary>
  341. /// Downloads the contents of a given url into a temporary location
  342. /// </summary>
  343. /// <param name="options">The options.</param>
  344. /// <returns>Task{System.String}.</returns>
  345. /// <exception cref="System.ArgumentNullException">progress</exception>
  346. /// <exception cref="HttpException"></exception>
  347. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  348. public async Task<string> GetTempFile(HttpRequestOptions options)
  349. {
  350. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  351. return response.TempFilePath;
  352. }
  353. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  354. {
  355. ValidateParams(options);
  356. Directory.CreateDirectory(_appPaths.TempDirectory);
  357. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  358. if (options.Progress == null)
  359. {
  360. throw new ArgumentNullException("progress");
  361. }
  362. options.CancellationToken.ThrowIfCancellationRequested();
  363. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  364. if (options.ResourcePool != null)
  365. {
  366. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  367. }
  368. options.Progress.Report(0);
  369. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  370. try
  371. {
  372. options.CancellationToken.ThrowIfCancellationRequested();
  373. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  374. {
  375. var httpResponse = (HttpWebResponse)response;
  376. EnsureSuccessStatusCode(httpResponse);
  377. options.CancellationToken.ThrowIfCancellationRequested();
  378. var contentLength = GetContentLength(httpResponse);
  379. if (!contentLength.HasValue)
  380. {
  381. // We're not able to track progress
  382. using (var stream = httpResponse.GetResponseStream())
  383. {
  384. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  385. {
  386. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  387. }
  388. }
  389. }
  390. else
  391. {
  392. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  393. {
  394. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  395. {
  396. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  397. }
  398. }
  399. }
  400. options.Progress.Report(100);
  401. return new HttpResponseInfo
  402. {
  403. TempFilePath = tempFile,
  404. StatusCode = httpResponse.StatusCode,
  405. ContentType = httpResponse.ContentType
  406. };
  407. }
  408. }
  409. catch (OperationCanceledException ex)
  410. {
  411. throw GetTempFileException(ex, options, tempFile);
  412. }
  413. catch (HttpRequestException ex)
  414. {
  415. throw GetTempFileException(ex, options, tempFile);
  416. }
  417. catch (WebException ex)
  418. {
  419. throw GetTempFileException(ex, options, tempFile);
  420. }
  421. catch (Exception ex)
  422. {
  423. throw GetTempFileException(ex, options, tempFile);
  424. }
  425. finally
  426. {
  427. if (options.ResourcePool != null)
  428. {
  429. options.ResourcePool.Release();
  430. }
  431. }
  432. }
  433. private long? GetContentLength(HttpWebResponse response)
  434. {
  435. var length = response.ContentLength;
  436. if (length == 0)
  437. {
  438. return null;
  439. }
  440. return length;
  441. }
  442. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  443. /// <summary>
  444. /// Handles the temp file exception.
  445. /// </summary>
  446. /// <param name="ex">The ex.</param>
  447. /// <param name="options">The options.</param>
  448. /// <param name="tempFile">The temp file.</param>
  449. /// <returns>Task.</returns>
  450. /// <exception cref="HttpException"></exception>
  451. private Exception GetTempFileException(Exception ex, HttpRequestOptions options, string tempFile)
  452. {
  453. var operationCanceledException = ex as OperationCanceledException;
  454. if (operationCanceledException != null)
  455. {
  456. // Cleanup
  457. DeleteTempFile(tempFile);
  458. return GetCancellationException(options.Url, options.CancellationToken, operationCanceledException);
  459. }
  460. _logger.ErrorException("Error getting response from " + options.Url, ex);
  461. // Cleanup
  462. DeleteTempFile(tempFile);
  463. var httpRequestException = ex as HttpRequestException;
  464. if (httpRequestException != null)
  465. {
  466. return new HttpException(ex.Message, ex);
  467. }
  468. var webException = ex as WebException;
  469. if (webException != null)
  470. {
  471. return new HttpException(ex.Message, ex);
  472. }
  473. return ex;
  474. }
  475. private void DeleteTempFile(string file)
  476. {
  477. try
  478. {
  479. File.Delete(file);
  480. }
  481. catch (IOException)
  482. {
  483. // Might not have been created at all. No need to worry.
  484. }
  485. }
  486. private void ValidateParams(HttpRequestOptions options)
  487. {
  488. if (string.IsNullOrEmpty(options.Url))
  489. {
  490. throw new ArgumentNullException("options");
  491. }
  492. }
  493. /// <summary>
  494. /// Gets the host from URL.
  495. /// </summary>
  496. /// <param name="url">The URL.</param>
  497. /// <returns>System.String.</returns>
  498. private string GetHostFromUrl(string url)
  499. {
  500. var start = url.IndexOf("://", StringComparison.OrdinalIgnoreCase) + 3;
  501. var len = url.IndexOf('/', start) - start;
  502. return url.Substring(start, len);
  503. }
  504. /// <summary>
  505. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  506. /// </summary>
  507. public void Dispose()
  508. {
  509. Dispose(true);
  510. GC.SuppressFinalize(this);
  511. }
  512. /// <summary>
  513. /// Releases unmanaged and - optionally - managed resources.
  514. /// </summary>
  515. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  516. protected virtual void Dispose(bool dispose)
  517. {
  518. if (dispose)
  519. {
  520. _httpClients.Clear();
  521. }
  522. }
  523. /// <summary>
  524. /// Throws the cancellation exception.
  525. /// </summary>
  526. /// <param name="url">The URL.</param>
  527. /// <param name="cancellationToken">The cancellation token.</param>
  528. /// <param name="exception">The exception.</param>
  529. /// <returns>Exception.</returns>
  530. private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
  531. {
  532. // If the HttpClient's timeout is reached, it will cancel the Task internally
  533. if (!cancellationToken.IsCancellationRequested)
  534. {
  535. var msg = string.Format("Connection to {0} timed out", url);
  536. _logger.Error(msg);
  537. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  538. return new HttpException(msg, exception) { IsTimedOut = true };
  539. }
  540. return exception;
  541. }
  542. private void EnsureSuccessStatusCode(HttpWebResponse response)
  543. {
  544. var statusCode = response.StatusCode;
  545. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  546. if (!isSuccessful)
  547. {
  548. throw new HttpException(response.StatusDescription) { StatusCode = response.StatusCode };
  549. }
  550. }
  551. /// <summary>
  552. /// Posts the specified URL.
  553. /// </summary>
  554. /// <param name="url">The URL.</param>
  555. /// <param name="postData">The post data.</param>
  556. /// <param name="cancellationToken">The cancellation token.</param>
  557. /// <returns>Task{Stream}.</returns>
  558. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  559. {
  560. return Post(url, postData, null, cancellationToken);
  561. }
  562. }
  563. }