WebSocketSharpRequest.cs 17 KB

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