HttpClientManager.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. using System.Net.Sockets;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Collections.Specialized;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using Emby.Common.Implementations.HttpClientManager;
  20. using MediaBrowser.Model.IO;
  21. namespace Emby.Common.Implementations.HttpClientManager
  22. {
  23. /// <summary>
  24. /// Class HttpClientManager
  25. /// </summary>
  26. public class HttpClientManager : IHttpClient
  27. {
  28. /// <summary>
  29. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  30. /// </summary>
  31. private const int TimeoutSeconds = 30;
  32. /// <summary>
  33. /// The _logger
  34. /// </summary>
  35. private readonly ILogger _logger;
  36. /// <summary>
  37. /// The _app paths
  38. /// </summary>
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IFileSystem _fileSystem;
  41. private readonly IMemoryStreamProvider _memoryStreamProvider;
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  44. /// </summary>
  45. /// <param name="appPaths">The app paths.</param>
  46. /// <param name="logger">The logger.</param>
  47. /// <param name="fileSystem">The file system.</param>
  48. /// <exception cref="System.ArgumentNullException">appPaths
  49. /// or
  50. /// logger</exception>
  51. public HttpClientManager(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem, IMemoryStreamProvider memoryStreamProvider)
  52. {
  53. if (appPaths == null)
  54. {
  55. throw new ArgumentNullException("appPaths");
  56. }
  57. if (logger == null)
  58. {
  59. throw new ArgumentNullException("logger");
  60. }
  61. _logger = logger;
  62. _fileSystem = fileSystem;
  63. _memoryStreamProvider = memoryStreamProvider;
  64. _appPaths = appPaths;
  65. #if NET46
  66. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  67. ServicePointManager.Expect100Continue = false;
  68. // Trakt requests sometimes fail without this
  69. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  70. #endif
  71. }
  72. /// <summary>
  73. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  74. /// DON'T dispose it after use.
  75. /// </summary>
  76. /// <value>The HTTP clients.</value>
  77. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  78. /// <summary>
  79. /// Gets
  80. /// </summary>
  81. /// <param name="host">The host.</param>
  82. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  83. /// <returns>HttpClient.</returns>
  84. /// <exception cref="System.ArgumentNullException">host</exception>
  85. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  86. {
  87. if (string.IsNullOrEmpty(host))
  88. {
  89. throw new ArgumentNullException("host");
  90. }
  91. HttpClientInfo client;
  92. var key = host + enableHttpCompression;
  93. if (!_httpClients.TryGetValue(key, out client))
  94. {
  95. client = new HttpClientInfo();
  96. _httpClients.TryAdd(key, client);
  97. }
  98. return client;
  99. }
  100. private WebRequest CreateWebRequest(string url)
  101. {
  102. try
  103. {
  104. return WebRequest.Create(url);
  105. }
  106. catch (NotSupportedException)
  107. {
  108. //Webrequest creation does fail on MONO randomly when using WebRequest.Create
  109. //the issue occurs in the GetCreator method here: http://www.oschina.net/code/explore/mono-2.8.1/mcs/class/System/System.Net/WebRequest.cs
  110. var type = Type.GetType("System.Net.HttpRequestCreator, System, Version=4.0.0.0,Culture=neutral, PublicKeyToken=b77a5c561934e089");
  111. var creator = Activator.CreateInstance(type, nonPublic: true) as IWebRequestCreate;
  112. return creator.Create(new Uri(url)) as HttpWebRequest;
  113. }
  114. }
  115. private void AddIpv4Option(HttpWebRequest request, HttpRequestOptions options)
  116. {
  117. #if NET46
  118. request.ServicePoint.BindIPEndPointDelegate = (servicePount, remoteEndPoint, retryCount) =>
  119. {
  120. if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork)
  121. {
  122. return new IPEndPoint(IPAddress.Any, 0);
  123. }
  124. throw new InvalidOperationException("no IPv4 address");
  125. };
  126. #endif
  127. }
  128. private WebRequest GetRequest(HttpRequestOptions options, string method)
  129. {
  130. var url = options.Url;
  131. var uriAddress = new Uri(url);
  132. var userInfo = uriAddress.UserInfo;
  133. if (!string.IsNullOrWhiteSpace(userInfo))
  134. {
  135. _logger.Info("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  136. url = url.Replace(userInfo + "@", string.Empty);
  137. }
  138. var request = CreateWebRequest(url);
  139. var httpWebRequest = request as HttpWebRequest;
  140. if (httpWebRequest != null)
  141. {
  142. if (options.PreferIpv4)
  143. {
  144. AddIpv4Option(httpWebRequest, options);
  145. }
  146. AddRequestHeaders(httpWebRequest, options);
  147. #if NET46
  148. if (options.EnableHttpCompression)
  149. {
  150. if (options.DecompressionMethod.HasValue)
  151. {
  152. httpWebRequest.AutomaticDecompression = options.DecompressionMethod.Value == CompressionMethod.Gzip
  153. ? DecompressionMethods.GZip
  154. : DecompressionMethods.Deflate;
  155. }
  156. else
  157. {
  158. httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
  159. }
  160. }
  161. else
  162. {
  163. httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
  164. }
  165. #endif
  166. }
  167. #if NET46
  168. request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
  169. #endif
  170. if (httpWebRequest != null)
  171. {
  172. if (options.EnableKeepAlive)
  173. {
  174. #if NET46
  175. httpWebRequest.KeepAlive = true;
  176. #endif
  177. }
  178. }
  179. request.Method = method;
  180. #if NET46
  181. request.Timeout = options.TimeoutMs;
  182. #endif
  183. if (httpWebRequest != null)
  184. {
  185. if (!string.IsNullOrEmpty(options.Host))
  186. {
  187. #if NET46
  188. httpWebRequest.Host = options.Host;
  189. #elif NETSTANDARD1_6
  190. httpWebRequest.Headers["Host"] = options.Host;
  191. #endif
  192. }
  193. if (!string.IsNullOrEmpty(options.Referer))
  194. {
  195. #if NET46
  196. httpWebRequest.Referer = options.Referer;
  197. #elif NETSTANDARD1_6
  198. httpWebRequest.Headers["Referer"] = options.Referer;
  199. #endif
  200. }
  201. }
  202. if (!string.IsNullOrWhiteSpace(userInfo))
  203. {
  204. var parts = userInfo.Split(':');
  205. if (parts.Length == 2)
  206. {
  207. request.Credentials = GetCredential(url, parts[0], parts[1]);
  208. // TODO: .net core ??
  209. #if NET46
  210. request.PreAuthenticate = true;
  211. #endif
  212. }
  213. }
  214. return request;
  215. }
  216. private CredentialCache GetCredential(string url, string username, string password)
  217. {
  218. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
  219. CredentialCache credentialCache = new CredentialCache();
  220. credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
  221. return credentialCache;
  222. }
  223. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  224. {
  225. foreach (var header in options.RequestHeaders.ToList())
  226. {
  227. if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
  228. {
  229. request.Accept = header.Value;
  230. }
  231. else if (string.Equals(header.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
  232. {
  233. #if NET46
  234. request.UserAgent = header.Value;
  235. #elif NETSTANDARD1_6
  236. request.Headers["User-Agent"] = header.Value;
  237. #endif
  238. }
  239. else
  240. {
  241. #if NET46
  242. request.Headers.Set(header.Key, header.Value);
  243. #elif NETSTANDARD1_6
  244. request.Headers[header.Key] = header.Value;
  245. #endif
  246. }
  247. }
  248. }
  249. /// <summary>
  250. /// Gets the response internal.
  251. /// </summary>
  252. /// <param name="options">The options.</param>
  253. /// <returns>Task{HttpResponseInfo}.</returns>
  254. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  255. {
  256. return SendAsync(options, "GET");
  257. }
  258. /// <summary>
  259. /// Performs a GET request and returns the resulting stream
  260. /// </summary>
  261. /// <param name="options">The options.</param>
  262. /// <returns>Task{Stream}.</returns>
  263. public async Task<Stream> Get(HttpRequestOptions options)
  264. {
  265. var response = await GetResponse(options).ConfigureAwait(false);
  266. return response.Content;
  267. }
  268. /// <summary>
  269. /// Performs a GET request and returns the resulting stream
  270. /// </summary>
  271. /// <param name="url">The URL.</param>
  272. /// <param name="resourcePool">The resource pool.</param>
  273. /// <param name="cancellationToken">The cancellation token.</param>
  274. /// <returns>Task{Stream}.</returns>
  275. public Task<Stream> Get(string url, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  276. {
  277. return Get(new HttpRequestOptions
  278. {
  279. Url = url,
  280. ResourcePool = resourcePool,
  281. CancellationToken = cancellationToken,
  282. BufferContent = resourcePool != null
  283. });
  284. }
  285. /// <summary>
  286. /// Gets the specified URL.
  287. /// </summary>
  288. /// <param name="url">The URL.</param>
  289. /// <param name="cancellationToken">The cancellation token.</param>
  290. /// <returns>Task{Stream}.</returns>
  291. public Task<Stream> Get(string url, CancellationToken cancellationToken)
  292. {
  293. return Get(url, null, cancellationToken);
  294. }
  295. /// <summary>
  296. /// send as an asynchronous operation.
  297. /// </summary>
  298. /// <param name="options">The options.</param>
  299. /// <param name="httpMethod">The HTTP method.</param>
  300. /// <returns>Task{HttpResponseInfo}.</returns>
  301. /// <exception cref="HttpException">
  302. /// </exception>
  303. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  304. {
  305. if (options.CacheMode == CacheMode.None)
  306. {
  307. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  308. }
  309. var url = options.Url;
  310. var urlHash = url.ToLower().GetMD5().ToString("N");
  311. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  312. var response = await GetCachedResponse(responseCachePath, options.CacheLength, url).ConfigureAwait(false);
  313. if (response != null)
  314. {
  315. return response;
  316. }
  317. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  318. if (response.StatusCode == HttpStatusCode.OK)
  319. {
  320. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  321. }
  322. return response;
  323. }
  324. private async Task<HttpResponseInfo> GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  325. {
  326. _logger.Info("Checking for cache file {0}", responseCachePath);
  327. try
  328. {
  329. if (_fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  330. {
  331. using (var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true))
  332. {
  333. var memoryStream = _memoryStreamProvider.CreateNew();
  334. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  335. memoryStream.Position = 0;
  336. return new HttpResponseInfo
  337. {
  338. ResponseUrl = url,
  339. Content = memoryStream,
  340. StatusCode = HttpStatusCode.OK,
  341. ContentLength = memoryStream.Length
  342. };
  343. }
  344. }
  345. }
  346. catch (FileNotFoundException)
  347. {
  348. }
  349. catch (DirectoryNotFoundException)
  350. {
  351. }
  352. return null;
  353. }
  354. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  355. {
  356. _fileSystem.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  357. using (var responseStream = response.Content)
  358. {
  359. var memoryStream = _memoryStreamProvider.CreateNew();
  360. await responseStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  361. memoryStream.Position = 0;
  362. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  363. {
  364. await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false);
  365. memoryStream.Position = 0;
  366. response.Content = memoryStream;
  367. }
  368. }
  369. }
  370. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  371. {
  372. ValidateParams(options);
  373. options.CancellationToken.ThrowIfCancellationRequested();
  374. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  375. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  376. {
  377. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  378. {
  379. IsTimedOut = true
  380. };
  381. }
  382. var httpWebRequest = GetRequest(options, httpMethod);
  383. if (options.RequestContentBytes != null ||
  384. !string.IsNullOrEmpty(options.RequestContent) ||
  385. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  386. {
  387. var bytes = options.RequestContentBytes ??
  388. Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  389. httpWebRequest.ContentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  390. #if NET46
  391. httpWebRequest.ContentLength = bytes.Length;
  392. #endif
  393. (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
  394. }
  395. if (options.ResourcePool != null)
  396. {
  397. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  398. }
  399. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  400. {
  401. if (options.ResourcePool != null)
  402. {
  403. options.ResourcePool.Release();
  404. }
  405. throw new HttpException(string.Format("Connection to {0} timed out", options.Url)) { IsTimedOut = true };
  406. }
  407. if (options.LogRequest)
  408. {
  409. _logger.Info("HttpClientManager {0}: {1}", httpMethod.ToUpper(), options.Url);
  410. }
  411. try
  412. {
  413. options.CancellationToken.ThrowIfCancellationRequested();
  414. if (!options.BufferContent)
  415. {
  416. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  417. var httpResponse = (HttpWebResponse)response;
  418. EnsureSuccessStatusCode(client, httpResponse, options);
  419. options.CancellationToken.ThrowIfCancellationRequested();
  420. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  421. }
  422. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  423. {
  424. var httpResponse = (HttpWebResponse)response;
  425. EnsureSuccessStatusCode(client, httpResponse, options);
  426. options.CancellationToken.ThrowIfCancellationRequested();
  427. using (var stream = httpResponse.GetResponseStream())
  428. {
  429. var memoryStream = _memoryStreamProvider.CreateNew();
  430. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  431. memoryStream.Position = 0;
  432. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  433. }
  434. }
  435. }
  436. catch (OperationCanceledException ex)
  437. {
  438. throw GetCancellationException(options, client, options.CancellationToken, ex);
  439. }
  440. catch (Exception ex)
  441. {
  442. throw GetException(ex, options, client);
  443. }
  444. finally
  445. {
  446. if (options.ResourcePool != null)
  447. {
  448. options.ResourcePool.Release();
  449. }
  450. }
  451. }
  452. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  453. {
  454. var responseInfo = new HttpResponseInfo(disposable)
  455. {
  456. Content = content,
  457. StatusCode = httpResponse.StatusCode,
  458. ContentType = httpResponse.ContentType,
  459. ContentLength = contentLength,
  460. ResponseUrl = httpResponse.ResponseUri.ToString()
  461. };
  462. if (httpResponse.Headers != null)
  463. {
  464. SetHeaders(httpResponse.Headers, responseInfo);
  465. }
  466. return responseInfo;
  467. }
  468. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  469. {
  470. var responseInfo = new HttpResponseInfo
  471. {
  472. TempFilePath = tempFile,
  473. StatusCode = httpResponse.StatusCode,
  474. ContentType = httpResponse.ContentType,
  475. ContentLength = contentLength
  476. };
  477. if (httpResponse.Headers != null)
  478. {
  479. SetHeaders(httpResponse.Headers, responseInfo);
  480. }
  481. return responseInfo;
  482. }
  483. private void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
  484. {
  485. foreach (var key in headers.AllKeys)
  486. {
  487. responseInfo.Headers[key] = headers[key];
  488. }
  489. }
  490. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  491. {
  492. return SendAsync(options, "POST");
  493. }
  494. /// <summary>
  495. /// Performs a POST request
  496. /// </summary>
  497. /// <param name="options">The options.</param>
  498. /// <param name="postData">Params to add to the POST data.</param>
  499. /// <returns>stream on success, null on failure</returns>
  500. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  501. {
  502. options.SetPostData(postData);
  503. var response = await Post(options).ConfigureAwait(false);
  504. return response.Content;
  505. }
  506. /// <summary>
  507. /// Performs a POST request
  508. /// </summary>
  509. /// <param name="url">The URL.</param>
  510. /// <param name="postData">Params to add to the POST data.</param>
  511. /// <param name="resourcePool">The resource pool.</param>
  512. /// <param name="cancellationToken">The cancellation token.</param>
  513. /// <returns>stream on success, null on failure</returns>
  514. public Task<Stream> Post(string url, Dictionary<string, string> postData, SemaphoreSlim resourcePool, CancellationToken cancellationToken)
  515. {
  516. return Post(new HttpRequestOptions
  517. {
  518. Url = url,
  519. ResourcePool = resourcePool,
  520. CancellationToken = cancellationToken,
  521. BufferContent = resourcePool != null
  522. }, postData);
  523. }
  524. /// <summary>
  525. /// Downloads the contents of a given url into a temporary location
  526. /// </summary>
  527. /// <param name="options">The options.</param>
  528. /// <returns>Task{System.String}.</returns>
  529. public async Task<string> GetTempFile(HttpRequestOptions options)
  530. {
  531. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  532. return response.TempFilePath;
  533. }
  534. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  535. {
  536. ValidateParams(options);
  537. _fileSystem.CreateDirectory(_appPaths.TempDirectory);
  538. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  539. if (options.Progress == null)
  540. {
  541. throw new ArgumentNullException("progress");
  542. }
  543. options.CancellationToken.ThrowIfCancellationRequested();
  544. var httpWebRequest = GetRequest(options, "GET");
  545. if (options.ResourcePool != null)
  546. {
  547. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  548. }
  549. options.Progress.Report(0);
  550. if (options.LogRequest)
  551. {
  552. _logger.Info("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  553. }
  554. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  555. try
  556. {
  557. options.CancellationToken.ThrowIfCancellationRequested();
  558. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  559. {
  560. var httpResponse = (HttpWebResponse)response;
  561. EnsureSuccessStatusCode(client, httpResponse, options);
  562. options.CancellationToken.ThrowIfCancellationRequested();
  563. var contentLength = GetContentLength(httpResponse);
  564. if (!contentLength.HasValue)
  565. {
  566. // We're not able to track progress
  567. using (var stream = httpResponse.GetResponseStream())
  568. {
  569. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  570. {
  571. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  572. }
  573. }
  574. }
  575. else
  576. {
  577. using (var stream = ProgressStream.CreateReadProgressStream(httpResponse.GetResponseStream(), options.Progress.Report, contentLength.Value))
  578. {
  579. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  580. {
  581. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  582. }
  583. }
  584. }
  585. options.Progress.Report(100);
  586. return GetResponseInfo(httpResponse, tempFile, contentLength);
  587. }
  588. }
  589. catch (Exception ex)
  590. {
  591. DeleteTempFile(tempFile);
  592. throw GetException(ex, options, client);
  593. }
  594. finally
  595. {
  596. if (options.ResourcePool != null)
  597. {
  598. options.ResourcePool.Release();
  599. }
  600. }
  601. }
  602. private long? GetContentLength(HttpWebResponse response)
  603. {
  604. var length = response.ContentLength;
  605. if (length == 0)
  606. {
  607. return null;
  608. }
  609. return length;
  610. }
  611. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  612. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  613. {
  614. if (ex is HttpException)
  615. {
  616. return ex;
  617. }
  618. var webException = ex as WebException
  619. ?? ex.InnerException as WebException;
  620. if (webException != null)
  621. {
  622. if (options.LogErrors)
  623. {
  624. _logger.ErrorException("Error getting response from " + options.Url, ex);
  625. }
  626. var exception = new HttpException(ex.Message, ex);
  627. var response = webException.Response as HttpWebResponse;
  628. if (response != null)
  629. {
  630. exception.StatusCode = response.StatusCode;
  631. if ((int)response.StatusCode == 429)
  632. {
  633. client.LastTimeout = DateTime.UtcNow;
  634. }
  635. }
  636. return exception;
  637. }
  638. var operationCanceledException = ex as OperationCanceledException
  639. ?? ex.InnerException as OperationCanceledException;
  640. if (operationCanceledException != null)
  641. {
  642. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  643. }
  644. if (options.LogErrors)
  645. {
  646. _logger.ErrorException("Error getting response from " + options.Url, ex);
  647. }
  648. return ex;
  649. }
  650. private void DeleteTempFile(string file)
  651. {
  652. try
  653. {
  654. _fileSystem.DeleteFile(file);
  655. }
  656. catch (IOException)
  657. {
  658. // Might not have been created at all. No need to worry.
  659. }
  660. }
  661. private void ValidateParams(HttpRequestOptions options)
  662. {
  663. if (string.IsNullOrEmpty(options.Url))
  664. {
  665. throw new ArgumentNullException("options");
  666. }
  667. }
  668. /// <summary>
  669. /// Gets the host from URL.
  670. /// </summary>
  671. /// <param name="url">The URL.</param>
  672. /// <returns>System.String.</returns>
  673. private string GetHostFromUrl(string url)
  674. {
  675. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  676. if (index != -1)
  677. {
  678. url = url.Substring(index + 3);
  679. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  680. if (!string.IsNullOrWhiteSpace(host))
  681. {
  682. return host;
  683. }
  684. }
  685. return url;
  686. }
  687. /// <summary>
  688. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  689. /// </summary>
  690. public void Dispose()
  691. {
  692. Dispose(true);
  693. GC.SuppressFinalize(this);
  694. }
  695. /// <summary>
  696. /// Releases unmanaged and - optionally - managed resources.
  697. /// </summary>
  698. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  699. protected virtual void Dispose(bool dispose)
  700. {
  701. if (dispose)
  702. {
  703. _httpClients.Clear();
  704. }
  705. }
  706. /// <summary>
  707. /// Throws the cancellation exception.
  708. /// </summary>
  709. /// <param name="options">The options.</param>
  710. /// <param name="client">The client.</param>
  711. /// <param name="cancellationToken">The cancellation token.</param>
  712. /// <param name="exception">The exception.</param>
  713. /// <returns>Exception.</returns>
  714. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  715. {
  716. // If the HttpClient's timeout is reached, it will cancel the Task internally
  717. if (!cancellationToken.IsCancellationRequested)
  718. {
  719. var msg = string.Format("Connection to {0} timed out", options.Url);
  720. if (options.LogErrors)
  721. {
  722. _logger.Error(msg);
  723. }
  724. client.LastTimeout = DateTime.UtcNow;
  725. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  726. return new HttpException(msg, exception)
  727. {
  728. IsTimedOut = true
  729. };
  730. }
  731. return exception;
  732. }
  733. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  734. {
  735. var statusCode = response.StatusCode;
  736. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  737. if (!isSuccessful)
  738. {
  739. if (options.LogErrorResponseBody)
  740. {
  741. try
  742. {
  743. using (var stream = response.GetResponseStream())
  744. {
  745. if (stream != null)
  746. {
  747. using (var reader = new StreamReader(stream))
  748. {
  749. var msg = reader.ReadToEnd();
  750. _logger.Error(msg);
  751. }
  752. }
  753. }
  754. }
  755. catch
  756. {
  757. }
  758. }
  759. throw new HttpException(response.StatusDescription)
  760. {
  761. StatusCode = response.StatusCode
  762. };
  763. }
  764. }
  765. /// <summary>
  766. /// Posts the specified URL.
  767. /// </summary>
  768. /// <param name="url">The URL.</param>
  769. /// <param name="postData">The post data.</param>
  770. /// <param name="cancellationToken">The cancellation token.</param>
  771. /// <returns>Task{Stream}.</returns>
  772. public Task<Stream> Post(string url, Dictionary<string, string> postData, CancellationToken cancellationToken)
  773. {
  774. return Post(url, postData, null, cancellationToken);
  775. }
  776. private Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  777. {
  778. #if NET46
  779. var taskCompletion = new TaskCompletionSource<WebResponse>();
  780. Task<WebResponse> asyncTask = Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
  781. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  782. var callback = new TaskCallback { taskCompletion = taskCompletion };
  783. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  784. // Handle errors
  785. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  786. return taskCompletion.Task;
  787. #endif
  788. return request.GetResponseAsync();
  789. }
  790. private static void TimeoutCallback(object state, bool timedOut)
  791. {
  792. if (timedOut)
  793. {
  794. WebRequest request = (WebRequest)state;
  795. if (state != null)
  796. {
  797. request.Abort();
  798. }
  799. }
  800. }
  801. private class TaskCallback
  802. {
  803. public TaskCompletionSource<WebResponse> taskCompletion;
  804. public void OnSuccess(Task<WebResponse> task)
  805. {
  806. taskCompletion.TrySetResult(task.Result);
  807. }
  808. public void OnError(Task<WebResponse> task)
  809. {
  810. if (task.Exception != null)
  811. {
  812. taskCompletion.TrySetException(task.Exception);
  813. }
  814. else
  815. {
  816. taskCompletion.TrySetException(new List<Exception>());
  817. }
  818. }
  819. }
  820. }
  821. }