WebSocketSharpRequest.cs 16 KB

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