HttpClientManager.cs 28 KB

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