HttpClientManager.cs 29 KB

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