HttpClientManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  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. (await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false)).Write(bytes, 0, bytes.Length);
  277. }
  278. catch (Exception ex)
  279. {
  280. throw new HttpException(ex.Message) { IsTimedOut = true };
  281. }
  282. }
  283. if (options.ResourcePool != null)
  284. {
  285. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  286. }
  287. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  288. {
  289. options.ResourcePool?.Release();
  290. throw new HttpException($"Connection to {options.Url} timed out") { IsTimedOut = true };
  291. }
  292. if (options.LogRequest)
  293. {
  294. if (options.LogRequestAsDebug)
  295. {
  296. _logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToUpper(CultureInfo.CurrentCulture), options.Url);
  297. }
  298. else
  299. {
  300. _logger.LogInformation("HttpClientManager {0}: {1}", httpMethod.ToUpper(CultureInfo.CurrentCulture), options.Url);
  301. }
  302. }
  303. try
  304. {
  305. options.CancellationToken.ThrowIfCancellationRequested();
  306. if (!options.BufferContent)
  307. {
  308. var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false);
  309. var httpResponse = (HttpWebResponse)response;
  310. EnsureSuccessStatusCode(client, httpResponse, options);
  311. options.CancellationToken.ThrowIfCancellationRequested();
  312. return GetResponseInfo(httpResponse, httpResponse.GetResponseStream(), GetContentLength(httpResponse), httpResponse);
  313. }
  314. using (var response = await GetResponseAsync(httpWebRequest, TimeSpan.FromMilliseconds(options.TimeoutMs)).ConfigureAwait(false))
  315. {
  316. var httpResponse = (HttpWebResponse)response;
  317. EnsureSuccessStatusCode(client, httpResponse, options);
  318. options.CancellationToken.ThrowIfCancellationRequested();
  319. using (var stream = httpResponse.GetResponseStream())
  320. {
  321. var memoryStream = new MemoryStream();
  322. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  323. memoryStream.Position = 0;
  324. return GetResponseInfo(httpResponse, memoryStream, memoryStream.Length, null);
  325. }
  326. }
  327. }
  328. catch (OperationCanceledException ex)
  329. {
  330. throw GetCancellationException(options, client, options.CancellationToken, ex);
  331. }
  332. catch (Exception ex)
  333. {
  334. throw GetException(ex, options, client);
  335. }
  336. finally
  337. {
  338. options.ResourcePool?.Release();
  339. }
  340. }
  341. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, Stream content, long? contentLength, IDisposable disposable)
  342. {
  343. var responseInfo = new HttpResponseInfo(disposable)
  344. {
  345. Content = content,
  346. StatusCode = httpResponse.StatusCode,
  347. ContentType = httpResponse.ContentType,
  348. ContentLength = contentLength,
  349. ResponseUrl = httpResponse.ResponseUri.ToString()
  350. };
  351. if (httpResponse.Headers != null)
  352. {
  353. SetHeaders(httpResponse.Headers, responseInfo);
  354. }
  355. return responseInfo;
  356. }
  357. private HttpResponseInfo GetResponseInfo(HttpWebResponse httpResponse, string tempFile, long? contentLength)
  358. {
  359. var responseInfo = new HttpResponseInfo
  360. {
  361. TempFilePath = tempFile,
  362. StatusCode = httpResponse.StatusCode,
  363. ContentType = httpResponse.ContentType,
  364. ContentLength = contentLength
  365. };
  366. if (httpResponse.Headers != null)
  367. {
  368. SetHeaders(httpResponse.Headers, responseInfo);
  369. }
  370. return responseInfo;
  371. }
  372. private static void SetHeaders(WebHeaderCollection headers, HttpResponseInfo responseInfo)
  373. {
  374. foreach (var key in headers.AllKeys)
  375. {
  376. responseInfo.Headers[key] = headers[key];
  377. }
  378. }
  379. public Task<HttpResponseInfo> Post(HttpRequestOptions options)
  380. {
  381. return SendAsync(options, "POST");
  382. }
  383. /// <summary>
  384. /// Performs a POST request
  385. /// </summary>
  386. /// <param name="options">The options.</param>
  387. /// <param name="postData">Params to add to the POST data.</param>
  388. /// <returns>stream on success, null on failure</returns>
  389. public async Task<Stream> Post(HttpRequestOptions options, Dictionary<string, string> postData)
  390. {
  391. options.SetPostData(postData);
  392. var response = await Post(options).ConfigureAwait(false);
  393. return response.Content;
  394. }
  395. /// <summary>
  396. /// Downloads the contents of a given url into a temporary location
  397. /// </summary>
  398. /// <param name="options">The options.</param>
  399. /// <returns>Task{System.String}.</returns>
  400. public async Task<string> GetTempFile(HttpRequestOptions options)
  401. {
  402. var response = await GetTempFileResponse(options).ConfigureAwait(false);
  403. return response.TempFilePath;
  404. }
  405. public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
  406. {
  407. ValidateParams(options);
  408. Directory.CreateDirectory(_appPaths.TempDirectory);
  409. var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
  410. if (options.Progress == null)
  411. {
  412. throw new ArgumentException("Options did not have a Progress value.", nameof(options));
  413. }
  414. options.CancellationToken.ThrowIfCancellationRequested();
  415. var httpWebRequest = GetRequest(options, "GET");
  416. if (options.ResourcePool != null)
  417. {
  418. await options.ResourcePool.WaitAsync(options.CancellationToken).ConfigureAwait(false);
  419. }
  420. options.Progress.Report(0);
  421. if (options.LogRequest)
  422. {
  423. if (options.LogRequestAsDebug)
  424. {
  425. _logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  426. }
  427. else
  428. {
  429. _logger.LogInformation("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
  430. }
  431. }
  432. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  433. try
  434. {
  435. options.CancellationToken.ThrowIfCancellationRequested();
  436. using (var response = await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
  437. {
  438. var httpResponse = (HttpWebResponse)response;
  439. EnsureSuccessStatusCode(client, httpResponse, options);
  440. options.CancellationToken.ThrowIfCancellationRequested();
  441. var contentLength = GetContentLength(httpResponse);
  442. using (var stream = httpResponse.GetResponseStream())
  443. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  444. {
  445. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  446. }
  447. options.Progress.Report(100);
  448. return GetResponseInfo(httpResponse, tempFile, contentLength);
  449. }
  450. }
  451. catch (Exception ex)
  452. {
  453. DeleteTempFile(tempFile);
  454. throw GetException(ex, options, client);
  455. }
  456. finally
  457. {
  458. options.ResourcePool?.Release();
  459. }
  460. }
  461. private static long? GetContentLength(HttpWebResponse response)
  462. {
  463. var length = response.ContentLength;
  464. if (length == 0)
  465. {
  466. return null;
  467. }
  468. return length;
  469. }
  470. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  471. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  472. {
  473. if (ex is HttpException)
  474. {
  475. return ex;
  476. }
  477. var webException = ex as WebException
  478. ?? ex.InnerException as WebException;
  479. if (webException != null)
  480. {
  481. if (options.LogErrors)
  482. {
  483. _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
  484. }
  485. var exception = new HttpException(webException.Message, webException);
  486. using (var response = webException.Response as HttpWebResponse)
  487. {
  488. if (response != null)
  489. {
  490. exception.StatusCode = response.StatusCode;
  491. if ((int)response.StatusCode == 429)
  492. {
  493. client.LastTimeout = DateTime.UtcNow;
  494. }
  495. }
  496. }
  497. if (!exception.StatusCode.HasValue)
  498. {
  499. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  500. webException.Status == WebExceptionStatus.ConnectFailure)
  501. {
  502. exception.IsTimedOut = true;
  503. }
  504. }
  505. return exception;
  506. }
  507. var operationCanceledException = ex as OperationCanceledException
  508. ?? ex.InnerException as OperationCanceledException;
  509. if (operationCanceledException != null)
  510. {
  511. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  512. }
  513. if (options.LogErrors)
  514. {
  515. _logger.LogError(ex, "Error getting response from {url}", options.Url);
  516. }
  517. return ex;
  518. }
  519. private void DeleteTempFile(string file)
  520. {
  521. try
  522. {
  523. _fileSystem.DeleteFile(file);
  524. }
  525. catch (IOException)
  526. {
  527. // Might not have been created at all. No need to worry.
  528. }
  529. }
  530. private void ValidateParams(HttpRequestOptions options)
  531. {
  532. if (string.IsNullOrEmpty(options.Url))
  533. {
  534. throw new ArgumentNullException(nameof(options));
  535. }
  536. }
  537. /// <summary>
  538. /// Gets the host from URL.
  539. /// </summary>
  540. /// <param name="url">The URL.</param>
  541. /// <returns>System.String.</returns>
  542. private static string GetHostFromUrl(string url)
  543. {
  544. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  545. if (index != -1)
  546. {
  547. url = url.Substring(index + 3);
  548. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  549. if (!string.IsNullOrWhiteSpace(host))
  550. {
  551. return host;
  552. }
  553. }
  554. return url;
  555. }
  556. /// <summary>
  557. /// Throws the cancellation exception.
  558. /// </summary>
  559. /// <param name="options">The options.</param>
  560. /// <param name="client">The client.</param>
  561. /// <param name="cancellationToken">The cancellation token.</param>
  562. /// <param name="exception">The exception.</param>
  563. /// <returns>Exception.</returns>
  564. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  565. {
  566. // If the HttpClient's timeout is reached, it will cancel the Task internally
  567. if (!cancellationToken.IsCancellationRequested)
  568. {
  569. var msg = string.Format("Connection to {0} timed out", options.Url);
  570. if (options.LogErrors)
  571. {
  572. _logger.LogError(msg);
  573. }
  574. client.LastTimeout = DateTime.UtcNow;
  575. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  576. return new HttpException(msg, exception)
  577. {
  578. IsTimedOut = true
  579. };
  580. }
  581. return exception;
  582. }
  583. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  584. {
  585. var statusCode = response.StatusCode;
  586. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  587. if (isSuccessful)
  588. {
  589. return;
  590. }
  591. if (options.LogErrorResponseBody)
  592. {
  593. try
  594. {
  595. using (var stream = response.GetResponseStream())
  596. {
  597. if (stream != null)
  598. {
  599. using (var reader = new StreamReader(stream))
  600. {
  601. var msg = reader.ReadToEnd();
  602. _logger.LogError(msg);
  603. }
  604. }
  605. }
  606. }
  607. catch
  608. {
  609. }
  610. }
  611. throw new HttpException(response.StatusDescription)
  612. {
  613. StatusCode = response.StatusCode
  614. };
  615. }
  616. private static Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  617. {
  618. var taskCompletion = new TaskCompletionSource<WebResponse>();
  619. var asyncTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
  620. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  621. var callback = new TaskCallback { taskCompletion = taskCompletion };
  622. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  623. // Handle errors
  624. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  625. return taskCompletion.Task;
  626. }
  627. private static void TimeoutCallback(object state, bool timedOut)
  628. {
  629. if (timedOut && state != null)
  630. {
  631. var request = (WebRequest)state;
  632. request.Abort();
  633. }
  634. }
  635. private class TaskCallback
  636. {
  637. public TaskCompletionSource<WebResponse> taskCompletion;
  638. public void OnSuccess(Task<WebResponse> task)
  639. {
  640. taskCompletion.TrySetResult(task.Result);
  641. }
  642. public void OnError(Task<WebResponse> task)
  643. {
  644. if (task.Exception == null)
  645. {
  646. taskCompletion.TrySetException(Enumerable.Empty<Exception>());
  647. }
  648. else
  649. {
  650. taskCompletion.TrySetException(task.Exception);
  651. }
  652. }
  653. }
  654. }
  655. }