WebSocketSharpRequest.cs 17 KB

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