WebSocketSharpRequest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 SocketHttpListener.Net;
  15. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  16. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  17. using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
  18. using IResponse = MediaBrowser.Model.Services.IResponse;
  19. namespace Emby.Server.Implementations.SocketSharp
  20. {
  21. public partial class WebSocketSharpRequest : IHttpRequest
  22. {
  23. private readonly HttpRequest request;
  24. private readonly IHttpResponse response;
  25. public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
  26. {
  27. this.OperationName = operationName;
  28. this.request = httpContext;
  29. this.response = new WebSocketSharpResponse(logger, response, this);
  30. // HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
  31. }
  32. public HttpRequest HttpRequest => request;
  33. public object OriginalRequest => request;
  34. public IResponse Response => response;
  35. public IHttpResponse HttpResponse => response;
  36. public string OperationName { get; set; }
  37. public object Dto { get; set; }
  38. public string RawUrl => request.GetEncodedPathAndQuery();
  39. public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
  40. public string UserHostAddress => request.HttpContext.Connection.RemoteIpAddress.ToString();
  41. public string XForwardedFor
  42. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();
  43. public int? XForwardedPort
  44. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
  45. public string XForwardedProtocol => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"].ToString();
  46. public string XRealIp => StringValues.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"].ToString();
  47. private string remoteIp;
  48. public string RemoteIp =>
  49. remoteIp ??
  50. (remoteIp = CheckBadChars(XForwardedFor) ??
  51. NormalizeIp(CheckBadChars(XRealIp) ??
  52. (string.IsNullOrEmpty(request.HttpContext.Connection.RemoteIpAddress.ToString()) ? null : NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString()))));
  53. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  54. // CheckBadChars - throws on invalid chars to be not found in header name/value
  55. internal static string CheckBadChars(string name)
  56. {
  57. if (name == null || name.Length == 0)
  58. {
  59. return name;
  60. }
  61. // VALUE check
  62. // Trim spaces from both ends
  63. name = name.Trim(HttpTrimCharacters);
  64. // First, check for correctly formed multi-line value
  65. // Second, check for absence of CTL characters
  66. int crlf = 0;
  67. for (int i = 0; i < name.Length; ++i)
  68. {
  69. char c = (char)(0x000000ff & (uint)name[i]);
  70. switch (crlf)
  71. {
  72. case 0:
  73. {
  74. if (c == '\r')
  75. {
  76. crlf = 1;
  77. }
  78. else if (c == '\n')
  79. {
  80. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  81. // Is there an exploit?
  82. crlf = 2;
  83. }
  84. else if (c == 127 || (c < ' ' && c != '\t'))
  85. {
  86. throw new ArgumentException("net_WebHeaderInvalidControlChars");
  87. }
  88. break;
  89. }
  90. case 1:
  91. {
  92. if (c == '\n')
  93. {
  94. crlf = 2;
  95. break;
  96. }
  97. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  98. }
  99. case 2:
  100. {
  101. if (c == ' ' || c == '\t')
  102. {
  103. crlf = 0;
  104. break;
  105. }
  106. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  107. }
  108. }
  109. }
  110. if (crlf != 0)
  111. {
  112. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  113. }
  114. return name;
  115. }
  116. internal static bool ContainsNonAsciiChars(string token)
  117. {
  118. for (int i = 0; i < token.Length; ++i)
  119. {
  120. if ((token[i] < 0x20) || (token[i] > 0x7e))
  121. {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. private string NormalizeIp(string ip)
  128. {
  129. if (!string.IsNullOrWhiteSpace(ip))
  130. {
  131. // Handle ipv4 mapped to ipv6
  132. const string srch = "::ffff:";
  133. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  134. if (index == 0)
  135. {
  136. ip = ip.Substring(srch.Length);
  137. }
  138. }
  139. return ip;
  140. }
  141. public bool IsSecureConnection => request.IsHttps || XForwardedProtocol == "https";
  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);
  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 QueryParamCollection Headers => new QueryParamCollection(request.Headers);
  346. private QueryParamCollection queryString;
  347. public QueryParamCollection QueryString => queryString ?? (queryString = new QueryParamCollection(request.Query));
  348. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  349. private string httpMethod;
  350. public string HttpMethod =>
  351. httpMethod
  352. ?? (httpMethod = request.Method);
  353. public string Verb => HttpMethod;
  354. public string ContentType => request.ContentType;
  355. private Encoding contentEncoding;
  356. public Encoding ContentEncoding
  357. {
  358. get => contentEncoding ?? Encoding.GetEncoding(request.Headers[HeaderNames.ContentEncoding].ToString());
  359. set => contentEncoding = value;
  360. }
  361. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  362. public static Encoding GetEncoding(string contentTypeHeader)
  363. {
  364. var param = GetParameter(contentTypeHeader, "charset=");
  365. if (param == null)
  366. {
  367. return null;
  368. }
  369. try
  370. {
  371. return Encoding.GetEncoding(param);
  372. }
  373. catch (ArgumentException)
  374. {
  375. return null;
  376. }
  377. }
  378. public Stream InputStream => request.Body;
  379. public long ContentLength => request.ContentLength ?? 0;
  380. private IHttpFile[] httpFiles;
  381. public IHttpFile[] Files
  382. {
  383. get
  384. {
  385. if (httpFiles == null)
  386. {
  387. if (files == null)
  388. {
  389. return httpFiles = Array.Empty<IHttpFile>();
  390. }
  391. httpFiles = new IHttpFile[files.Count];
  392. var i = 0;
  393. foreach (var pair in files)
  394. {
  395. var reqFile = pair.Value;
  396. httpFiles[i] = new HttpFile
  397. {
  398. ContentType = reqFile.ContentType,
  399. ContentLength = reqFile.ContentLength,
  400. FileName = reqFile.FileName,
  401. InputStream = reqFile.InputStream,
  402. };
  403. i++;
  404. }
  405. }
  406. return httpFiles;
  407. }
  408. }
  409. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  410. {
  411. if (handlerPath != null)
  412. {
  413. var trimmed = pathInfo.TrimStart('/');
  414. if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  415. {
  416. return trimmed.Substring(handlerPath.Length);
  417. }
  418. }
  419. return pathInfo;
  420. }
  421. }
  422. }