HttpClientManager.cs 29 KB

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