WebSocketSharpRequest.cs 20 KB

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