2
0

HttpClientManager.cs 34 KB

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