HttpClientManager.cs 34 KB

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