2
0

HttpClientManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. using System.Collections.Specialized;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Net;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Net.Cache;
  15. using System.Net.Http;
  16. using System.Reflection;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Common.Implementations.HttpClientManager
  21. {
  22. /// <summary>
  23. /// Class HttpClientManager
  24. /// </summary>
  25. public class HttpClientManager : IHttpClient
  26. {
  27. /// <summary>
  28. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  29. /// </summary>
  30. private const int TimeoutSeconds = 30;
  31. /// <summary>
  32. /// The _logger
  33. /// </summary>
  34. private readonly ILogger _logger;
  35. /// <summary>
  36. /// The _app paths
  37. /// </summary>
  38. private readonly IApplicationPaths _appPaths;
  39. private readonly IFileSystem _fileSystem;
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  42. /// </summary>
  43. /// <param name="appPaths">The app paths.</param>
  44. /// <param name="logger">The logger.</param>
  45. /// <param name="fileSystem">The file system.</param>
  46. /// <exception cref="System.ArgumentNullException">appPaths
  47. /// or
  48. /// logger</exception>
  49. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  50. {
  51. if (appPaths == null)
  52. {
  53. throw new ArgumentNullException("appPaths");
  54. }
  55. if (logger == null)
  56. {
  57. throw new ArgumentNullException("logger");
  58. }
  59. _logger = logger;
  60. _fileSystem = fileSystem;
  61. _appPaths = appPaths;
  62. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  63. ServicePointManager.Expect100Continue = false;
  64. }
  65. /// <summary>
  66. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  67. /// DON'T dispose it after use.
  68. /// </summary>
  69. /// <value>The HTTP clients.</value>
  70. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  71. /// <summary>
  72. /// Gets
  73. /// </summary>
  74. /// <param name="host">The host.</param>
  75. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  76. /// <returns>HttpClient.</returns>
  77. /// <exception cref="System.ArgumentNullException">host</exception>
  78. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  79. {
  80. if (string.IsNullOrEmpty(host))
  81. {
  82. throw new ArgumentNullException("host");
  83. }
  84. HttpClientInfo client;
  85. var key = host + enableHttpCompression;
  86. if (!_httpClients.TryGetValue(key, out client))
  87. {
  88. client = new HttpClientInfo();
  89. _httpClients.TryAdd(key, client);
  90. }
  91. return client;
  92. }
  93. private PropertyInfo _httpBehaviorPropertyInfo;
  94. private WebRequest GetRequest(HttpRequestOptions options, string method, bool enableHttpCompression)
  95. {
  96. var request = (HttpWebRequest)WebRequest.Create(options.Url);
  97. AddRequestHeaders(request, options);
  98. request.AutomaticDecompression = enableHttpCompression ? DecompressionMethods.Deflate : DecompressionMethods.None;
  99. request.CachePolicy = options.CachePolicy == Net.HttpRequestCachePolicy.None ?
  100. new RequestCachePolicy(RequestCacheLevel.BypassCache) :
  101. new RequestCachePolicy(RequestCacheLevel.Revalidate);
  102. request.ConnectionGroupName = GetHostFromUrl(options.Url);
  103. request.KeepAlive = true;
  104. request.Method = method;
  105. request.Pipelined = true;
  106. request.Timeout = 20000;
  107. #if !__MonoCS__
  108. // This is a hack to prevent KeepAlive from getting disabled internally by the HttpWebRequest
  109. // May need to remove this for mono
  110. var sp = request.ServicePoint;
  111. if (_httpBehaviorPropertyInfo == null)
  112. {
  113. _httpBehaviorPropertyInfo = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
  114. }
  115. _httpBehaviorPropertyInfo.SetValue(sp, (byte)0, null);
  116. #endif
  117. return request;
  118. }
  119. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  120. {
  121. foreach (var header in options.RequestHeaders.ToList())
  122. {
  123. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  124. {
  125. request.Accept = header.Value;
  126. }
  127. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  128. {
  129. request.UserAgent = header.Value;
  130. }
  131. else
  132. {
  133. request.Headers.Set(header.Key, header.Value);
  134. }
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the response internal.
  139. /// </summary>
  140. /// <param name="options">The options.</param>
  141. /// <returns>Task{HttpResponseInfo}.</returns>
  142. /// <exception cref="HttpException">
  143. /// </exception>
  144. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  145. {
  146. return SendAsync(options, "GET");
  147. }
  148. /// <summary>
  149. /// Performs a GET request and returns the resulting stream
  150. /// </summary>
  151. /// <param name="options">The options.</param>
  152. /// <returns>Task{Stream}.</returns>
  153. /// <exception cref="HttpException"></exception>
  154. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  155. public async Task<Stream> Get(HttpRequestOptions options)
  156. {
  157. var response = await GetResponse(options).ConfigureAwait(false);
  158. return response.Content;
  159. }
  160. /// <summary>
  161. /// Performs a GET request and returns the resulting stream
  162. /// </summary>
  163. /// <param name="url">The URL.</param>
  164. /// <param name="resourcePool">The resource pool.</param>
  165. /// <param name="cancellationToken">The cancellation token.</param>
  166. /// <returns>Task{Stream}.</returns>
  167. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  168. {
  169. return Get(new HttpRequestOptions
  170. {
  171. Url = url,
  172. ResourcePool = resourcePool,
  173. CancellationToken = cancellationToken,
  174. });
  175. }
  176. /// <summary>
  177. /// Gets the specified URL.
  178. /// </summary>
  179. /// <param name="url">The URL.</param>
  180. /// <param name="cancellationToken">The cancellation token.</param>
  181. /// <returns>Task{Stream}.</returns>
  182. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  183. {
  184. return Get(url, null, cancellationToken);
  185. }
  186. /// <summary>
  187. /// send as an asynchronous operation.
  188. /// </summary>
  189. /// <param name="options">The options.</param>
  190. /// <param name="httpMethod">The HTTP method.</param>
  191. /// <returns>Task{HttpResponseInfo}.</returns>
  192. /// <exception cref="HttpException">
  193. /// </exception>
  194. private async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  195. {
  196. ValidateParams(options);
  197. options.CancellationToken.ThrowIfCancellationRequested();
  198. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  199. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  200. {
  201. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url)) { IsTimedOut = true };
  202. }
  203. var httpWebRequest = GetRequest(options, httpMethod, options.EnableHttpCompression);
  204. if (!string.IsNullOrEmpty(options.RequestContent) || string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  205. {
  206. var content = options.RequestContent ?? string.Empty;
  207. var bytes = Encoding.UTF8.GetBytes(content);
  208. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  209. httpWebRequest.ContentLength = bytes.Length;
  210. httpWebRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
  211. }
  212. if (options.ResourcePool != null)
  213. {
  214. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  215. }
  216. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  217. {
  218. if (options.ResourcePool != null)
  219. {
  220. options.ResourcePool.Release();
  221. }
  222. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  223. }
  224. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  225. try
  226. {
  227. options.CancellationToken.ThrowIfCancellationRequested();
  228. if (!options.BufferContent)
  229. {
  230. var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false);
  231. var httpResponse = (HttpWebResponse)response;
  232. EnsureSuccessStatusCode(httpResponse);
  233. options.CancellationToken.ThrowIfCancellationRequested();
  234. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse));
  235. }
  236. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  237. {
  238. var httpResponse = (HttpWebResponse)response;
  239. EnsureSuccessStatusCode(httpResponse);
  240. options.CancellationToken.ThrowIfCancellationRequested();
  241. using (var stream = httpResponse.GetResponseStream())
  242. {
  243. var memoryStream = new MemoryStream();
  244. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  245. memoryStream.Position = 0;
  246. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length);
  247. }
  248. }
  249. }
  250. catch (OperationCanceledException ex)
  251. {
  252. var exception = GetCancellationException(options.Url, options.CancellationToken, ex);
  253. var httpException = exception as HttpException;
  254. if (httpException != null && httpException.IsTimedOut)
  255. {
  256. client.LastTimeout = DateTime.UtcNow;
  257. }
  258. throw exception;
  259. }
  260. catch (HttpRequestException ex)
  261. {
  262. _logger.ErrorException("Error getting response from " + options.Url, ex);
  263. throw new HttpException(ex.Message, ex);
  264. }
  265. catch (WebException ex)
  266. {
  267. _logger.ErrorException("Error getting response from " + options.Url, ex);
  268. throw new HttpException(ex.Message, ex);
  269. }
  270. catch (Exception ex)
  271. {
  272. _logger.ErrorException("Error getting response from " + options.Url, ex);
  273. throw;
  274. }
  275. finally
  276. {
  277. if (options.ResourcePool != null)
  278. {
  279. options.ResourcePool.Release();
  280. }
  281. }
  282. }
  283. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength)
  284. {
  285. return new HttpResponseInfo
  286. {
  287. Content = content,
  288. StatusCode = httpResponse.StatusCode,
  289. ContentType = httpResponse.ContentType,
  290. Headers = new NameValueCollection(httpResponse.Headers),
  291. ContentLength = contentLength
  292. };
  293. }
  294. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  295. {
  296. return new HttpResponseInfo
  297. {
  298. TempFilePath = tempFile,
  299. StatusCode = httpResponse.StatusCode,
  300. ContentType = httpResponse.ContentType,
  301. Headers = httpResponse.Headers,
  302. ContentLength = contentLength
  303. };
  304. }
  305. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  306. {
  307. return SendAsync(options, "POST");
  308. }
  309. /// <summary>
  310. /// Performs a POST request
  311. /// </summary>
  312. /// <param name="options">The options.</param>
  313. /// <param name="postData">Params to add to the POST data.</param>
  314. /// <returns>stream on success, null on failure</returns>
  315. /// <exception cref="HttpException">
  316. /// </exception>
  317. /// <exception cref="System.ArgumentNullException">postData</exception>
  318. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  319. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  320. {
  321. var strings = postData.Keys.Select(key => string.Format("{0}={1}", key, postData[key]));
  322. var postContent = string.Join("&", strings.ToArray());
  323. options.RequestContent = postContent;
  324. options.RequestContentType = "application/x-www-form-urlencoded";
  325. var response = await Post(options).ConfigureAwait(false);
  326. return response.Content;
  327. }
  328. /// <summary>
  329. /// Performs a POST request
  330. /// </summary>
  331. /// <param name="url">The URL.</param>
  332. /// <param name="postData">Params to add to the POST data.</param>
  333. /// <param name="resourcePool">The resource pool.</param>
  334. /// <param name="cancellationToken">The cancellation token.</param>
  335. /// <returns>stream on success, null on failure</returns>
  336. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  337. {
  338. return Post(new HttpRequestOptions
  339. {
  340. Url = url,
  341. ResourcePool = resourcePool,
  342. CancellationToken = cancellationToken
  343. }, postData);
  344. }
  345. /// <summary>
  346. /// Downloads the contents of a given url into a temporary location
  347. /// </summary>
  348. /// <param name="options">The options.</param>
  349. /// <returns>Task{System.String}.</returns>
  350. /// <exception cref="System.ArgumentNullException">progress</exception>
  351. /// <exception cref="HttpException"></exception>
  352. /// <exception cref="MediaBrowser.Model.Net.HttpException"></exception>
  353. public async Task<string> GetTempFile(HttpRequestOptions options)
  354. {
  355. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  356. return response.TempFilePath;
  357. }
  358. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  359. {
  360. ValidateParams(options);
  361. Directory.CreateDirectory(_appPaths.TempDirectory);
  362. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  363. if (options.Progress == null)
  364. {
  365. throw new ArgumentNullException("progress");
  366. }
  367. options.CancellationToken.ThrowIfCancellationRequested();
  368. var httpWebRequest = GetRequest(options, "GET", options.EnableHttpCompression);
  369. if (options.ResourcePool != null)
  370. {
  371. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  372. }
  373. options.Progress.Report(0);
  374. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  375. try
  376. {
  377. options.CancellationToken.ThrowIfCancellationRequested();
  378. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  379. {
  380. var httpResponse = (HttpWebResponse)response;
  381. EnsureSuccessStatusCode(httpResponse);
  382. options.CancellationToken.ThrowIfCancellationRequested();
  383. var contentLength = GetContentLength(httpResponse);
  384. if (!contentLength.HasValue)
  385. {
  386. // We're not able to track progress
  387. using (var stream = httpResponse.GetResponseStream())
  388. {
  389. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  390. {
  391. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  392. }
  393. }
  394. }
  395. else
  396. {
  397. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  398. {
  399. using (var fs = _fileSystem.GetFileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  400. {
  401. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  402. }
  403. }
  404. }
  405. options.Progress.Report(100);
  406. return GetResponseInfo(httpResponse, tempFile, contentLength);
  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. }