WebSocketSharpRequest.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text;
  6. using Emby.Server.Implementations.HttpServer;
  7. using MediaBrowser.Model.Services;
  8. using Microsoft.Extensions.Logging;
  9. using SocketHttpListener.Net;
  10. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  11. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  12. using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
  13. using IResponse = MediaBrowser.Model.Services.IResponse;
  14. namespace Jellyfin.Server.SocketSharp
  15. {
  16. public partial class WebSocketSharpRequest : IHttpRequest
  17. {
  18. private readonly HttpListenerRequest request;
  19. private readonly IHttpResponse response;
  20. public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, ILogger logger)
  21. {
  22. this.OperationName = operationName;
  23. this.request = httpContext.Request;
  24. this.response = new WebSocketSharpResponse(logger, httpContext.Response, this);
  25. // HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
  26. }
  27. public HttpListenerRequest HttpRequest => request;
  28. public object OriginalRequest => request;
  29. public IResponse Response => response;
  30. public IHttpResponse HttpResponse => response;
  31. public string OperationName { get; set; }
  32. public object Dto { get; set; }
  33. public string RawUrl => request.RawUrl;
  34. public string AbsoluteUri => request.Url.AbsoluteUri.TrimEnd('/');
  35. public string UserHostAddress => request.UserHostAddress;
  36. public string XForwardedFor
  37. => string.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"];
  38. public int? XForwardedPort
  39. => string.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
  40. public string XForwardedProtocol => string.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"];
  41. public string XRealIp => string.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"];
  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);
  52. if (temp.Length != 0)
  53. {
  54. return remoteIp = temp.ToString();
  55. }
  56. temp = CheckBadChars(XRealIp);
  57. if (temp.Length != 0)
  58. {
  59. return remoteIp = NormalizeIp(temp).ToString();
  60. }
  61. return remoteIp = NormalizeIp(request.RemoteEndPoint?.Address.ToString()).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. internal static bool ContainsNonAsciiChars(string token)
  128. {
  129. for (int i = 0; i < token.Length; ++i)
  130. {
  131. if ((token[i] < 0x20) || (token[i] > 0x7e))
  132. {
  133. return true;
  134. }
  135. }
  136. return false;
  137. }
  138. private ReadOnlySpan<char> NormalizeIp(ReadOnlySpan<char> ip)
  139. {
  140. if (ip.Length != 0 && !ip.IsWhiteSpace())
  141. {
  142. // Handle ipv4 mapped to ipv6
  143. const string srch = "::ffff:";
  144. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  145. if (index == 0)
  146. {
  147. ip = ip.Slice(srch.Length);
  148. }
  149. }
  150. return ip;
  151. }
  152. public bool IsSecureConnection => request.IsSecureConnection || XForwardedProtocol == "https";
  153. public string[] AcceptTypes => request.AcceptTypes;
  154. private Dictionary<string, object> items;
  155. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  156. private string responseContentType;
  157. public string ResponseContentType
  158. {
  159. get =>
  160. responseContentType
  161. ?? (responseContentType = GetResponseContentType(this));
  162. set => this.responseContentType = value;
  163. }
  164. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  165. public const string MultiPartFormData = "multipart/form-data";
  166. public static string GetResponseContentType(IRequest httpReq)
  167. {
  168. var specifiedContentType = GetQueryStringContentType(httpReq);
  169. if (!string.IsNullOrEmpty(specifiedContentType))
  170. {
  171. return specifiedContentType;
  172. }
  173. const string serverDefaultContentType = "application/json";
  174. var acceptContentTypes = httpReq.AcceptTypes;
  175. string defaultContentType = null;
  176. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  177. {
  178. defaultContentType = serverDefaultContentType;
  179. }
  180. var acceptsAnything = false;
  181. var hasDefaultContentType = defaultContentType != null;
  182. if (acceptContentTypes != null)
  183. {
  184. foreach (var acceptsType in acceptContentTypes)
  185. {
  186. // TODO: @bond move to Span when Span.Split lands
  187. // https://github.com/dotnet/corefx/issues/26528
  188. var contentType = acceptsType?.Split(';')[0].Trim();
  189. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  190. if (acceptsAnything)
  191. {
  192. break;
  193. }
  194. }
  195. if (acceptsAnything)
  196. {
  197. if (hasDefaultContentType)
  198. {
  199. return defaultContentType;
  200. }
  201. else
  202. {
  203. return serverDefaultContentType;
  204. }
  205. }
  206. }
  207. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  208. {
  209. return Soap11;
  210. }
  211. // We could also send a '406 Not Acceptable', but this is allowed also
  212. return serverDefaultContentType;
  213. }
  214. public const string Soap11 = "text/xml; charset=utf-8";
  215. public static bool HasAnyOfContentTypes(IRequest request, params string[] contentTypes)
  216. {
  217. if (contentTypes == null || request.ContentType == null)
  218. {
  219. return false;
  220. }
  221. foreach (var contentType in contentTypes)
  222. {
  223. if (IsContentType(request, contentType))
  224. {
  225. return true;
  226. }
  227. }
  228. return false;
  229. }
  230. public static bool IsContentType(IRequest request, string contentType)
  231. {
  232. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  233. }
  234. private static string GetQueryStringContentType(IRequest httpReq)
  235. {
  236. ReadOnlySpan<char> format = httpReq.QueryString["format"];
  237. if (format == null)
  238. {
  239. const int formatMaxLength = 4;
  240. ReadOnlySpan<char> pi = httpReq.PathInfo;
  241. if (pi == null || pi.Length <= formatMaxLength)
  242. {
  243. return null;
  244. }
  245. if (pi[0] == '/')
  246. {
  247. pi = pi.Slice(1);
  248. }
  249. format = LeftPart(pi, '/');
  250. if (format.Length > formatMaxLength)
  251. {
  252. return null;
  253. }
  254. }
  255. format = LeftPart(format, '.');
  256. if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
  257. {
  258. return "application/json";
  259. }
  260. else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
  261. {
  262. return "application/xml";
  263. }
  264. return null;
  265. }
  266. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  267. {
  268. if (strVal == null)
  269. {
  270. return null;
  271. }
  272. var pos = strVal.IndexOf(needle);
  273. return pos == -1 ? strVal : strVal.Slice(0, pos);
  274. }
  275. public static string HandlerFactoryPath;
  276. private string pathInfo;
  277. public string PathInfo
  278. {
  279. get
  280. {
  281. if (this.pathInfo == null)
  282. {
  283. var mode = HandlerFactoryPath;
  284. var pos = request.RawUrl.IndexOf('?', StringComparison.Ordinal);
  285. if (pos != -1)
  286. {
  287. var path = request.RawUrl.Substring(0, pos);
  288. this.pathInfo = GetPathInfo(
  289. path,
  290. mode,
  291. mode ?? string.Empty);
  292. }
  293. else
  294. {
  295. this.pathInfo = request.RawUrl;
  296. }
  297. this.pathInfo = System.Net.WebUtility.UrlDecode(pathInfo);
  298. this.pathInfo = NormalizePathInfo(pathInfo, mode).ToString();
  299. }
  300. return this.pathInfo;
  301. }
  302. }
  303. private static string GetPathInfo(string fullPath, string mode, string appPath)
  304. {
  305. var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
  306. if (!string.IsNullOrEmpty(pathInfo))
  307. {
  308. return pathInfo;
  309. }
  310. // Wildcard mode relies on this to work out the handlerPath
  311. pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
  312. if (!string.IsNullOrEmpty(pathInfo))
  313. {
  314. return pathInfo;
  315. }
  316. return fullPath;
  317. }
  318. private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
  319. {
  320. if (mappedPathRoot == null)
  321. {
  322. return null;
  323. }
  324. var sbPathInfo = new StringBuilder();
  325. var fullPathParts = fullPath.Split('/');
  326. var mappedPathRootParts = mappedPathRoot.Split('/');
  327. var fullPathIndexOffset = mappedPathRootParts.Length - 1;
  328. var pathRootFound = false;
  329. for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
  330. {
  331. if (pathRootFound)
  332. {
  333. sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
  334. }
  335. else if (fullPathIndex - fullPathIndexOffset >= 0)
  336. {
  337. pathRootFound = true;
  338. for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
  339. {
  340. if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
  341. {
  342. pathRootFound = false;
  343. break;
  344. }
  345. }
  346. }
  347. }
  348. if (!pathRootFound)
  349. {
  350. return null;
  351. }
  352. var path = sbPathInfo.ToString();
  353. return path.Length > 1 ? path.TrimEnd('/') : "/";
  354. }
  355. private Dictionary<string, System.Net.Cookie> cookies;
  356. public IDictionary<string, System.Net.Cookie> Cookies
  357. {
  358. get
  359. {
  360. if (cookies == null)
  361. {
  362. cookies = new Dictionary<string, System.Net.Cookie>();
  363. foreach (var cookie in this.request.Cookies)
  364. {
  365. var httpCookie = (System.Net.Cookie)cookie;
  366. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  367. }
  368. }
  369. return cookies;
  370. }
  371. }
  372. public string UserAgent => request.UserAgent;
  373. public QueryParamCollection Headers => request.Headers;
  374. private QueryParamCollection queryString;
  375. public QueryParamCollection QueryString => queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query));
  376. public bool IsLocal => request.IsLocal;
  377. private string httpMethod;
  378. public string HttpMethod =>
  379. httpMethod
  380. ?? (httpMethod = request.HttpMethod);
  381. public string Verb => HttpMethod;
  382. public string ContentType => request.ContentType;
  383. private Encoding contentEncoding;
  384. public Encoding ContentEncoding
  385. {
  386. get => contentEncoding ?? request.ContentEncoding;
  387. set => contentEncoding = value;
  388. }
  389. public Uri UrlReferrer => request.UrlReferrer;
  390. public static Encoding GetEncoding(string contentTypeHeader)
  391. {
  392. var param = GetParameter(contentTypeHeader, "charset=");
  393. if (param == null)
  394. {
  395. return null;
  396. }
  397. try
  398. {
  399. return Encoding.GetEncoding(param);
  400. }
  401. catch (ArgumentException)
  402. {
  403. return null;
  404. }
  405. }
  406. public Stream InputStream => request.InputStream;
  407. public long ContentLength => request.ContentLength64;
  408. private IHttpFile[] httpFiles;
  409. public IHttpFile[] Files
  410. {
  411. get
  412. {
  413. if (httpFiles == null)
  414. {
  415. if (files == null)
  416. {
  417. return httpFiles = Array.Empty<IHttpFile>();
  418. }
  419. httpFiles = new IHttpFile[files.Count];
  420. var i = 0;
  421. foreach (var pair in files)
  422. {
  423. var reqFile = pair.Value;
  424. httpFiles[i] = new HttpFile
  425. {
  426. ContentType = reqFile.ContentType,
  427. ContentLength = reqFile.ContentLength,
  428. FileName = reqFile.FileName,
  429. InputStream = reqFile.InputStream,
  430. };
  431. i++;
  432. }
  433. }
  434. return httpFiles;
  435. }
  436. }
  437. public static ReadOnlySpan<char> NormalizePathInfo(string pathInfo, string handlerPath)
  438. {
  439. if (handlerPath != null)
  440. {
  441. var trimmed = pathInfo.AsSpan().TrimStart('/');
  442. if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  443. {
  444. return trimmed.Slice(handlerPath.Length).ToString();
  445. }
  446. }
  447. return pathInfo;
  448. }
  449. }
  450. }