diff options
Diffstat (limited to 'Emby.Server.Implementations/HttpServer')
4 files changed, 59 insertions, 122 deletions
diff --git a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs index 163b54e39..033ffd4c0 100644 --- a/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -54,39 +54,33 @@ namespace Emby.Server.Implementations.HttpServer private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>(); private readonly List<IWebSocketConnection> _webSocketConnections = new List<IWebSocketConnection>(); - public HttpListenerHost(IServerApplicationHost applicationHost, + public HttpListenerHost( + IServerApplicationHost applicationHost, ILogger logger, IServerConfigurationManager config, - string defaultRedirectPath, INetworkManager networkManager, ITextEncoding textEncoding, IJsonSerializer jsonSerializer, IXmlSerializer xmlSerializer, Func<Type, Func<string, object>> funcParseFn) + string defaultRedirectPath, + INetworkManager networkManager, + ITextEncoding textEncoding, + IJsonSerializer jsonSerializer, + IXmlSerializer xmlSerializer, + Func<Type, Func<string, object>> funcParseFn) { - Instance = this; - _appHost = applicationHost; + _logger = logger; + _config = config; DefaultRedirectPath = defaultRedirectPath; _networkManager = networkManager; _textEncoding = textEncoding; _jsonSerializer = jsonSerializer; _xmlSerializer = xmlSerializer; - _config = config; - - _logger = logger; _funcParseFn = funcParseFn; - ResponseFilters = new Action<IRequest, IResponse, object>[] { }; + Instance = this; + ResponseFilters = Array.Empty<Action<IRequest, IResponse, object>>(); } public string GlobalResponse { get; set; } - readonly Dictionary<Type, int> _mapExceptionToStatusCode = new Dictionary<Type, int> - { - {typeof (ResourceNotFoundException), 404}, - {typeof (RemoteServiceUnavailableException), 502}, - {typeof (FileNotFoundException), 404}, - //{typeof (DirectoryNotFoundException), 404}, - {typeof (SecurityException), 401}, - {typeof (ArgumentException), 400} - }; - protected ILogger Logger => _logger; public object CreateInstance(Type type) @@ -103,9 +97,9 @@ namespace Emby.Server.Implementations.HttpServer { //Exec all RequestFilter attributes with Priority < 0 var attributes = GetRequestFilterAttributes(requestDto.GetType()); - var i = 0; - var count = attributes.Count; + int count = attributes.Count; + int i = 0; for (; i < count && attributes[i].Priority < 0; i++) { var attribute = attributes[i]; @@ -167,10 +161,7 @@ namespace Emby.Server.Implementations.HttpServer _webSocketConnections.Add(connection); } - if (WebSocketConnected != null) - { - WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); - } + WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection)); } private void Connection_Closed(object sender, EventArgs e) @@ -205,26 +196,16 @@ namespace Emby.Server.Implementations.HttpServer private int GetStatusCode(Exception ex) { - if (ex is ArgumentException) - { - return 400; - } - - var exceptionType = ex.GetType(); - - if (!_mapExceptionToStatusCode.TryGetValue(exceptionType, out var statusCode)) + switch (ex) { - if (ex is DirectoryNotFoundException) - { - statusCode = 404; - } - else - { - statusCode = 500; - } + case ArgumentException _: return 400; + case SecurityException _: return 401; + case DirectoryNotFoundException _: + case FileNotFoundException _: + case ResourceNotFoundException _: return 404; + case RemoteServiceUnavailableException _: return 502; + default: return 500; } - - return statusCode; } private async Task ErrorHandler(Exception ex, IRequest httpReq, bool logExceptionStackTrace, bool logExceptionMessage) @@ -310,29 +291,22 @@ namespace Emby.Server.Implementations.HttpServer } } - private readonly Dictionary<string, int> _skipLogExtensions = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) + private static readonly string[] _skipLogExtensions = { - {".js", 0}, - {".css", 0}, - {".woff", 0}, - {".woff2", 0}, - {".ttf", 0}, - {".html", 0} + ".js", + ".css", + ".woff", + ".woff2", + ".ttf", + ".html" }; private bool EnableLogging(string url, string localPath) { var extension = GetExtension(url); - if (string.IsNullOrEmpty(extension) || !_skipLogExtensions.ContainsKey(extension)) - { - if (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1) - { - return true; - } - } - - return false; + return ((string.IsNullOrEmpty(extension) || !_skipLogExtensions.Contains(extension)) + && (string.IsNullOrEmpty(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)); } private static string GetExtension(string url) @@ -555,9 +529,7 @@ namespace Emby.Server.Implementations.HttpServer return; } - if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || - string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || - localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) + if (localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; @@ -711,7 +683,7 @@ namespace Emby.Server.Implementations.HttpServer }; } - _logger.LogError("Could not find handler for {pathInfo}", pathInfo); + _logger.LogError("Could not find handler for {PathInfo}", pathInfo); return null; } @@ -725,13 +697,13 @@ namespace Emby.Server.Implementations.HttpServer private void RedirectToSecureUrl(IHttpRequest httpReq, IResponse httpRes, string url) { - int currentPort; - if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) + if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { - currentPort = uri.Port; - var builder = new UriBuilder(uri); - builder.Port = _config.Configuration.PublicHttpsPort; - builder.Scheme = "https"; + var builder = new UriBuilder(uri) + { + Port = _config.Configuration.PublicHttpsPort, + Scheme = "https" + }; url = builder.Uri.ToString(); RedirectToUrl(httpRes, url); @@ -831,12 +803,6 @@ namespace Emby.Server.Implementations.HttpServer public Task<object> DeserializeJson(Type type, Stream stream) { - //using (var reader = new StreamReader(stream)) - //{ - // var json = reader.ReadToEnd(); - // logger.LogInformation(json); - // return _jsonSerializer.DeserializeFromString(json, type); - //} return _jsonSerializer.DeserializeFromStreamAsync(stream, type); } diff --git a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs index 851250ecd..08e43732d 100644 --- a/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs +++ b/Emby.Server.Implementations/HttpServer/HttpResultFactory.cs @@ -410,8 +410,10 @@ namespace Emby.Server.Implementations.HttpServer serializer.WriteObject(xw, from); xw.Flush(); ms.Seek(0, SeekOrigin.Begin); - var reader = new StreamReader(ms); - return reader.ReadToEnd(); + using (var reader = new StreamReader(ms)) + { + return reader.ReadToEnd(); + } } } } @@ -423,7 +425,7 @@ namespace Emby.Server.Implementations.HttpServer { responseHeaders["ETag"] = string.Format("\"{0}\"", cacheKeyString); - var noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; + bool noCache = (requestContext.Headers.Get("Cache-Control") ?? string.Empty).IndexOf("no-cache", StringComparison.OrdinalIgnoreCase) != -1; if (!noCache) { @@ -461,8 +463,7 @@ namespace Emby.Server.Implementations.HttpServer }); } - public Task<object> GetStaticFileResult(IRequest requestContext, - StaticFileResultOptions options) + public Task<object> GetStaticFileResult(IRequest requestContext, StaticFileResultOptions options) { var path = options.Path; var fileShare = options.FileShare; @@ -697,32 +698,26 @@ namespace Emby.Server.Implementations.HttpServer var ifModifiedSinceHeader = requestContext.Headers.Get("If-Modified-Since"); - if (!string.IsNullOrEmpty(ifModifiedSinceHeader)) + if (!string.IsNullOrEmpty(ifModifiedSinceHeader) + && DateTime.TryParse(ifModifiedSinceHeader, out DateTime ifModifiedSince) + && IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) { - if (DateTime.TryParse(ifModifiedSinceHeader, out var ifModifiedSince)) - { - if (IsNotModified(ifModifiedSince.ToUniversalTime(), cacheDuration, lastDateModified)) - { - return true; - } - } + return true; } var ifNoneMatchHeader = requestContext.Headers.Get("If-None-Match"); - var hasCacheKey = !cacheKey.Equals(Guid.Empty); + bool hasCacheKey = !cacheKey.Equals(Guid.Empty); // Validate If-None-Match - if ((hasCacheKey || !string.IsNullOrEmpty(ifNoneMatchHeader))) + if ((hasCacheKey && !string.IsNullOrEmpty(ifNoneMatchHeader))) { ifNoneMatchHeader = (ifNoneMatchHeader ?? string.Empty).Trim('\"'); - if (Guid.TryParse(ifNoneMatchHeader, out var ifNoneMatch)) + if (Guid.TryParse(ifNoneMatchHeader, out Guid ifNoneMatch) + && cacheKey.Equals(ifNoneMatch)) { - if (hasCacheKey && cacheKey.Equals(ifNoneMatch)) - { - return true; - } + return true; } } diff --git a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs index bb52cd705..891a76ec2 100644 --- a/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs +++ b/Emby.Server.Implementations/HttpServer/RangeRequestWriter.cs @@ -40,8 +40,6 @@ namespace Emby.Server.Implementations.HttpServer /// </summary> private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - public List<Cookie> Cookies { get; private set; } - /// <summary> /// Additional HTTP Headers /// </summary> @@ -72,7 +70,6 @@ namespace Emby.Server.Implementations.HttpServer Headers["Accept-Ranges"] = "bytes"; StatusCode = HttpStatusCode.PartialContent; - Cookies = new List<Cookie>(); SetRangeValues(contentLength); } @@ -220,7 +217,5 @@ namespace Emby.Server.Implementations.HttpServer get => (HttpStatusCode)Status; set => Status = (int)value; } - - public string StatusDescription { get; set; } } } diff --git a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs index 80386f35e..da2bf983a 100644 --- a/Emby.Server.Implementations/HttpServer/ResponseFilter.cs +++ b/Emby.Server.Implementations/HttpServer/ResponseFilter.cs @@ -25,14 +25,11 @@ namespace Emby.Server.Implementations.HttpServer public void FilterResponse(IRequest req, IResponse res, object dto) { // Try to prevent compatibility view - //res.AddHeader("X-UA-Compatible", "IE=Edge"); res.AddHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Disposition, Content-Encoding, Content-Language, Content-Length, Content-MD5, Content-Range, Content-Type, Date, Host, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Origin, OriginToken, Pragma, Range, Slug, Transfer-Encoding, Want-Digest, X-MediaBrowser-Token, X-Emby-Authorization"); res.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); res.AddHeader("Access-Control-Allow-Origin", "*"); - var exception = dto as Exception; - - if (exception != null) + if (dto is Exception exception) { _logger.LogError(exception, "Error processing request for {RawUrl}", req.RawUrl); @@ -45,42 +42,26 @@ namespace Emby.Server.Implementations.HttpServer } } - var hasHeaders = dto as IHasHeaders; - - if (hasHeaders != null) + if (dto is IHasHeaders hasHeaders) { if (!hasHeaders.Headers.ContainsKey("Server")) { hasHeaders.Headers["Server"] = "Microsoft-NetCore/2.0, UPnP/1.0 DLNADOC/1.50"; - //hasHeaders.Headers["Server"] = "Mono-HTTPAPI/1.1"; } // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy - - if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength) && !string.IsNullOrEmpty(contentLength)) + if (hasHeaders.Headers.TryGetValue("Content-Length", out string contentLength) + && !string.IsNullOrEmpty(contentLength)) { var length = long.Parse(contentLength, UsCulture); if (length > 0) { res.SetContentLength(length); - - //var listenerResponse = res.OriginalResponse as HttpListenerResponse; - - //if (listenerResponse != null) - //{ - // // Disable chunked encoding. Technically this is only needed when using Content-Range, but - // // anytime we know the content length there's no need for it - // listenerResponse.SendChunked = false; - // return; - //} - res.SendChunked = false; } } } - - //res.KeepAlive = false; } /// <summary> |
