2
0

WebSocketSharpRequest.cs 17 KB

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