WebSocketSharpRequest.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. string format = httpReq.Query["format"];
  226. if (format == null)
  227. {
  228. const int formatMaxLength = 4;
  229. string pi = httpReq.Path.ToString();
  230. if (pi == null || pi.Length <= formatMaxLength)
  231. {
  232. return null;
  233. }
  234. if (pi[0] == '/')
  235. {
  236. pi = pi.Substring(1);
  237. }
  238. format = LeftPart(pi, '/');
  239. if (format.Length > formatMaxLength)
  240. {
  241. return null;
  242. }
  243. }
  244. format = LeftPart(format, '.');
  245. if (format.ToLower().Contains("json"))
  246. {
  247. return "application/json";
  248. }
  249. else if (format.ToLower().Contains("xml"))
  250. {
  251. return "application/xml";
  252. }
  253. return null;
  254. }
  255. public static string LeftPart(string strVal, char needle)
  256. {
  257. if (strVal == null)
  258. {
  259. return null;
  260. }
  261. var pos = strVal.IndexOf(needle.ToString(), StringComparison.Ordinal);
  262. return pos == -1 ? strVal : strVal.Substring(0, pos);
  263. }
  264. public static ReadOnlySpan<string> LeftPart(ReadOnlySpan<string> strVal, char needle)
  265. {
  266. if (strVal == null)
  267. {
  268. return null;
  269. }
  270. var pos = strVal.IndexOf(needle.ToString());
  271. return pos == -1 ? strVal : strVal.Slice(0, pos);
  272. }
  273. public static string HandlerFactoryPath;
  274. private string pathInfo;
  275. public string PathInfo
  276. {
  277. get
  278. {
  279. if (this.pathInfo == null)
  280. {
  281. var mode = HandlerFactoryPath;
  282. var pos = request.Path.ToString().IndexOf("?", StringComparison.Ordinal);
  283. if (pos != -1)
  284. {
  285. var path = request.Path.ToString().Substring(0, pos);
  286. this.pathInfo = GetPathInfo(
  287. path,
  288. mode,
  289. mode ?? string.Empty);
  290. }
  291. else
  292. {
  293. this.pathInfo = request.Path.ToString();
  294. }
  295. this.pathInfo = System.Net.WebUtility.UrlDecode(pathInfo);
  296. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  297. }
  298. return this.pathInfo;
  299. }
  300. }
  301. private static string GetPathInfo(string fullPath, string mode, string appPath)
  302. {
  303. var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
  304. if (!string.IsNullOrEmpty(pathInfo))
  305. {
  306. return pathInfo;
  307. }
  308. // Wildcard mode relies on this to work out the handlerPath
  309. pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
  310. if (!string.IsNullOrEmpty(pathInfo))
  311. {
  312. return pathInfo;
  313. }
  314. return fullPath;
  315. }
  316. private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
  317. {
  318. if (mappedPathRoot == null)
  319. {
  320. return null;
  321. }
  322. var sbPathInfo = new StringBuilder();
  323. var fullPathParts = fullPath.Split('/');
  324. var mappedPathRootParts = mappedPathRoot.Split('/');
  325. var fullPathIndexOffset = mappedPathRootParts.Length - 1;
  326. var pathRootFound = false;
  327. for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
  328. {
  329. if (pathRootFound)
  330. {
  331. sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
  332. }
  333. else if (fullPathIndex - fullPathIndexOffset >= 0)
  334. {
  335. pathRootFound = true;
  336. for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
  337. {
  338. if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
  339. {
  340. pathRootFound = false;
  341. break;
  342. }
  343. }
  344. }
  345. }
  346. if (!pathRootFound)
  347. {
  348. return null;
  349. }
  350. var path = sbPathInfo.ToString();
  351. return path.Length > 1 ? path.TrimEnd('/') : "/";
  352. }
  353. private Dictionary<string, System.Net.Cookie> cookies;
  354. public IDictionary<string, System.Net.Cookie> Cookies
  355. {
  356. get
  357. {
  358. if (cookies == null)
  359. {
  360. cookies = new Dictionary<string, System.Net.Cookie>();
  361. foreach (var cookie in this.request.Cookies)
  362. {
  363. var httpCookie = cookie;
  364. cookies[httpCookie.Key] = new Cookie(httpCookie.Key, httpCookie.Value, "", "");
  365. }
  366. }
  367. return cookies;
  368. }
  369. }
  370. public string UserAgent => request.Headers[HeaderNames.UserAgent];
  371. public QueryParamCollection Headers => new QueryParamCollection(request.Headers);
  372. private QueryParamCollection queryString;
  373. public QueryParamCollection QueryString => queryString ?? (queryString = new QueryParamCollection(request.Query));
  374. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  375. private string httpMethod;
  376. public string HttpMethod =>
  377. httpMethod
  378. ?? (httpMethod = request.Method);
  379. public string Verb => HttpMethod;
  380. public string ContentType => request.ContentType;
  381. private Encoding contentEncoding;
  382. public Encoding ContentEncoding
  383. {
  384. get => contentEncoding ?? Encoding.GetEncoding(request.Headers[HeaderNames.ContentEncoding].ToString());
  385. set => contentEncoding = value;
  386. }
  387. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  388. public static Encoding GetEncoding(string contentTypeHeader)
  389. {
  390. var param = GetParameter(contentTypeHeader, "charset=");
  391. if (param == null)
  392. {
  393. return null;
  394. }
  395. try
  396. {
  397. return Encoding.GetEncoding(param);
  398. }
  399. catch (ArgumentException)
  400. {
  401. return null;
  402. }
  403. }
  404. public Stream InputStream => request.Body;
  405. public long ContentLength => request.ContentLength ?? 0;
  406. private IHttpFile[] httpFiles;
  407. public IHttpFile[] Files
  408. {
  409. get
  410. {
  411. if (httpFiles == null)
  412. {
  413. if (files == null)
  414. {
  415. return httpFiles = Array.Empty<IHttpFile>();
  416. }
  417. httpFiles = new IHttpFile[files.Count];
  418. var i = 0;
  419. foreach (var pair in files)
  420. {
  421. var reqFile = pair.Value;
  422. httpFiles[i] = new HttpFile
  423. {
  424. ContentType = reqFile.ContentType,
  425. ContentLength = reqFile.ContentLength,
  426. FileName = reqFile.FileName,
  427. InputStream = reqFile.InputStream,
  428. };
  429. i++;
  430. }
  431. }
  432. return httpFiles;
  433. }
  434. }
  435. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  436. {
  437. if (handlerPath != null)
  438. {
  439. var trimmed = pathInfo.TrimStart('/');
  440. if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  441. {
  442. return trimmed.Substring(handlerPath.Length);
  443. }
  444. }
  445. return pathInfo;
  446. }
  447. }
  448. }