WebSocketSharpRequest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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.Server.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. // CheckBadChars - throws on invalid chars to be not found in header name/value
  67. internal static string CheckBadChars(string name)
  68. {
  69. if (name == null || name.Length == 0)
  70. {
  71. return name;
  72. }
  73. // VALUE check
  74. // Trim spaces from both ends
  75. name = name.Trim(HttpTrimCharacters);
  76. // First, check for correctly formed multi-line value
  77. // Second, check for absenece of CTL characters
  78. int crlf = 0;
  79. for (int i = 0; i < name.Length; ++i)
  80. {
  81. char c = (char)(0x000000ff & (uint)name[i]);
  82. switch (crlf)
  83. {
  84. case 0:
  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");
  98. }
  99. break;
  100. case 1:
  101. if (c == '\n')
  102. {
  103. crlf = 2;
  104. break;
  105. }
  106. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  107. case 2:
  108. if (c == ' ' || c == '\t')
  109. {
  110. crlf = 0;
  111. break;
  112. }
  113. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  114. }
  115. }
  116. if (crlf != 0)
  117. {
  118. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  119. }
  120. return name;
  121. }
  122. internal static bool ContainsNonAsciiChars(string token)
  123. {
  124. for (int i = 0; i < token.Length; ++i)
  125. {
  126. if ((token[i] < 0x20) || (token[i] > 0x7e))
  127. {
  128. return true;
  129. }
  130. }
  131. return false;
  132. }
  133. private string NormalizeIp(string ip)
  134. {
  135. if (!string.IsNullOrWhiteSpace(ip))
  136. {
  137. // Handle ipv4 mapped to ipv6
  138. const string srch = "::ffff:";
  139. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  140. if (index == 0)
  141. {
  142. ip = ip.Substring(srch.Length);
  143. }
  144. }
  145. return ip;
  146. }
  147. public bool IsSecureConnection => request.IsSecureConnection || XForwardedProtocol == "https";
  148. public string[] AcceptTypes => request.AcceptTypes;
  149. private Dictionary<string, object> items;
  150. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  151. private string responseContentType;
  152. public string ResponseContentType
  153. {
  154. get =>
  155. responseContentType
  156. ?? (responseContentType = GetResponseContentType(this));
  157. set => this.responseContentType = value;
  158. }
  159. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  160. public const string MultiPartFormData = "multipart/form-data";
  161. public static string GetResponseContentType(IRequest httpReq)
  162. {
  163. var specifiedContentType = GetQueryStringContentType(httpReq);
  164. if (!string.IsNullOrEmpty(specifiedContentType))
  165. {
  166. return specifiedContentType;
  167. }
  168. const string serverDefaultContentType = "application/json";
  169. var acceptContentTypes = httpReq.AcceptTypes;
  170. string defaultContentType = null;
  171. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  172. {
  173. defaultContentType = serverDefaultContentType;
  174. }
  175. var acceptsAnything = false;
  176. var hasDefaultContentType = defaultContentType != null;
  177. if (acceptContentTypes != null)
  178. {
  179. foreach (var acceptsType in acceptContentTypes)
  180. {
  181. var contentType = HttpResultFactory.GetRealContentType(acceptsType);
  182. acceptsAnything = acceptsAnything || contentType == "*/*";
  183. }
  184. if (acceptsAnything)
  185. {
  186. if (hasDefaultContentType)
  187. {
  188. return defaultContentType;
  189. }
  190. else if (serverDefaultContentType != null)
  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(IRequest 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(IRequest request, string contentType)
  220. {
  221. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  222. }
  223. private static string GetQueryStringContentType(IRequest httpReq)
  224. {
  225. var format = httpReq.QueryString["format"];
  226. if (format == null)
  227. {
  228. const int formatMaxLength = 4;
  229. var pi = httpReq.PathInfo;
  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.Contains("json", StringComparison.OrdinalIgnoreCase))
  246. {
  247. return "application/json";
  248. }
  249. else if (format.Contains("xml", StringComparison.OrdinalIgnoreCase))
  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, StringComparison.Ordinal);
  262. return pos == -1 ? strVal : strVal.Substring(0, pos);
  263. }
  264. public static string HandlerFactoryPath;
  265. private string pathInfo;
  266. public string PathInfo
  267. {
  268. get
  269. {
  270. if (this.pathInfo == null)
  271. {
  272. var mode = HandlerFactoryPath;
  273. var pos = request.RawUrl.IndexOf("?", StringComparison.Ordinal);
  274. if (pos != -1)
  275. {
  276. var path = request.RawUrl.Substring(0, pos);
  277. this.pathInfo = GetPathInfo(
  278. path,
  279. mode,
  280. mode ?? string.Empty);
  281. }
  282. else
  283. {
  284. this.pathInfo = request.RawUrl;
  285. }
  286. this.pathInfo = System.Net.WebUtility.UrlDecode(pathInfo);
  287. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  288. }
  289. return this.pathInfo;
  290. }
  291. }
  292. private static string GetPathInfo(string fullPath, string mode, string appPath)
  293. {
  294. var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
  295. if (!string.IsNullOrEmpty(pathInfo))
  296. {
  297. return pathInfo;
  298. }
  299. // Wildcard mode relies on this to work out the handlerPath
  300. pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
  301. if (!string.IsNullOrEmpty(pathInfo))
  302. {
  303. return pathInfo;
  304. }
  305. return fullPath;
  306. }
  307. private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
  308. {
  309. if (mappedPathRoot == null)
  310. {
  311. return null;
  312. }
  313. var sbPathInfo = new StringBuilder();
  314. var fullPathParts = fullPath.Split('/');
  315. var mappedPathRootParts = mappedPathRoot.Split('/');
  316. var fullPathIndexOffset = mappedPathRootParts.Length - 1;
  317. var pathRootFound = false;
  318. for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
  319. {
  320. if (pathRootFound)
  321. {
  322. sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
  323. }
  324. else if (fullPathIndex - fullPathIndexOffset >= 0)
  325. {
  326. pathRootFound = true;
  327. for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
  328. {
  329. if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
  330. {
  331. pathRootFound = false;
  332. break;
  333. }
  334. }
  335. }
  336. }
  337. if (!pathRootFound)
  338. {
  339. return null;
  340. }
  341. var path = sbPathInfo.ToString();
  342. return path.Length > 1 ? path.TrimEnd('/') : "/";
  343. }
  344. private Dictionary<string, System.Net.Cookie> cookies;
  345. public IDictionary<string, System.Net.Cookie> Cookies
  346. {
  347. get
  348. {
  349. if (cookies == null)
  350. {
  351. cookies = new Dictionary<string, System.Net.Cookie>();
  352. foreach (var cookie in this.request.Cookies)
  353. {
  354. var httpCookie = (System.Net.Cookie)cookie;
  355. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  356. }
  357. }
  358. return cookies;
  359. }
  360. }
  361. public string UserAgent => request.UserAgent;
  362. public QueryParamCollection Headers => request.Headers;
  363. private QueryParamCollection queryString;
  364. public QueryParamCollection QueryString => queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query));
  365. public bool IsLocal => request.IsLocal;
  366. private string httpMethod;
  367. public string HttpMethod =>
  368. httpMethod
  369. ?? (httpMethod = request.HttpMethod);
  370. public string Verb => HttpMethod;
  371. public string ContentType => request.ContentType;
  372. public Encoding contentEncoding;
  373. public Encoding ContentEncoding
  374. {
  375. get => contentEncoding ?? request.ContentEncoding;
  376. set => contentEncoding = value;
  377. }
  378. public Uri UrlReferrer => request.UrlReferrer;
  379. public static Encoding GetEncoding(string contentTypeHeader)
  380. {
  381. var param = GetParameter(contentTypeHeader, "charset=");
  382. if (param == null)
  383. {
  384. return null;
  385. }
  386. try
  387. {
  388. return Encoding.GetEncoding(param);
  389. }
  390. catch (ArgumentException)
  391. {
  392. return null;
  393. }
  394. }
  395. public Stream InputStream => request.InputStream;
  396. public long ContentLength => request.ContentLength64;
  397. private IHttpFile[] httpFiles;
  398. public IHttpFile[] Files
  399. {
  400. get
  401. {
  402. if (httpFiles == null)
  403. {
  404. if (files == null)
  405. {
  406. return httpFiles = Array.Empty<IHttpFile>();
  407. }
  408. httpFiles = new IHttpFile[files.Count];
  409. var i = 0;
  410. foreach (var pair in files)
  411. {
  412. var reqFile = pair.Value;
  413. httpFiles[i] = new HttpFile
  414. {
  415. ContentType = reqFile.ContentType,
  416. ContentLength = reqFile.ContentLength,
  417. FileName = reqFile.FileName,
  418. InputStream = reqFile.InputStream,
  419. };
  420. i++;
  421. }
  422. }
  423. return httpFiles;
  424. }
  425. }
  426. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  427. {
  428. var trimmed = pathInfo.TrimStart('/');
  429. if (handlerPath != null && trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
  430. {
  431. return trimmed.Substring(handlerPath.Length);
  432. }
  433. return pathInfo;
  434. }
  435. }
  436. }