HttpClientManager.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. using Microsoft.Net.Http.Headers;
  19. namespace Emby.Server.Implementations.HttpClientManager
  20. {
  21. /// <summary>
  22. /// Class HttpClientManager
  23. /// </summary>
  24. public class HttpClientManager : IHttpClient
  25. {
  26. /// <summary>
  27. /// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
  28. /// </summary>
  29. private const int TimeoutSeconds = 30;
  30. /// <summary>
  31. /// The _logger
  32. /// </summary>
  33. private readonly ILogger _logger;
  34. /// <summary>
  35. /// The _app paths
  36. /// </summary>
  37. private readonly IApplicationPaths _appPaths;
  38. private readonly IFileSystem _fileSystem;
  39. private readonly Func<string> _defaultUserAgentFn;
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="HttpClientManager" /> class.
  42. /// </summary>
  43. public HttpClientManager(
  44. IApplicationPaths appPaths,
  45. ILoggerFactory loggerFactory,
  46. IFileSystem fileSystem,
  47. Func<string> defaultUserAgentFn)
  48. {
  49. if (appPaths == null)
  50. {
  51. throw new ArgumentNullException(nameof(appPaths));
  52. }
  53. if (loggerFactory == null)
  54. {
  55. throw new ArgumentNullException(nameof(loggerFactory));
  56. }
  57. _logger = loggerFactory.CreateLogger("HttpClient");
  58. _fileSystem = fileSystem;
  59. _appPaths = appPaths;
  60. _defaultUserAgentFn = defaultUserAgentFn;
  61. // http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
  62. ServicePointManager.Expect100Continue = false;
  63. }
  64. /// <summary>
  65. /// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
  66. /// DON'T dispose it after use.
  67. /// </summary>
  68. /// <value>The HTTP clients.</value>
  69. private readonly ConcurrentDictionary<string, HttpClientInfo> _httpClients = new ConcurrentDictionary<string, HttpClientInfo>();
  70. /// <summary>
  71. /// Gets
  72. /// </summary>
  73. /// <param name="host">The host.</param>
  74. /// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
  75. /// <returns>HttpClient.</returns>
  76. /// <exception cref="ArgumentNullException">host</exception>
  77. private HttpClientInfo GetHttpClient(string host, bool enableHttpCompression)
  78. {
  79. if (string.IsNullOrEmpty(host))
  80. {
  81. throw new ArgumentNullException(nameof(host));
  82. }
  83. var key = host + enableHttpCompression;
  84. if (!_httpClients.TryGetValue(key, out var client))
  85. {
  86. client = new HttpClientInfo();
  87. _httpClients.TryAdd(key, client);
  88. }
  89. return client;
  90. }
  91. private WebRequest GetRequest(HttpRequestOptions options, string method)
  92. {
  93. string url = options.Url;
  94. var uriAddress = new Uri(url);
  95. string userInfo = uriAddress.UserInfo;
  96. if (!string.IsNullOrWhiteSpace(userInfo))
  97. {
  98. _logger.LogInformation("Found userInfo in url: {0} ... url: {1}", userInfo, url);
  99. url = url.Replace(userInfo + "@", string.Empty);
  100. }
  101. var request = WebRequest.Create(url);
  102. if (request is HttpWebRequest httpWebRequest)
  103. {
  104. AddRequestHeaders(httpWebRequest, options);
  105. if (options.EnableHttpCompression)
  106. {
  107. httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate;
  108. if (options.DecompressionMethod.HasValue
  109. && options.DecompressionMethod.Value == CompressionMethod.Gzip)
  110. {
  111. httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
  112. }
  113. }
  114. else
  115. {
  116. httpWebRequest.AutomaticDecompression = DecompressionMethods.None;
  117. }
  118. httpWebRequest.KeepAlive = options.EnableKeepAlive;
  119. if (!string.IsNullOrEmpty(options.Host))
  120. {
  121. httpWebRequest.Host = options.Host;
  122. }
  123. if (!string.IsNullOrEmpty(options.Referer))
  124. {
  125. httpWebRequest.Referer = options.Referer;
  126. }
  127. }
  128. request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
  129. request.Method = method;
  130. request.Timeout = options.TimeoutMs;
  131. if (!string.IsNullOrWhiteSpace(userInfo))
  132. {
  133. var parts = userInfo.Split(':');
  134. if (parts.Length == 2)
  135. {
  136. request.Credentials = GetCredential(url, parts[0], parts[1]);
  137. // TODO: .net core ??
  138. request.PreAuthenticate = true;
  139. }
  140. }
  141. return request;
  142. }
  143. private static CredentialCache GetCredential(string url, string username, string password)
  144. {
  145. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
  146. var credentialCache = new CredentialCache();
  147. credentialCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
  148. return credentialCache;
  149. }
  150. private void AddRequestHeaders(HttpWebRequest request, HttpRequestOptions options)
  151. {
  152. var hasUserAgent = false;
  153. foreach (var header in options.RequestHeaders)
  154. {
  155. if (string.Equals(header.Key, HeaderNames.Accept, StringComparison.OrdinalIgnoreCase))
  156. {
  157. request.Accept = header.Value;
  158. }
  159. else if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
  160. {
  161. SetUserAgent(request, header.Value);
  162. hasUserAgent = true;
  163. }
  164. else
  165. {
  166. request.Headers.Set(header.Key, header.Value);
  167. }
  168. }
  169. if (!hasUserAgent && options.EnableDefaultUserAgent)
  170. {
  171. SetUserAgent(request, _defaultUserAgentFn());
  172. }
  173. }
  174. private static void SetUserAgent(HttpWebRequest request, string userAgent)
  175. {
  176. request.UserAgent = userAgent;
  177. }
  178. /// <summary>
  179. /// Gets the response internal.
  180. /// </summary>
  181. /// <param name="options">The options.</param>
  182. /// <returns>Task{HttpResponseInfo}.</returns>
  183. public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
  184. {
  185. return SendAsync(options, "GET");
  186. }
  187. /// <summary>
  188. /// Performs a GET request and returns the resulting stream
  189. /// </summary>
  190. /// <param name="options">The options.</param>
  191. /// <returns>Task{Stream}.</returns>
  192. public async Task<Stream> Get(HttpRequestOptions options)
  193. {
  194. var response = await GetResponse(options).ConfigureAwait(false);
  195. return response.Content;
  196. }
  197. /// <summary>
  198. /// send as an asynchronous operation.
  199. /// </summary>
  200. /// <param name="options">The options.</param>
  201. /// <param name="httpMethod">The HTTP method.</param>
  202. /// <returns>Task{HttpResponseInfo}.</returns>
  203. /// <exception cref="HttpException">
  204. /// </exception>
  205. public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
  206. {
  207. if (options.CacheMode == CacheMode.None)
  208. {
  209. return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  210. }
  211. var url = options.Url;
  212. var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
  213. var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
  214. var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
  215. if (response != null)
  216. {
  217. return response;
  218. }
  219. response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
  220. if (response.StatusCode == HttpStatusCode.OK)
  221. {
  222. await CacheResponse(response, responseCachePath).ConfigureAwait(false);
  223. }
  224. return response;
  225. }
  226. private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
  227. {
  228. if (File.Exists(responseCachePath)
  229. && _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
  230. {
  231. var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
  232. return new HttpResponseInfo
  233. {
  234. ResponseUrl = url,
  235. Content = stream,
  236. StatusCode = HttpStatusCode.OK,
  237. ContentLength = stream.Length
  238. };
  239. }
  240. return null;
  241. }
  242. private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
  243. {
  244. Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
  245. using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
  246. {
  247. await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
  248. response.Content.Position = 0;
  249. }
  250. }
  251. private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, string httpMethod)
  252. {
  253. ValidateParams(options);
  254. options.CancellationToken.ThrowIfCancellationRequested();
  255. var client = GetHttpClient(GetHostFromUrl(options.Url), options.EnableHttpCompression);
  256. if ((DateTime.UtcNow - client.LastTimeout).TotalSeconds < TimeoutSeconds)
  257. {
  258. throw new HttpException(string.Format("Cancelling connection to {0} due to a previous timeout.", options.Url))
  259. {
  260. IsTimedOut = true
  261. };
  262. }
  263. var httpWebRequest = GetRequest(options, httpMethod);
  264. if (options.RequestContentBytes != null ||
  265. !string.IsNullOrEmpty(options.RequestContent) ||
  266. string.Equals(httpMethod, "post", StringComparison.OrdinalIgnoreCase))
  267. {
  268. try
  269. {
  270. var bytes = options.RequestContentBytes ?? Encoding.UTF8.GetBytes(options.RequestContent ?? string.Empty);
  271. var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
  272. if (options.AppendCharsetToMimeType)
  273. {
  274. contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\"";
  275. }
  276. httpWebRequest.ContentType = contentType;
  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. using (var stream = httpResponse.GetResponseStream())
  444. using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  445. {
  446. await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
  447. }
  448. options.Progress.Report(100);
  449. return GetResponseInfo(httpResponse, tempFile, contentLength);
  450. }
  451. }
  452. catch (Exception ex)
  453. {
  454. DeleteTempFile(tempFile);
  455. throw GetException(ex, options, client);
  456. }
  457. finally
  458. {
  459. options.ResourcePool?.Release();
  460. }
  461. }
  462. private static long? GetContentLength(HttpWebResponse response)
  463. {
  464. var length = response.ContentLength;
  465. if (length == 0)
  466. {
  467. return null;
  468. }
  469. return length;
  470. }
  471. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  472. private Exception GetException(Exception ex, HttpRequestOptions options, HttpClientInfo client)
  473. {
  474. if (ex is HttpException)
  475. {
  476. return ex;
  477. }
  478. var webException = ex as WebException
  479. ?? ex.InnerException as WebException;
  480. if (webException != null)
  481. {
  482. if (options.LogErrors)
  483. {
  484. _logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
  485. }
  486. var exception = new HttpException(webException.Message, webException);
  487. using (var response = webException.Response as HttpWebResponse)
  488. {
  489. if (response != null)
  490. {
  491. exception.StatusCode = response.StatusCode;
  492. if ((int)response.StatusCode == 429)
  493. {
  494. client.LastTimeout = DateTime.UtcNow;
  495. }
  496. }
  497. }
  498. if (!exception.StatusCode.HasValue)
  499. {
  500. if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
  501. webException.Status == WebExceptionStatus.ConnectFailure)
  502. {
  503. exception.IsTimedOut = true;
  504. }
  505. }
  506. return exception;
  507. }
  508. var operationCanceledException = ex as OperationCanceledException
  509. ?? ex.InnerException as OperationCanceledException;
  510. if (operationCanceledException != null)
  511. {
  512. return GetCancellationException(options, client, options.CancellationToken, operationCanceledException);
  513. }
  514. if (options.LogErrors)
  515. {
  516. _logger.LogError(ex, "Error getting response from {url}", options.Url);
  517. }
  518. return ex;
  519. }
  520. private void DeleteTempFile(string file)
  521. {
  522. try
  523. {
  524. _fileSystem.DeleteFile(file);
  525. }
  526. catch (IOException)
  527. {
  528. // Might not have been created at all. No need to worry.
  529. }
  530. }
  531. private void ValidateParams(HttpRequestOptions options)
  532. {
  533. if (string.IsNullOrEmpty(options.Url))
  534. {
  535. throw new ArgumentNullException(nameof(options));
  536. }
  537. }
  538. /// <summary>
  539. /// Gets the host from URL.
  540. /// </summary>
  541. /// <param name="url">The URL.</param>
  542. /// <returns>System.String.</returns>
  543. private static string GetHostFromUrl(string url)
  544. {
  545. var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  546. if (index != -1)
  547. {
  548. url = url.Substring(index + 3);
  549. var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
  550. if (!string.IsNullOrWhiteSpace(host))
  551. {
  552. return host;
  553. }
  554. }
  555. return url;
  556. }
  557. /// <summary>
  558. /// Throws the cancellation exception.
  559. /// </summary>
  560. /// <param name="options">The options.</param>
  561. /// <param name="client">The client.</param>
  562. /// <param name="cancellationToken">The cancellation token.</param>
  563. /// <param name="exception">The exception.</param>
  564. /// <returns>Exception.</returns>
  565. private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
  566. {
  567. // If the HttpClient's timeout is reached, it will cancel the Task internally
  568. if (!cancellationToken.IsCancellationRequested)
  569. {
  570. var msg = string.Format("Connection to {0} timed out", options.Url);
  571. if (options.LogErrors)
  572. {
  573. _logger.LogError(msg);
  574. }
  575. client.LastTimeout = DateTime.UtcNow;
  576. // Throw an HttpException so that the caller doesn't think it was cancelled by user code
  577. return new HttpException(msg, exception)
  578. {
  579. IsTimedOut = true
  580. };
  581. }
  582. return exception;
  583. }
  584. private void EnsureSuccessStatusCode(HttpClientInfo client, HttpWebResponse response, HttpRequestOptions options)
  585. {
  586. var statusCode = response.StatusCode;
  587. var isSuccessful = statusCode >= HttpStatusCode.OK && statusCode <= (HttpStatusCode)299;
  588. if (isSuccessful)
  589. {
  590. return;
  591. }
  592. if (options.LogErrorResponseBody)
  593. {
  594. try
  595. {
  596. using (var stream = response.GetResponseStream())
  597. {
  598. if (stream != null)
  599. {
  600. using (var reader = new StreamReader(stream))
  601. {
  602. var msg = reader.ReadToEnd();
  603. _logger.LogError(msg);
  604. }
  605. }
  606. }
  607. }
  608. catch
  609. {
  610. }
  611. }
  612. throw new HttpException(response.StatusDescription)
  613. {
  614. StatusCode = response.StatusCode
  615. };
  616. }
  617. private static Task<WebResponse> GetResponseAsync(WebRequest request, TimeSpan timeout)
  618. {
  619. var taskCompletion = new TaskCompletionSource<WebResponse>();
  620. var asyncTask = Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null);
  621. ThreadPool.RegisterWaitForSingleObject((asyncTask as IAsyncResult).AsyncWaitHandle, TimeoutCallback, request, timeout, true);
  622. var callback = new TaskCallback { taskCompletion = taskCompletion };
  623. asyncTask.ContinueWith(callback.OnSuccess, TaskContinuationOptions.NotOnFaulted);
  624. // Handle errors
  625. asyncTask.ContinueWith(callback.OnError, TaskContinuationOptions.OnlyOnFaulted);
  626. return taskCompletion.Task;
  627. }
  628. private static void TimeoutCallback(object state, bool timedOut)
  629. {
  630. if (timedOut && state != null)
  631. {
  632. var request = (WebRequest)state;
  633. request.Abort();
  634. }
  635. }
  636. private class TaskCallback
  637. {
  638. public TaskCompletionSource<WebResponse> taskCompletion;
  639. public void OnSuccess(Task<WebResponse> task)
  640. {
  641. taskCompletion.TrySetResult(task.Result);
  642. }
  643. public void OnError(Task<WebResponse> task)
  644. {
  645. if (task.Exception == null)
  646. {
  647. taskCompletion.TrySetException(Enumerable.Empty<Exception>());
  648. }
  649. else
  650. {
  651. taskCompletion.TrySetException(task.Exception);
  652. }
  653. }
  654. }
  655. }
  656. }