WebSocketSharpRequest.cs 20 KB

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