HttpClientManager.cs 31 KB

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