2
0

HttpClientManager.cs 30 KB

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