WebSocketSharpRequest.cs 16 KB

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