HttpClientManager.cs 34 KB

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