HttpClientManager.cs 34 KB

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