HttpClientManager.cs 31 KB

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