2
0

WebSocketSharpRequest.cs 18 KB

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