WebSocketSharpRequest.cs 17 KB

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