WebSocketSharpRequest.cs 18 KB

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