HttpClientManager.cs 31 KB

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