jellyfin/Jellyfin.Server/SocketSharp/WebSocketSharpRequest.cs

535 lines
17 KiB
C#
Raw Normal View History

using System;
2014-07-19 03:28:40 +02:00
using System.Collections.Generic;
2019-02-13 17:28:04 +01:00
using System.Globalization;
2014-07-19 03:28:40 +02:00
using System.IO;
using System.Text;
2016-11-11 02:37:20 +01:00
using Emby.Server.Implementations.HttpServer;
2016-10-25 21:02:04 +02:00
using MediaBrowser.Model.Services;
2019-01-01 16:27:11 +01:00
using Microsoft.Extensions.Logging;
2015-01-03 20:38:22 +01:00
using SocketHttpListener.Net;
2016-10-25 21:02:04 +02:00
using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
using IResponse = MediaBrowser.Model.Services.IResponse;
2014-07-19 03:28:40 +02:00
namespace Jellyfin.Server.SocketSharp
2014-07-19 03:28:40 +02:00
{
public partial class WebSocketSharpRequest : IHttpRequest
{
private readonly HttpListenerRequest request;
private readonly IHttpResponse response;
2018-09-12 19:26:21 +02:00
public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, ILogger logger)
2014-07-19 03:28:40 +02:00
{
this.OperationName = operationName;
this.request = httpContext.Request;
2016-06-19 18:53:43 +02:00
this.response = new WebSocketSharpResponse(logger, httpContext.Response, this);
2017-09-03 05:17:48 +02:00
// HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
2017-09-03 05:17:48 +02:00
}
public HttpListenerRequest HttpRequest => request;
2014-07-19 03:28:40 +02:00
public object OriginalRequest => request;
2014-07-19 03:28:40 +02:00
public IResponse Response => response;
2014-07-19 03:28:40 +02:00
public IHttpResponse HttpResponse => response;
2014-07-19 03:28:40 +02:00
public string OperationName { get; set; }
public object Dto { get; set; }
public string RawUrl => request.RawUrl;
2014-07-19 03:28:40 +02:00
public string AbsoluteUri => request.Url.AbsoluteUri.TrimEnd('/');
2014-07-19 03:28:40 +02:00
public string UserHostAddress => request.UserHostAddress;
2014-07-19 03:28:40 +02:00
2019-02-13 17:28:04 +01:00
public string XForwardedFor
=> string.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"];
2014-07-19 03:28:40 +02:00
2019-02-13 17:28:04 +01:00
public int? XForwardedPort
=> string.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
2014-07-19 03:28:40 +02:00
public string XForwardedProtocol => string.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"];
2014-07-19 03:28:40 +02:00
public string XRealIp => string.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"];
2014-07-19 03:28:40 +02:00
private string remoteIp;
public string RemoteIp =>
remoteIp ??
2019-02-08 00:07:57 +01:00
(remoteIp = CheckBadChars(XForwardedFor) ??
NormalizeIp(CheckBadChars(XRealIp) ??
(request.RemoteEndPoint != null ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
2014-07-19 03:28:40 +02:00
2016-07-08 20:11:23 +02:00
private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
// CheckBadChars - throws on invalid chars to be not found in header name/value
internal static string CheckBadChars(string name)
{
if (name == null || name.Length == 0)
{
return name;
}
// VALUE check
2019-02-07 23:36:44 +01:00
// Trim spaces from both ends
2016-07-08 20:11:23 +02:00
name = name.Trim(HttpTrimCharacters);
2019-02-07 23:36:44 +01:00
// First, check for correctly formed multi-line value
2019-02-09 11:53:07 +01:00
// Second, check for absence of CTL characters
2016-07-08 20:11:23 +02:00
int crlf = 0;
for (int i = 0; i < name.Length; ++i)
{
char c = (char)(0x000000ff & (uint)name[i]);
switch (crlf)
{
case 0:
2019-02-13 18:37:44 +01:00
{
2016-07-08 20:11:23 +02:00
if (c == '\r')
{
crlf = 1;
}
else if (c == '\n')
{
// Technically this is bad HTTP. But it would be a breaking change to throw here.
// Is there an exploit?
crlf = 2;
}
else if (c == 127 || (c < ' ' && c != '\t'))
{
throw new ArgumentException("net_WebHeaderInvalidControlChars");
}
2019-02-13 18:37:44 +01:00
2016-07-08 20:11:23 +02:00
break;
2019-02-13 18:37:44 +01:00
}
2016-07-08 20:11:23 +02:00
case 1:
2019-02-13 18:37:44 +01:00
{
2016-07-08 20:11:23 +02:00
if (c == '\n')
{
crlf = 2;
break;
}
2019-02-13 18:37:44 +01:00
2016-07-08 20:11:23 +02:00
throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
2019-02-13 18:37:44 +01:00
}
2016-07-08 20:11:23 +02:00
case 2:
2019-02-13 18:37:44 +01:00
{
2016-07-08 20:11:23 +02:00
if (c == ' ' || c == '\t')
{
crlf = 0;
break;
}
2019-02-13 18:37:44 +01:00
2016-07-08 20:11:23 +02:00
throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
2019-02-13 18:37:44 +01:00
}
2016-07-08 20:11:23 +02:00
}
}
2016-07-08 20:11:23 +02:00
if (crlf != 0)
{
throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
}
2016-07-08 20:11:23 +02:00
return name;
}
internal static bool ContainsNonAsciiChars(string token)
{
for (int i = 0; i < token.Length; ++i)
{
if ((token[i] < 0x20) || (token[i] > 0x7e))
{
return true;
}
}
2016-07-08 20:11:23 +02:00
return false;
}
2016-01-20 04:02:26 +01:00
private string NormalizeIp(string ip)
{
if (!string.IsNullOrWhiteSpace(ip))
{
// Handle ipv4 mapped to ipv6
const string srch = "::ffff:";
var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
if (index == 0)
{
ip = ip.Substring(srch.Length);
}
}
return ip;
}
public bool IsSecureConnection => request.IsSecureConnection || XForwardedProtocol == "https";
2014-07-19 03:28:40 +02:00
public string[] AcceptTypes => request.AcceptTypes;
2014-07-19 03:28:40 +02:00
private Dictionary<string, object> items;
public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
2014-07-19 03:28:40 +02:00
private string responseContentType;
public string ResponseContentType
{
get =>
responseContentType
?? (responseContentType = GetResponseContentType(this));
set => this.responseContentType = value;
2014-07-19 03:28:40 +02:00
}
2016-11-10 15:41:24 +01:00
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
public const string MultiPartFormData = "multipart/form-data";
2017-09-03 09:28:58 +02:00
public static string GetResponseContentType(IRequest httpReq)
2016-11-06 21:41:55 +01:00
{
var specifiedContentType = GetQueryStringContentType(httpReq);
2019-02-07 23:36:44 +01:00
if (!string.IsNullOrEmpty(specifiedContentType))
{
return specifiedContentType;
}
2016-11-06 21:41:55 +01:00
2019-02-08 00:07:57 +01:00
const string serverDefaultContentType = "application/json";
2016-11-11 02:37:20 +01:00
2016-11-06 21:41:55 +01:00
var acceptContentTypes = httpReq.AcceptTypes;
2018-09-12 19:26:21 +02:00
string defaultContentType = null;
2016-11-10 15:41:24 +01:00
if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
2016-11-06 21:41:55 +01:00
{
2016-11-11 02:37:20 +01:00
defaultContentType = serverDefaultContentType;
2016-11-06 21:41:55 +01:00
}
var acceptsAnything = false;
2019-02-08 00:07:57 +01:00
var hasDefaultContentType = defaultContentType != null;
2016-11-06 21:41:55 +01:00
if (acceptContentTypes != null)
{
foreach (var acceptsType in acceptContentTypes)
{
2019-02-09 12:01:11 +01:00
// TODO: @bond move to Span when Span.Split lands
// https://github.com/dotnet/corefx/issues/26528
2019-02-12 21:06:34 +01:00
var contentType = acceptsType?.Split(';')[0].Trim();
acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
2019-02-09 11:53:07 +01:00
if (acceptsAnything)
{
break;
}
2016-11-06 21:41:55 +01:00
}
if (acceptsAnything)
{
if (hasDefaultContentType)
2019-01-27 12:03:43 +01:00
{
2016-11-06 21:41:55 +01:00
return defaultContentType;
2019-01-27 12:03:43 +01:00
}
2019-02-09 11:53:07 +01:00
else
2019-01-27 12:03:43 +01:00
{
2016-11-11 02:37:20 +01:00
return serverDefaultContentType;
2019-01-27 12:03:43 +01:00
}
2016-11-06 21:41:55 +01:00
}
}
2016-11-10 15:41:24 +01:00
if (acceptContentTypes == null && httpReq.ContentType == Soap11)
2016-11-06 21:41:55 +01:00
{
2016-11-10 15:41:24 +01:00
return Soap11;
2016-11-06 21:41:55 +01:00
}
2019-02-07 23:36:44 +01:00
// We could also send a '406 Not Acceptable', but this is allowed also
2016-11-11 02:37:20 +01:00
return serverDefaultContentType;
2016-11-06 21:41:55 +01:00
}
2016-11-11 02:37:20 +01:00
2016-11-10 15:41:24 +01:00
public const string Soap11 = "text/xml; charset=utf-8";
2016-11-06 21:41:55 +01:00
2016-11-10 15:41:24 +01:00
public static bool HasAnyOfContentTypes(IRequest request, params string[] contentTypes)
{
2019-01-27 12:03:43 +01:00
if (contentTypes == null || request.ContentType == null)
{
return false;
}
2016-11-10 15:41:24 +01:00
foreach (var contentType in contentTypes)
{
2019-02-07 23:36:44 +01:00
if (IsContentType(request, contentType))
{
return true;
}
2016-11-10 15:41:24 +01:00
}
2019-01-27 12:03:43 +01:00
2016-11-10 15:41:24 +01:00
return false;
}
public static bool IsContentType(IRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
}
2016-11-06 21:41:55 +01:00
private static string GetQueryStringContentType(IRequest httpReq)
{
2019-02-09 11:53:07 +01:00
ReadOnlySpan<char> format = httpReq.QueryString["format"];
2016-11-06 21:41:55 +01:00
if (format == null)
{
const int formatMaxLength = 4;
2019-02-09 11:53:07 +01:00
ReadOnlySpan<char> pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength)
{
return null;
}
2019-02-07 23:36:44 +01:00
if (pi[0] == '/')
{
2019-02-09 11:53:07 +01:00
pi = pi.Slice(1);
}
2019-02-07 23:36:44 +01:00
2016-11-11 02:58:20 +01:00
format = LeftPart(pi, '/');
if (format.Length > formatMaxLength)
{
return null;
}
2016-11-06 21:41:55 +01:00
}
2019-02-07 23:36:44 +01:00
format = LeftPart(format, '.');
if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
{
return "application/json";
}
2019-01-27 12:03:43 +01:00
else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
{
return "application/xml";
}
2016-11-06 21:41:55 +01:00
2016-11-11 02:37:20 +01:00
return null;
2016-11-06 21:41:55 +01:00
}
2016-11-11 02:58:20 +01:00
public static string LeftPart(string strVal, char needle)
{
if (strVal == null)
{
return null;
}
2019-01-27 12:03:43 +01:00
2019-02-08 00:07:57 +01:00
var pos = strVal.IndexOf(needle, StringComparison.Ordinal);
2019-01-27 12:03:43 +01:00
return pos == -1 ? strVal : strVal.Substring(0, pos);
2016-11-11 02:58:20 +01:00
}
2019-02-09 11:53:07 +01:00
public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
{
if (strVal == null)
{
return null;
}
var pos = strVal.IndexOf(needle);
return pos == -1 ? strVal : strVal.Slice(0, pos);
}
2016-11-11 02:58:20 +01:00
public static string HandlerFactoryPath;
2014-07-19 03:28:40 +02:00
private string pathInfo;
public string PathInfo
{
get
{
if (this.pathInfo == null)
{
2016-11-11 02:58:20 +01:00
var mode = HandlerFactoryPath;
2014-07-19 03:28:40 +02:00
2019-02-09 12:01:11 +01:00
var pos = request.RawUrl.IndexOf('?', StringComparison.Ordinal);
2014-07-19 03:28:40 +02:00
if (pos != -1)
{
var path = request.RawUrl.Substring(0, pos);
2016-11-06 21:41:55 +01:00
this.pathInfo = GetPathInfo(
2014-07-19 03:28:40 +02:00
path,
mode,
mode ?? string.Empty);
2014-07-19 03:28:40 +02:00
}
else
{
this.pathInfo = request.RawUrl;
}
2017-05-24 21:12:55 +02:00
this.pathInfo = System.Net.WebUtility.UrlDecode(pathInfo);
2014-07-19 03:28:40 +02:00
this.pathInfo = NormalizePathInfo(pathInfo, mode);
}
2019-02-13 18:37:44 +01:00
2014-07-19 03:28:40 +02:00
return this.pathInfo;
}
}
2016-11-06 21:41:55 +01:00
private static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!string.IsNullOrEmpty(pathInfo))
{
return pathInfo;
}
2016-11-06 21:41:55 +01:00
2019-02-07 23:36:44 +01:00
// Wildcard mode relies on this to work out the handlerPath
2016-11-06 21:41:55 +01:00
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!string.IsNullOrEmpty(pathInfo))
{
return pathInfo;
}
2016-11-06 21:41:55 +01:00
return fullPath;
}
private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
if (mappedPathRoot == null)
{
return null;
}
2016-11-06 21:41:55 +01:00
var sbPathInfo = new StringBuilder();
var fullPathParts = fullPath.Split('/');
var mappedPathRootParts = mappedPathRoot.Split('/');
var fullPathIndexOffset = mappedPathRootParts.Length - 1;
var pathRootFound = false;
for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
{
if (pathRootFound)
{
sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
}
else if (fullPathIndex - fullPathIndexOffset >= 0)
{
pathRootFound = true;
for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
{
if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
{
pathRootFound = false;
break;
}
}
}
}
2019-02-08 00:07:57 +01:00
if (!pathRootFound)
{
return null;
}
2016-11-06 21:41:55 +01:00
var path = sbPathInfo.ToString();
return path.Length > 1 ? path.TrimEnd('/') : "/";
}
2014-07-19 03:28:40 +02:00
private Dictionary<string, System.Net.Cookie> cookies;
public IDictionary<string, System.Net.Cookie> Cookies
{
get
{
if (cookies == null)
{
cookies = new Dictionary<string, System.Net.Cookie>();
2016-11-11 02:58:20 +01:00
foreach (var cookie in this.request.Cookies)
2014-07-19 03:28:40 +02:00
{
var httpCookie = (System.Net.Cookie)cookie;
2014-07-19 03:28:40 +02:00
cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
}
}
return cookies;
}
}
public string UserAgent => request.UserAgent;
2014-07-19 03:28:40 +02:00
public QueryParamCollection Headers => request.Headers;
2016-10-25 21:02:04 +02:00
private QueryParamCollection queryString;
public QueryParamCollection QueryString => queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query));
2014-07-19 03:28:40 +02:00
public bool IsLocal => request.IsLocal;
2014-07-19 03:28:40 +02:00
private string httpMethod;
public string HttpMethod =>
httpMethod
?? (httpMethod = request.HttpMethod);
2014-07-19 03:28:40 +02:00
public string Verb => HttpMethod;
2014-07-19 03:28:40 +02:00
public string ContentType => request.ContentType;
2014-07-19 03:28:40 +02:00
2019-02-13 17:03:50 +01:00
private Encoding contentEncoding;
2014-07-19 03:28:40 +02:00
public Encoding ContentEncoding
{
get => contentEncoding ?? request.ContentEncoding;
set => contentEncoding = value;
2014-07-19 03:28:40 +02:00
}
public Uri UrlReferrer => request.UrlReferrer;
2014-07-19 03:28:40 +02:00
public static Encoding GetEncoding(string contentTypeHeader)
{
var param = GetParameter(contentTypeHeader, "charset=");
if (param == null)
{
return null;
}
2019-01-27 12:03:43 +01:00
2014-07-19 03:28:40 +02:00
try
{
return Encoding.GetEncoding(param);
}
catch (ArgumentException)
{
return null;
}
}
public Stream InputStream => request.InputStream;
2014-07-19 03:28:40 +02:00
public long ContentLength => request.ContentLength64;
2014-07-19 03:28:40 +02:00
private IHttpFile[] httpFiles;
public IHttpFile[] Files
{
get
{
if (httpFiles == null)
{
if (files == null)
{
return httpFiles = Array.Empty<IHttpFile>();
}
2014-07-19 03:28:40 +02:00
httpFiles = new IHttpFile[files.Count];
2016-11-11 02:58:20 +01:00
var i = 0;
foreach (var pair in files)
2014-07-19 03:28:40 +02:00
{
2016-11-11 02:58:20 +01:00
var reqFile = pair.Value;
2014-07-19 03:28:40 +02:00
httpFiles[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
2016-11-11 02:58:20 +01:00
i++;
2014-07-19 03:28:40 +02:00
}
}
2019-02-13 18:37:44 +01:00
2014-07-19 03:28:40 +02:00
return httpFiles;
}
}
public static string NormalizePathInfo(string pathInfo, string handlerPath)
{
2019-02-09 12:01:11 +01:00
if (handlerPath != null)
2014-07-19 03:28:40 +02:00
{
2019-02-09 12:01:11 +01:00
var trimmed = pathInfo.TrimStart('/');
if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
{
return trimmed.Substring(handlerPath.Length);
}
2014-07-19 03:28:40 +02:00
}
return pathInfo;
}
}
}