WebSocketSharpRequest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using Emby.Server.Implementations.HttpServer;
  8. using MediaBrowser.Model.Services;
  9. using Microsoft.AspNetCore.Http;
  10. using Microsoft.AspNetCore.Http.Extensions;
  11. using Microsoft.Extensions.Logging;
  12. using Microsoft.Extensions.Primitives;
  13. using Microsoft.Net.Http.Headers;
  14. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  15. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  16. using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
  17. using IResponse = MediaBrowser.Model.Services.IResponse;
  18. namespace Emby.Server.Implementations.SocketSharp
  19. {
  20. public partial class WebSocketSharpRequest : IHttpRequest
  21. {
  22. private readonly HttpRequest request;
  23. private readonly IHttpResponse response;
  24. public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
  25. {
  26. this.OperationName = operationName;
  27. this.request = httpContext;
  28. this.response = new WebSocketSharpResponse(logger, response, this);
  29. // HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
  30. }
  31. public HttpRequest HttpRequest => request;
  32. public object OriginalRequest => request;
  33. public IResponse Response => response;
  34. public IHttpResponse HttpResponse => response;
  35. public string OperationName { get; set; }
  36. public object Dto { get; set; }
  37. public string RawUrl => request.GetEncodedPathAndQuery();
  38. public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
  39. public string XForwardedFor
  40. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();
  41. public int? XForwardedPort
  42. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
  43. public string XForwardedProtocol => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"].ToString();
  44. public string XRealIp => StringValues.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"].ToString();
  45. private string remoteIp;
  46. public string RemoteIp =>
  47. remoteIp ??
  48. (remoteIp = CheckBadChars(XForwardedFor) ??
  49. NormalizeIp(CheckBadChars(XRealIp) ??
  50. (string.IsNullOrEmpty(request.HttpContext.Connection.RemoteIpAddress.ToString()) ? null : NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString()))));
  51. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  52. // CheckBadChars - throws on invalid chars to be not found in header name/value
  53. internal static string CheckBadChars(string name)
  54. {
  55. if (name == null || name.Length == 0)
  56. {
  57. return name;
  58. }
  59. // VALUE check
  60. // Trim spaces from both ends
  61. name = name.Trim(HttpTrimCharacters);
  62. // First, check for correctly formed multi-line value
  63. // Second, check for absence of CTL characters
  64. int crlf = 0;
  65. for (int i = 0; i < name.Length; ++i)
  66. {
  67. char c = (char)(0x000000ff & (uint)name[i]);
  68. switch (crlf)
  69. {
  70. case 0:
  71. {
  72. if (c == '\r')
  73. {
  74. crlf = 1;
  75. }
  76. else if (c == '\n')
  77. {
  78. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  79. // Is there an exploit?
  80. crlf = 2;
  81. }
  82. else if (c == 127 || (c < ' ' && c != '\t'))
  83. {
  84. throw new ArgumentException("net_WebHeaderInvalidControlChars");
  85. }
  86. break;
  87. }
  88. case 1:
  89. {
  90. if (c == '\n')
  91. {
  92. crlf = 2;
  93. break;
  94. }
  95. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  96. }
  97. case 2:
  98. {
  99. if (c == ' ' || c == '\t')
  100. {
  101. crlf = 0;
  102. break;
  103. }
  104. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  105. }
  106. }
  107. }
  108. if (crlf != 0)
  109. {
  110. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  111. }
  112. return name;
  113. }
  114. private string NormalizeIp(string ip)
  115. {
  116. if (!string.IsNullOrWhiteSpace(ip))
  117. {
  118. // Handle ipv4 mapped to ipv6
  119. const string srch = "::ffff:";
  120. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  121. if (index == 0)
  122. {
  123. ip = ip.Substring(srch.Length);
  124. }
  125. }
  126. return ip;
  127. }
  128. public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  129. private Dictionary<string, object> items;
  130. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  131. private string responseContentType;
  132. public string ResponseContentType
  133. {
  134. get =>
  135. responseContentType
  136. ?? (responseContentType = GetResponseContentType(HttpRequest));
  137. set => this.responseContentType = value;
  138. }
  139. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  140. public const string MultiPartFormData = "multipart/form-data";
  141. public static string GetResponseContentType(HttpRequest httpReq)
  142. {
  143. var specifiedContentType = GetQueryStringContentType(httpReq);
  144. if (!string.IsNullOrEmpty(specifiedContentType))
  145. {
  146. return specifiedContentType;
  147. }
  148. const string serverDefaultContentType = "application/json";
  149. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  150. string defaultContentType = null;
  151. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  152. {
  153. defaultContentType = serverDefaultContentType;
  154. }
  155. var acceptsAnything = false;
  156. var hasDefaultContentType = defaultContentType != null;
  157. if (acceptContentTypes != null)
  158. {
  159. foreach (var acceptsType in acceptContentTypes)
  160. {
  161. // TODO: @bond move to Span when Span.Split lands
  162. // https://github.com/dotnet/corefx/issues/26528
  163. var contentType = acceptsType?.Split(';')[0].Trim();
  164. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  165. if (acceptsAnything)
  166. {
  167. break;
  168. }
  169. }
  170. if (acceptsAnything)
  171. {
  172. if (hasDefaultContentType)
  173. {
  174. return defaultContentType;
  175. }
  176. else
  177. {
  178. return serverDefaultContentType;
  179. }
  180. }
  181. }
  182. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  183. {
  184. return Soap11;
  185. }
  186. // We could also send a '406 Not Acceptable', but this is allowed also
  187. return serverDefaultContentType;
  188. }
  189. public const string Soap11 = "text/xml; charset=utf-8";
  190. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  191. {
  192. if (contentTypes == null || request.ContentType == null)
  193. {
  194. return false;
  195. }
  196. foreach (var contentType in contentTypes)
  197. {
  198. if (IsContentType(request, contentType))
  199. {
  200. return true;
  201. }
  202. }
  203. return false;
  204. }
  205. public static bool IsContentType(HttpRequest request, string contentType)
  206. {
  207. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  208. }
  209. private static string GetQueryStringContentType(HttpRequest httpReq)
  210. {
  211. ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
  212. if (format == null)
  213. {
  214. const int formatMaxLength = 4;
  215. ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
  216. if (pi == null || pi.Length <= formatMaxLength)
  217. {
  218. return null;
  219. }
  220. if (pi[0] == '/')
  221. {
  222. pi = pi.Slice(1);
  223. }
  224. format = LeftPart(pi, '/');
  225. if (format.Length > formatMaxLength)
  226. {
  227. return null;
  228. }
  229. }
  230. format = LeftPart(format, '.');
  231. if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
  232. {
  233. return "application/json";
  234. }
  235. else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
  236. {
  237. return "application/xml";
  238. }
  239. return null;
  240. }
  241. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  242. {
  243. if (strVal == null)
  244. {
  245. return null;
  246. }
  247. var pos = strVal.IndexOf(needle);
  248. return pos == -1 ? strVal : strVal.Slice(0, pos);
  249. }
  250. public static string HandlerFactoryPath;
  251. private string pathInfo;
  252. public string PathInfo
  253. {
  254. get
  255. {
  256. if (this.pathInfo == null)
  257. {
  258. var mode = HandlerFactoryPath;
  259. var pos = RawUrl.IndexOf("?", StringComparison.Ordinal);
  260. if (pos != -1)
  261. {
  262. var path = RawUrl.Substring(0, pos);
  263. this.pathInfo = GetPathInfo(
  264. path,
  265. mode,
  266. mode ?? string.Empty);
  267. }
  268. else
  269. {
  270. this.pathInfo = RawUrl;
  271. }
  272. this.pathInfo = WebUtility.UrlDecode(pathInfo);
  273. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  274. }
  275. return this.pathInfo;
  276. }
  277. }
  278. private static string GetPathInfo(string fullPath, string mode, string appPath)
  279. {
  280. var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
  281. if (!string.IsNullOrEmpty(pathInfo))
  282. {
  283. return pathInfo;
  284. }
  285. // Wildcard mode relies on this to work out the handlerPath
  286. pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
  287. if (!string.IsNullOrEmpty(pathInfo))
  288. {
  289. return pathInfo;
  290. }
  291. return fullPath;
  292. }
  293. private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
  294. {
  295. if (mappedPathRoot == null)
  296. {
  297. return null;
  298. }
  299. var sbPathInfo = new StringBuilder();
  300. var fullPathParts = fullPath.Split('/');
  301. var mappedPathRootParts = mappedPathRoot.Split('/');
  302. var fullPathIndexOffset = mappedPathRootParts.Length - 1;
  303. var pathRootFound = false;
  304. for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
  305. {
  306. if (pathRootFound)
  307. {
  308. sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
  309. }
  310. else if (fullPathIndex - fullPathIndexOffset >= 0)
  311. {
  312. pathRootFound = true;
  313. for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
  314. {
  315. if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
  316. {
  317. pathRootFound = false;
  318. break;
  319. }
  320. }
  321. }
  322. }
  323. if (!pathRootFound)
  324. {
  325. return null;
  326. }
  327. var path = sbPathInfo.ToString();
  328. return path.Length > 1 ? path.TrimEnd('/') : "/";
  329. }
  330. public string UserAgent => request.Headers[HeaderNames.UserAgent];
  331. public QueryParamCollection Headers => new QueryParamCollection(request.Headers);
  332. private QueryParamCollection queryString;
  333. public QueryParamCollection QueryString => queryString ?? (queryString = new QueryParamCollection(request.Query));
  334. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  335. private string httpMethod;
  336. public string HttpMethod =>
  337. httpMethod
  338. ?? (httpMethod = request.Method);
  339. public string Verb => HttpMethod;
  340. public string ContentType => request.ContentType;
  341. private Encoding contentEncoding;
  342. public Encoding ContentEncoding
  343. {
  344. get => contentEncoding ?? Encoding.GetEncoding(request.Headers[HeaderNames.ContentEncoding].ToString());
  345. set => contentEncoding = value;
  346. }
  347. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  348. public static Encoding GetEncoding(string contentTypeHeader)
  349. {
  350. var param = GetParameter(contentTypeHeader, "charset=");
  351. if (param == null)
  352. {
  353. return null;
  354. }
  355. try
  356. {
  357. return Encoding.GetEncoding(param);
  358. }
  359. catch (ArgumentException)
  360. {
  361. return null;
  362. }
  363. }
  364. public Stream InputStream => request.Body;
  365. public long ContentLength => request.ContentLength ?? 0;
  366. private IHttpFile[] httpFiles;
  367. public IHttpFile[] Files
  368. {
  369. get
  370. {
  371. if (httpFiles == null)
  372. {
  373. if (files == null)
  374. {
  375. return httpFiles = Array.Empty<IHttpFile>();
  376. }
  377. httpFiles = new IHttpFile[files.Count];
  378. var i = 0;
  379. foreach (var pair in files)
  380. {
  381. var reqFile = pair.Value;
  382. httpFiles[i] = new HttpFile
  383. {
  384. ContentType = reqFile.ContentType,
  385. ContentLength = reqFile.ContentLength,
  386. FileName = reqFile.FileName,
  387. InputStream = reqFile.InputStream,
  388. };
  389. i++;
  390. }
  391. }
  392. return httpFiles;
  393. }
  394. }
  395. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  396. {
  397. if (handlerPath != null)
  398. {
  399. var trimmed = pathInfo.TrimStart('/');
  400. if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  401. {
  402. return trimmed.Substring(handlerPath.Length);
  403. }
  404. }
  405. return pathInfo;
  406. }
  407. }
  408. }