WebSocketSharpRequest.cs 17 KB

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