jellyfin/Emby.Server.Implementations/HttpClientManager/HttpClientManager.cs

651 lines
23 KiB
C#
Raw Normal View History

using System;
2016-10-29 05:40:15 +00:00
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
2016-10-29 05:40:15 +00:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
2016-10-29 05:40:15 +00:00
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
2016-10-29 05:40:15 +00:00
namespace Emby.Server.Implementations.HttpClientManager
2016-10-29 05:40:15 +00:00
{
/// <summary>
/// Class HttpClientManager
/// </summary>
public class HttpClientManager : IHttpClient
{
/// <summary>
/// When one request to a host times out, we'll ban all other requests for this period of time, to prevent scans from stalling
/// </summary>
private const int TimeoutSeconds = 30;
/// <summary>
/// The _logger
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// The _app paths
/// </summary>
private readonly IApplicationPaths _appPaths;
private readonly IFileSystem _fileSystem;
2017-02-09 03:58:04 +00:00
private readonly Func<string> _defaultUserAgentFn;
2016-10-29 05:40:15 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientManager" /> class.
/// </summary>
public HttpClientManager(
IApplicationPaths appPaths,
ILoggerFactory loggerFactory,
IFileSystem fileSystem,
Func<string> defaultUserAgentFn)
2016-10-29 05:40:15 +00:00
{
if (appPaths == null)
{
throw new ArgumentNullException(nameof(appPaths));
2016-10-29 05:40:15 +00:00
}
if (loggerFactory == null)
2016-10-29 05:40:15 +00:00
{
throw new ArgumentNullException(nameof(loggerFactory));
2016-10-29 05:40:15 +00:00
}
_logger = loggerFactory.CreateLogger(nameof(HttpClientManager));
2016-10-29 05:40:15 +00:00
_fileSystem = fileSystem;
_appPaths = appPaths;
2017-02-09 03:58:04 +00:00
_defaultUserAgentFn = defaultUserAgentFn;
2016-10-29 05:40:15 +00:00
// http://stackoverflow.com/questions/566437/http-post-returns-the-error-417-expectation-failed-c
ServicePointManager.Expect100Continue = false;
}
/// <summary>
/// Holds a dictionary of http clients by host. Use GetHttpClient(host) to retrieve or create a client for web requests.
/// DON'T dispose it after use.
/// </summary>
/// <value>The HTTP clients.</value>
private readonly ConcurrentDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets
/// </summary>
/// <param name="url">The host.</param>
2016-10-29 05:40:15 +00:00
/// <param name="enableHttpCompression">if set to <c>true</c> [enable HTTP compression].</param>
/// <returns>HttpClient.</returns>
2019-01-13 20:37:13 +00:00
/// <exception cref="ArgumentNullException">host</exception>
private HttpClient GetHttpClient(string url, bool enableHttpCompression)
2016-10-29 05:40:15 +00:00
{
var key = GetHostFromUrl(url) + enableHttpCompression;
2016-10-29 05:40:15 +00:00
if (!_httpClients.TryGetValue(key, out var client))
2016-10-29 05:40:15 +00:00
{
client = new HttpClient()
{
BaseAddress = new Uri(url)
};
2016-10-29 05:40:15 +00:00
_httpClients.TryAdd(key, client);
}
return client;
}
private HttpRequestMessage GetRequestMessage(HttpRequestOptions options, HttpMethod method)
2016-10-29 05:40:15 +00:00
{
2018-12-30 12:01:52 +00:00
string url = options.Url;
2019-01-13 20:37:13 +00:00
var uriAddress = new Uri(url);
2018-12-30 12:01:52 +00:00
string userInfo = uriAddress.UserInfo;
2016-10-29 05:40:15 +00:00
if (!string.IsNullOrWhiteSpace(userInfo))
{
_logger.LogWarning("Found userInfo in url: {0} ... url: {1}", userInfo, url);
2016-10-29 05:40:15 +00:00
url = url.Replace(userInfo + "@", string.Empty);
}
var request = new HttpRequestMessage(method, url);
2016-10-29 05:40:15 +00:00
AddRequestHeaders(request, options);
2016-10-29 05:40:15 +00:00
if (options.EnableHttpCompression)
{
if (options.DecompressionMethod.HasValue
&& options.DecompressionMethod.Value == CompressionMethod.Gzip)
2016-11-03 19:07:48 +00:00
{
request.Headers.Add(HeaderNames.AcceptEncoding, new[] { "gzip", "deflate" });
2016-11-03 19:07:48 +00:00
}
else
{
request.Headers.Add(HeaderNames.AcceptEncoding, "deflate");
2016-11-03 19:07:48 +00:00
}
}
2016-10-29 05:40:15 +00:00
if (options.EnableKeepAlive)
{
request.Headers.Add(HeaderNames.Connection, "Keep-Alive");
}
2016-10-29 05:40:15 +00:00
if (!string.IsNullOrEmpty(options.Host))
{
request.Headers.Add(HeaderNames.Host, options.Host);
}
2016-10-29 05:40:15 +00:00
if (!string.IsNullOrEmpty(options.Referer))
{
request.Headers.Add(HeaderNames.Referer, options.Referer);
2016-10-29 05:40:15 +00:00
}
//request.Headers.Add(HeaderNames.CacheControl, "no-cache");
//request.Headers.Add(HeaderNames., options.TimeoutMs;
/*
2016-10-29 05:40:15 +00:00
if (!string.IsNullOrWhiteSpace(userInfo))
{
var parts = userInfo.Split(':');
if (parts.Length == 2)
{
request.Headers.Add(HeaderNames., GetCredential(url, parts[0], parts[1]);
2016-10-29 05:40:15 +00:00
}
}
*/
2016-10-29 05:40:15 +00:00
return request;
}
private void AddRequestHeaders(HttpRequestMessage request, HttpRequestOptions options)
2016-10-29 05:40:15 +00:00
{
2017-02-08 18:50:50 +00:00
var hasUserAgent = false;
foreach (var header in options.RequestHeaders)
2016-10-29 05:40:15 +00:00
{
if (string.Equals(header.Key, HeaderNames.UserAgent, StringComparison.OrdinalIgnoreCase))
2016-10-29 05:40:15 +00:00
{
2017-02-08 18:50:50 +00:00
hasUserAgent = true;
2016-10-29 05:40:15 +00:00
}
request.Headers.Add(header.Key, header.Value);
2016-10-29 05:40:15 +00:00
}
2017-02-08 18:50:50 +00:00
if (!hasUserAgent && options.EnableDefaultUserAgent)
{
request.Headers.Add(HeaderNames.UserAgent, _defaultUserAgentFn());
2017-02-08 18:50:50 +00:00
}
}
2016-10-29 05:40:15 +00:00
/// <summary>
/// Gets the response internal.
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
public Task<HttpResponseInfo> GetResponse(HttpRequestOptions options)
{
return SendAsync(options, HttpMethod.Get);
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Performs a GET request and returns the resulting stream
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task{Stream}.</returns>
public async Task<Stream> Get(HttpRequestOptions options)
{
var response = await GetResponse(options).ConfigureAwait(false);
return response.Content;
}
/// <summary>
/// send as an asynchronous operation.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
/// <exception cref="HttpException">
/// </exception>
public Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, string httpMethod)
{
var httpMethod2 = GetHttpMethod(httpMethod);
return SendAsync(options, httpMethod2);
}
/// <summary>
/// send as an asynchronous operation.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <returns>Task{HttpResponseInfo}.</returns>
/// <exception cref="HttpException">
/// </exception>
public async Task<HttpResponseInfo> SendAsync(HttpRequestOptions options, HttpMethod httpMethod)
2016-10-29 05:40:15 +00:00
{
if (options.CacheMode == CacheMode.None)
{
return await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
}
var url = options.Url;
2019-01-27 11:03:43 +00:00
var urlHash = url.ToLowerInvariant().GetMD5().ToString("N");
2016-10-29 05:40:15 +00:00
var responseCachePath = Path.Combine(_appPaths.CachePath, "httpclient", urlHash);
var response = GetCachedResponse(responseCachePath, options.CacheLength, url);
2016-10-29 05:40:15 +00:00
if (response != null)
{
return response;
}
response = await SendAsyncInternal(options, httpMethod).ConfigureAwait(false);
if (response.StatusCode == HttpStatusCode.OK)
{
await CacheResponse(response, responseCachePath).ConfigureAwait(false);
}
return response;
}
private HttpMethod GetHttpMethod(string httpMethod)
{
if (httpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Delete;
}
else if (httpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Get;
}
else if (httpMethod.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Head;
}
else if (httpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Options;
}
else if (httpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Post;
}
else if (httpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Put;
}
else if (httpMethod.Equals("TRACE", StringComparison.OrdinalIgnoreCase))
{
return HttpMethod.Trace;
}
throw new ArgumentException("Invalid HTTP method", nameof(httpMethod));
}
private HttpResponseInfo GetCachedResponse(string responseCachePath, TimeSpan cacheLength, string url)
2016-10-29 05:40:15 +00:00
{
if (File.Exists(responseCachePath)
&& _fileSystem.GetLastWriteTimeUtc(responseCachePath).Add(cacheLength) > DateTime.UtcNow)
2016-10-29 05:40:15 +00:00
{
var stream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read, true);
2016-10-29 05:40:15 +00:00
return new HttpResponseInfo
{
ResponseUrl = url,
Content = stream,
StatusCode = HttpStatusCode.OK,
ContentLength = stream.Length
};
2016-10-29 05:40:15 +00:00
}
return null;
}
private async Task CacheResponse(HttpResponseInfo response, string responseCachePath)
{
Directory.CreateDirectory(Path.GetDirectoryName(responseCachePath));
2016-10-29 05:40:15 +00:00
using (var fileStream = _fileSystem.GetFileStream(responseCachePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None, true))
2016-10-29 05:40:15 +00:00
{
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
response.Content.Position = 0;
2016-10-29 05:40:15 +00:00
}
}
private async Task<HttpResponseInfo> SendAsyncInternal(HttpRequestOptions options, HttpMethod httpMethod)
2016-10-29 05:40:15 +00:00
{
ValidateParams(options);
options.CancellationToken.ThrowIfCancellationRequested();
var client = GetHttpClient(options.Url, options.EnableHttpCompression);
2016-10-29 05:40:15 +00:00
var httpWebRequest = GetRequestMessage(options, httpMethod);
2016-10-29 05:40:15 +00:00
if (options.RequestContentBytes != null ||
!string.IsNullOrEmpty(options.RequestContent) ||
httpMethod == HttpMethod.Post)
2016-10-29 05:40:15 +00:00
{
2017-02-09 23:25:10 +00:00
try
{
httpWebRequest.Content = new StringContent(Encoding.UTF8.GetString(options.RequestContentBytes) ?? options.RequestContent ?? string.Empty);
2016-10-29 05:40:15 +00:00
var contentType = options.RequestContentType ?? "application/x-www-form-urlencoded";
2017-10-22 23:36:22 +00:00
if (options.AppendCharsetToMimeType)
{
2017-10-22 23:36:22 +00:00
contentType = contentType.TrimEnd(';') + "; charset=\"utf-8\"";
}
httpWebRequest.Headers.Add(HeaderNames.ContentType, contentType);
await client.SendAsync(httpWebRequest).ConfigureAwait(false);
2017-02-09 23:25:10 +00:00
}
catch (Exception ex)
{
throw new HttpException(ex.Message) { IsTimedOut = true };
}
2016-10-29 05:40:15 +00:00
}
if (options.LogRequest)
{
_logger.LogDebug("HttpClientManager {0}: {1}", httpMethod.ToString(), options.Url);
2016-10-29 05:40:15 +00:00
}
try
{
options.CancellationToken.ThrowIfCancellationRequested();
/*if (!options.BufferContent)
2016-10-29 05:40:15 +00:00
{
var response = await client.HttpClient.SendAsync(httpWebRequest).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
await EnsureSuccessStatusCode(client, response, options).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
options.CancellationToken.ThrowIfCancellationRequested();
return GetResponseInfo(response, await response.Content.ReadAsStreamAsync().ConfigureAwait(false), response.Content.Headers.ContentLength, response);
}*/
2016-10-29 05:40:15 +00:00
using (var response = await client.SendAsync(httpWebRequest).ConfigureAwait(false))
2016-10-29 05:40:15 +00:00
{
await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
options.CancellationToken.ThrowIfCancellationRequested();
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
2016-10-29 05:40:15 +00:00
{
var memoryStream = new MemoryStream();
2016-10-29 05:40:15 +00:00
await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
memoryStream.Position = 0;
return GetResponseInfo(response, memoryStream, memoryStream.Length, null);
2016-10-29 05:40:15 +00:00
}
}
}
catch (OperationCanceledException ex)
{
throw GetCancellationException(options, options.CancellationToken, ex);
2016-10-29 05:40:15 +00:00
}
}
private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, Stream content, long? contentLength, IDisposable disposable)
2016-10-29 05:40:15 +00:00
{
var responseInfo = new HttpResponseInfo(disposable)
{
Content = content,
StatusCode = httpResponse.StatusCode,
ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
2016-10-29 05:40:15 +00:00
ContentLength = contentLength,
ResponseUrl = httpResponse.Content.Headers.ContentLocation?.ToString()
2016-10-29 05:40:15 +00:00
};
if (httpResponse.Headers != null)
{
SetHeaders(httpResponse.Content.Headers, responseInfo);
2016-10-29 05:40:15 +00:00
}
return responseInfo;
}
private HttpResponseInfo GetResponseInfo(HttpResponseMessage httpResponse, string tempFile, long? contentLength)
2016-10-29 05:40:15 +00:00
{
var responseInfo = new HttpResponseInfo
{
TempFilePath = tempFile,
StatusCode = httpResponse.StatusCode,
ContentType = httpResponse.Content.Headers.ContentType?.MediaType,
2016-10-29 05:40:15 +00:00
ContentLength = contentLength
};
if (httpResponse.Headers != null)
{
SetHeaders(httpResponse.Content.Headers, responseInfo);
2016-10-29 05:40:15 +00:00
}
return responseInfo;
}
private static void SetHeaders(HttpContentHeaders headers, HttpResponseInfo responseInfo)
2016-10-29 05:40:15 +00:00
{
foreach (var key in headers)
2016-10-29 05:40:15 +00:00
{
responseInfo.Headers[key.Key] = string.Join(", ", key.Value);
2016-10-29 05:40:15 +00:00
}
}
public Task<HttpResponseInfo> Post(HttpRequestOptions options)
{
return SendAsync(options, HttpMethod.Post);
2016-10-29 05:40:15 +00:00
}
/// <summary>
/// Downloads the contents of a given url into a temporary location
/// </summary>
/// <param name="options">The options.</param>
/// <returns>Task{System.String}.</returns>
public async Task<string> GetTempFile(HttpRequestOptions options)
{
using (var response = await GetTempFileResponse(options).ConfigureAwait(false))
{
return response.TempFilePath;
}
2016-10-29 05:40:15 +00:00
}
public async Task<HttpResponseInfo> GetTempFileResponse(HttpRequestOptions options)
{
ValidateParams(options);
Directory.CreateDirectory(_appPaths.TempDirectory);
2016-10-29 05:40:15 +00:00
var tempFile = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + ".tmp");
if (options.Progress == null)
{
throw new ArgumentException("Options did not have a Progress value.", nameof(options));
2016-10-29 05:40:15 +00:00
}
options.CancellationToken.ThrowIfCancellationRequested();
var httpWebRequest = GetRequestMessage(options, HttpMethod.Get);
2016-10-29 05:40:15 +00:00
options.Progress.Report(0);
if (options.LogRequest)
{
_logger.LogDebug("HttpClientManager.GetTempFileResponse url: {0}", options.Url);
2016-10-29 05:40:15 +00:00
}
var client = GetHttpClient(options.Url, options.EnableHttpCompression);
2016-10-29 05:40:15 +00:00
try
{
options.CancellationToken.ThrowIfCancellationRequested();
using (var response = (await client.SendAsync(httpWebRequest).ConfigureAwait(false)))
2016-10-29 05:40:15 +00:00
{
await EnsureSuccessStatusCode(response, options).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
options.CancellationToken.ThrowIfCancellationRequested();
using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var fs = _fileSystem.GetFileStream(tempFile, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
2016-10-29 05:40:15 +00:00
{
await stream.CopyToAsync(fs, StreamDefaults.DefaultCopyToBufferSize, options.CancellationToken).ConfigureAwait(false);
2016-10-29 05:40:15 +00:00
}
options.Progress.Report(100);
var contentLength = response.Content.Headers.ContentLength;
return GetResponseInfo(response, tempFile, contentLength);
2016-10-29 05:40:15 +00:00
}
}
catch (Exception ex)
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
throw GetException(ex, options);
2016-10-29 05:40:15 +00:00
}
}
private Exception GetException(Exception ex, HttpRequestOptions options)
2016-10-29 05:40:15 +00:00
{
if (ex is HttpException)
{
return ex;
}
var webException = ex as WebException
2017-08-17 20:19:02 +00:00
?? ex.InnerException as WebException;
2016-10-29 05:40:15 +00:00
if (webException != null)
{
if (options.LogErrors)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(webException, "Error {status} getting response from {url}", webException.Status, options.Url);
2016-10-29 05:40:15 +00:00
}
2017-07-22 23:00:32 +00:00
var exception = new HttpException(webException.Message, webException);
2016-10-29 05:40:15 +00:00
using (var response = webException.Response as HttpWebResponse)
2016-10-29 05:40:15 +00:00
{
if (response != null)
2016-10-29 05:40:15 +00:00
{
exception.StatusCode = response.StatusCode;
2016-10-29 05:40:15 +00:00
}
}
2017-07-22 23:00:32 +00:00
if (!exception.StatusCode.HasValue)
{
if (webException.Status == WebExceptionStatus.NameResolutionFailure ||
webException.Status == WebExceptionStatus.ConnectFailure)
{
exception.IsTimedOut = true;
}
}
2016-10-29 05:40:15 +00:00
return exception;
}
var operationCanceledException = ex as OperationCanceledException
2017-08-17 20:19:02 +00:00
?? ex.InnerException as OperationCanceledException;
2016-10-29 05:40:15 +00:00
if (operationCanceledException != null)
{
return GetCancellationException(options, options.CancellationToken, operationCanceledException);
2016-10-29 05:40:15 +00:00
}
if (options.LogErrors)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error getting response from {url}", options.Url);
2016-10-29 05:40:15 +00:00
}
return ex;
}
private void ValidateParams(HttpRequestOptions options)
{
if (string.IsNullOrEmpty(options.Url))
{
throw new ArgumentNullException(nameof(options));
2016-10-29 05:40:15 +00:00
}
}
/// <summary>
/// Gets the host from URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>System.String.</returns>
private static string GetHostFromUrl(string url)
2016-10-29 05:40:15 +00:00
{
var index = url.IndexOf("://", StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
url = url.Substring(index + 3);
var host = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(host))
{
return host;
}
}
return url;
}
/// <summary>
/// Throws the cancellation exception.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="exception">The exception.</param>
/// <returns>Exception.</returns>
private Exception GetCancellationException(HttpRequestOptions options, CancellationToken cancellationToken, OperationCanceledException exception)
2016-10-29 05:40:15 +00:00
{
// If the HttpClient's timeout is reached, it will cancel the Task internally
if (!cancellationToken.IsCancellationRequested)
{
var msg = string.Format("Connection to {0} timed out", options.Url);
if (options.LogErrors)
{
_logger.LogError(msg);
2016-10-29 05:40:15 +00:00
}
// Throw an HttpException so that the caller doesn't think it was cancelled by user code
return new HttpException(msg, exception)
{
IsTimedOut = true
};
}
return exception;
}
private async Task EnsureSuccessStatusCode(HttpResponseMessage response, HttpRequestOptions options)
2016-10-29 05:40:15 +00:00
{
if (response.IsSuccessStatusCode)
{
return;
}
var msg = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
_logger.LogError(msg);
throw new HttpException(response.ReasonPhrase)
{
StatusCode = response.StatusCode
};
2016-10-29 05:40:15 +00:00
}
}
}