WebSocketSharpRequest.cs 17 KB

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