WebSocketSharpRequest.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. private static string GetHandlerPathIfAny(string listenerUrl)
  28. {
  29. if (listenerUrl == null)
  30. {
  31. return null;
  32. }
  33. var pos = listenerUrl.IndexOf("://", StringComparison.OrdinalIgnoreCase);
  34. if (pos == -1)
  35. {
  36. return null;
  37. }
  38. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  39. var endPos = startHostUrl.IndexOf('/', StringComparison.Ordinal);
  40. if (endPos == -1)
  41. {
  42. return null;
  43. }
  44. var endHostUrl = startHostUrl.Substring(endPos + 1);
  45. return string.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  46. }
  47. public HttpListenerRequest HttpRequest => request;
  48. public object OriginalRequest => request;
  49. public IResponse Response => response;
  50. public IHttpResponse HttpResponse => response;
  51. public string OperationName { get; set; }
  52. public object Dto { get; set; }
  53. public string RawUrl => request.RawUrl;
  54. public string AbsoluteUri => request.Url.AbsoluteUri.TrimEnd('/');
  55. public string UserHostAddress => request.UserHostAddress;
  56. public string XForwardedFor
  57. => string.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"];
  58. public int? XForwardedPort
  59. => string.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
  60. public string XForwardedProtocol => string.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"];
  61. public string XRealIp => string.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"];
  62. private string remoteIp;
  63. public string RemoteIp =>
  64. remoteIp ??
  65. (remoteIp = CheckBadChars(XForwardedFor) ??
  66. NormalizeIp(CheckBadChars(XRealIp) ??
  67. (request.RemoteEndPoint != null ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
  68. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  69. // CheckBadChars - throws on invalid chars to be not found in header name/value
  70. internal static string CheckBadChars(string name)
  71. {
  72. if (name == null || name.Length == 0)
  73. {
  74. return name;
  75. }
  76. // VALUE check
  77. // Trim spaces from both ends
  78. name = name.Trim(HttpTrimCharacters);
  79. // First, check for correctly formed multi-line value
  80. // Second, check for absenece of CTL characters
  81. int crlf = 0;
  82. for (int i = 0; i < name.Length; ++i)
  83. {
  84. char c = (char)(0x000000ff & (uint)name[i]);
  85. switch (crlf)
  86. {
  87. case 0:
  88. {
  89. if (c == '\r')
  90. {
  91. crlf = 1;
  92. }
  93. else if (c == '\n')
  94. {
  95. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  96. // Is there an exploit?
  97. crlf = 2;
  98. }
  99. else if (c == 127 || (c < ' ' && c != '\t'))
  100. {
  101. throw new ArgumentException("net_WebHeaderInvalidControlChars");
  102. }
  103. break;
  104. }
  105. case 1:
  106. {
  107. if (c == '\n')
  108. {
  109. crlf = 2;
  110. break;
  111. }
  112. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  113. }
  114. case 2:
  115. {
  116. if (c == ' ' || c == '\t')
  117. {
  118. crlf = 0;
  119. break;
  120. }
  121. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  122. }
  123. }
  124. }
  125. if (crlf != 0)
  126. {
  127. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  128. }
  129. return name;
  130. }
  131. internal static bool ContainsNonAsciiChars(string token)
  132. {
  133. for (int i = 0; i < token.Length; ++i)
  134. {
  135. if ((token[i] < 0x20) || (token[i] > 0x7e))
  136. {
  137. return true;
  138. }
  139. }
  140. return false;
  141. }
  142. private string NormalizeIp(string ip)
  143. {
  144. if (!string.IsNullOrWhiteSpace(ip))
  145. {
  146. // Handle ipv4 mapped to ipv6
  147. const string srch = "::ffff:";
  148. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  149. if (index == 0)
  150. {
  151. ip = ip.Substring(srch.Length);
  152. }
  153. }
  154. return ip;
  155. }
  156. public bool IsSecureConnection => request.IsSecureConnection || XForwardedProtocol == "https";
  157. public string[] AcceptTypes => request.AcceptTypes;
  158. private Dictionary<string, object> items;
  159. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  160. private string responseContentType;
  161. public string ResponseContentType
  162. {
  163. get =>
  164. responseContentType
  165. ?? (responseContentType = GetResponseContentType(this));
  166. set => this.responseContentType = value;
  167. }
  168. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  169. public const string MultiPartFormData = "multipart/form-data";
  170. public static string GetResponseContentType(IRequest httpReq)
  171. {
  172. var specifiedContentType = GetQueryStringContentType(httpReq);
  173. if (!string.IsNullOrEmpty(specifiedContentType))
  174. {
  175. return specifiedContentType;
  176. }
  177. const string serverDefaultContentType = "application/json";
  178. var acceptContentTypes = httpReq.AcceptTypes;
  179. string defaultContentType = null;
  180. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  181. {
  182. defaultContentType = serverDefaultContentType;
  183. }
  184. var acceptsAnything = false;
  185. var hasDefaultContentType = defaultContentType != null;
  186. if (acceptContentTypes != null)
  187. {
  188. foreach (var acceptsType in acceptContentTypes)
  189. {
  190. var contentType = HttpResultFactory.GetRealContentType(acceptsType);
  191. acceptsAnything = acceptsAnything || contentType == "*/*";
  192. }
  193. if (acceptsAnything)
  194. {
  195. if (hasDefaultContentType)
  196. {
  197. return defaultContentType;
  198. }
  199. else if (serverDefaultContentType != null)
  200. {
  201. return serverDefaultContentType;
  202. }
  203. }
  204. }
  205. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  206. {
  207. return Soap11;
  208. }
  209. // We could also send a '406 Not Acceptable', but this is allowed also
  210. return serverDefaultContentType;
  211. }
  212. public const string Soap11 = "text/xml; charset=utf-8";
  213. public static bool HasAnyOfContentTypes(IRequest request, params string[] contentTypes)
  214. {
  215. if (contentTypes == null || request.ContentType == null)
  216. {
  217. return false;
  218. }
  219. foreach (var contentType in contentTypes)
  220. {
  221. if (IsContentType(request, contentType))
  222. {
  223. return true;
  224. }
  225. }
  226. return false;
  227. }
  228. public static bool IsContentType(IRequest request, string contentType)
  229. {
  230. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  231. }
  232. private static string GetQueryStringContentType(IRequest httpReq)
  233. {
  234. var format = httpReq.QueryString["format"];
  235. if (format == null)
  236. {
  237. const int formatMaxLength = 4;
  238. var pi = httpReq.PathInfo;
  239. if (pi == null || pi.Length <= formatMaxLength)
  240. {
  241. return null;
  242. }
  243. if (pi[0] == '/')
  244. {
  245. pi = pi.Substring(1);
  246. }
  247. format = LeftPart(pi, '/');
  248. if (format.Length > formatMaxLength)
  249. {
  250. return null;
  251. }
  252. }
  253. format = LeftPart(format, '.');
  254. if (format.Contains("json", StringComparison.OrdinalIgnoreCase))
  255. {
  256. return "application/json";
  257. }
  258. else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
  259. {
  260. return "application/xml";
  261. }
  262. return null;
  263. }
  264. public static string LeftPart(string strVal, char needle)
  265. {
  266. if (strVal == null)
  267. {
  268. return null;
  269. }
  270. var pos = strVal.IndexOf(needle, StringComparison.Ordinal);
  271. return pos == -1 ? strVal : strVal.Substring(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.RawUrl.IndexOf("?", StringComparison.Ordinal);
  283. if (pos != -1)
  284. {
  285. var path = request.RawUrl.Substring(0, pos);
  286. this.pathInfo = GetPathInfo(
  287. path,
  288. mode,
  289. mode ?? string.Empty);
  290. }
  291. else
  292. {
  293. this.pathInfo = request.RawUrl;
  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 = (System.Net.Cookie)cookie;
  364. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  365. }
  366. }
  367. return cookies;
  368. }
  369. }
  370. public string UserAgent => request.UserAgent;
  371. public QueryParamCollection Headers => request.Headers;
  372. private QueryParamCollection queryString;
  373. public QueryParamCollection QueryString => queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query));
  374. public bool IsLocal => request.IsLocal;
  375. private string httpMethod;
  376. public string HttpMethod =>
  377. httpMethod
  378. ?? (httpMethod = request.HttpMethod);
  379. public string Verb => HttpMethod;
  380. public string ContentType => request.ContentType;
  381. private Encoding contentEncoding;
  382. public Encoding ContentEncoding
  383. {
  384. get => contentEncoding ?? request.ContentEncoding;
  385. set => contentEncoding = value;
  386. }
  387. public Uri UrlReferrer => request.UrlReferrer;
  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.InputStream;
  405. public long ContentLength => request.ContentLength64;
  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. var trimmed = pathInfo.TrimStart('/');
  438. if (handlerPath != null && trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  439. {
  440. return trimmed.Substring(handlerPath.Length);
  441. }
  442. return pathInfo;
  443. }
  444. }
  445. }