WebSocketSharpRequest.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Funq;
  6. using MediaBrowser.Model.Logging;
  7. using ServiceStack;
  8. using ServiceStack.Host;
  9. using ServiceStack.Web;
  10. using SocketHttpListener.Net;
  11. namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp
  12. {
  13. public partial class WebSocketSharpRequest : IHttpRequest
  14. {
  15. public Container Container { get; set; }
  16. private readonly HttpListenerRequest request;
  17. private readonly IHttpResponse response;
  18. public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, RequestAttributes requestAttributes, ILogger logger)
  19. {
  20. this.OperationName = operationName;
  21. this.RequestAttributes = requestAttributes;
  22. this.request = httpContext.Request;
  23. this.response = new WebSocketSharpResponse(logger, httpContext.Response, this);
  24. this.RequestPreferences = new RequestPreferences(this);
  25. }
  26. public HttpListenerRequest HttpRequest
  27. {
  28. get { return request; }
  29. }
  30. public object OriginalRequest
  31. {
  32. get { return request; }
  33. }
  34. public IResponse Response
  35. {
  36. get { return response; }
  37. }
  38. public IHttpResponse HttpResponse
  39. {
  40. get { return response; }
  41. }
  42. public RequestAttributes RequestAttributes { get; set; }
  43. public IRequestPreferences RequestPreferences { get; private set; }
  44. public T TryResolve<T>()
  45. {
  46. if (typeof(T) == typeof(IHttpRequest))
  47. throw new Exception("You don't need to use IHttpRequest.TryResolve<IHttpRequest> to resolve itself");
  48. if (typeof(T) == typeof(IHttpResponse))
  49. throw new Exception("Resolve IHttpResponse with 'Response' property instead of IHttpRequest.TryResolve<IHttpResponse>");
  50. return Container == null
  51. ? HostContext.TryResolve<T>()
  52. : Container.TryResolve<T>();
  53. }
  54. public string OperationName { get; set; }
  55. public object Dto { get; set; }
  56. public string GetRawBody()
  57. {
  58. if (bufferedStream != null)
  59. {
  60. return bufferedStream.ToArray().FromUtf8Bytes();
  61. }
  62. using (var reader = new StreamReader(InputStream))
  63. {
  64. return reader.ReadToEnd();
  65. }
  66. }
  67. public string RawUrl
  68. {
  69. get { return request.RawUrl; }
  70. }
  71. public string AbsoluteUri
  72. {
  73. get { return request.Url.AbsoluteUri.TrimEnd('/'); }
  74. }
  75. public string UserHostAddress
  76. {
  77. get { return request.UserHostAddress; }
  78. }
  79. public string XForwardedFor
  80. {
  81. get
  82. {
  83. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedFor]) ? null : request.Headers[HttpHeaders.XForwardedFor];
  84. }
  85. }
  86. public int? XForwardedPort
  87. {
  88. get
  89. {
  90. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedPort]) ? (int?)null : int.Parse(request.Headers[HttpHeaders.XForwardedPort]);
  91. }
  92. }
  93. public string XForwardedProtocol
  94. {
  95. get
  96. {
  97. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedProtocol]) ? null : request.Headers[HttpHeaders.XForwardedProtocol];
  98. }
  99. }
  100. public string XRealIp
  101. {
  102. get
  103. {
  104. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XRealIp]) ? null : request.Headers[HttpHeaders.XRealIp];
  105. }
  106. }
  107. private string remoteIp;
  108. public string RemoteIp
  109. {
  110. get
  111. {
  112. return remoteIp ??
  113. (remoteIp = (CheckBadChars(XForwardedFor)) ??
  114. (NormalizeIp(CheckBadChars(XRealIp)) ??
  115. (request.RemoteEndPoint != null ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
  116. }
  117. }
  118. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  119. //
  120. // CheckBadChars - throws on invalid chars to be not found in header name/value
  121. //
  122. internal static string CheckBadChars(string name)
  123. {
  124. if (name == null || name.Length == 0)
  125. {
  126. return name;
  127. }
  128. // VALUE check
  129. //Trim spaces from both ends
  130. name = name.Trim(HttpTrimCharacters);
  131. //First, check for correctly formed multi-line value
  132. //Second, check for absenece of CTL characters
  133. int crlf = 0;
  134. for (int i = 0; i < name.Length; ++i)
  135. {
  136. char c = (char)(0x000000ff & (uint)name[i]);
  137. switch (crlf)
  138. {
  139. case 0:
  140. if (c == '\r')
  141. {
  142. crlf = 1;
  143. }
  144. else if (c == '\n')
  145. {
  146. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  147. // Is there an exploit?
  148. crlf = 2;
  149. }
  150. else if (c == 127 || (c < ' ' && c != '\t'))
  151. {
  152. throw new ArgumentException("net_WebHeaderInvalidControlChars");
  153. }
  154. break;
  155. case 1:
  156. if (c == '\n')
  157. {
  158. crlf = 2;
  159. break;
  160. }
  161. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  162. case 2:
  163. if (c == ' ' || c == '\t')
  164. {
  165. crlf = 0;
  166. break;
  167. }
  168. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  169. }
  170. }
  171. if (crlf != 0)
  172. {
  173. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  174. }
  175. return name;
  176. }
  177. internal static bool ContainsNonAsciiChars(string token)
  178. {
  179. for (int i = 0; i < token.Length; ++i)
  180. {
  181. if ((token[i] < 0x20) || (token[i] > 0x7e))
  182. {
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. private string NormalizeIp(string ip)
  189. {
  190. if (!string.IsNullOrWhiteSpace(ip))
  191. {
  192. // Handle ipv4 mapped to ipv6
  193. const string srch = "::ffff:";
  194. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  195. if (index == 0)
  196. {
  197. ip = ip.Substring(srch.Length);
  198. }
  199. }
  200. return ip;
  201. }
  202. public bool IsSecureConnection
  203. {
  204. get { return request.IsSecureConnection || XForwardedProtocol == "https"; }
  205. }
  206. public string[] AcceptTypes
  207. {
  208. get { return request.AcceptTypes; }
  209. }
  210. private Dictionary<string, object> items;
  211. public Dictionary<string, object> Items
  212. {
  213. get { return items ?? (items = new Dictionary<string, object>()); }
  214. }
  215. private string responseContentType;
  216. public string ResponseContentType
  217. {
  218. get
  219. {
  220. return responseContentType
  221. ?? (responseContentType = this.GetResponseContentType());
  222. }
  223. set
  224. {
  225. this.responseContentType = value;
  226. HasExplicitResponseContentType = true;
  227. }
  228. }
  229. public bool HasExplicitResponseContentType { get; private set; }
  230. private string pathInfo;
  231. public string PathInfo
  232. {
  233. get
  234. {
  235. if (this.pathInfo == null)
  236. {
  237. var mode = HostContext.Config.HandlerFactoryPath;
  238. var pos = request.RawUrl.IndexOf("?");
  239. if (pos != -1)
  240. {
  241. var path = request.RawUrl.Substring(0, pos);
  242. this.pathInfo = HttpRequestExtensions.GetPathInfo(
  243. path,
  244. mode,
  245. mode ?? "");
  246. }
  247. else
  248. {
  249. this.pathInfo = request.RawUrl;
  250. }
  251. this.pathInfo = this.pathInfo.UrlDecode();
  252. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  253. }
  254. return this.pathInfo;
  255. }
  256. }
  257. private Dictionary<string, System.Net.Cookie> cookies;
  258. public IDictionary<string, System.Net.Cookie> Cookies
  259. {
  260. get
  261. {
  262. if (cookies == null)
  263. {
  264. cookies = new Dictionary<string, System.Net.Cookie>();
  265. for (var i = 0; i < this.request.Cookies.Count; i++)
  266. {
  267. var httpCookie = this.request.Cookies[i];
  268. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  269. }
  270. }
  271. return cookies;
  272. }
  273. }
  274. public string UserAgent
  275. {
  276. get { return request.UserAgent; }
  277. }
  278. private NameValueCollectionWrapper headers;
  279. public INameValueCollection Headers
  280. {
  281. get { return headers ?? (headers = new NameValueCollectionWrapper(request.Headers)); }
  282. }
  283. private NameValueCollectionWrapper queryString;
  284. public INameValueCollection QueryString
  285. {
  286. get { return queryString ?? (queryString = new NameValueCollectionWrapper(MyHttpUtility.ParseQueryString(request.Url.Query))); }
  287. }
  288. private NameValueCollectionWrapper formData;
  289. public INameValueCollection FormData
  290. {
  291. get { return formData ?? (formData = new NameValueCollectionWrapper(this.Form)); }
  292. }
  293. public bool IsLocal
  294. {
  295. get { return request.IsLocal; }
  296. }
  297. private string httpMethod;
  298. public string HttpMethod
  299. {
  300. get
  301. {
  302. return httpMethod
  303. ?? (httpMethod = Param(HttpHeaders.XHttpMethodOverride)
  304. ?? request.HttpMethod);
  305. }
  306. }
  307. public string Verb
  308. {
  309. get { return HttpMethod; }
  310. }
  311. public string Param(string name)
  312. {
  313. return Headers[name]
  314. ?? QueryString[name]
  315. ?? FormData[name];
  316. }
  317. public string ContentType
  318. {
  319. get { return request.ContentType; }
  320. }
  321. public Encoding contentEncoding;
  322. public Encoding ContentEncoding
  323. {
  324. get { return contentEncoding ?? request.ContentEncoding; }
  325. set { contentEncoding = value; }
  326. }
  327. public Uri UrlReferrer
  328. {
  329. get { return request.UrlReferrer; }
  330. }
  331. public static Encoding GetEncoding(string contentTypeHeader)
  332. {
  333. var param = GetParameter(contentTypeHeader, "charset=");
  334. if (param == null) return null;
  335. try
  336. {
  337. return Encoding.GetEncoding(param);
  338. }
  339. catch (ArgumentException)
  340. {
  341. return null;
  342. }
  343. }
  344. public bool UseBufferedStream
  345. {
  346. get { return bufferedStream != null; }
  347. set
  348. {
  349. bufferedStream = value
  350. ? bufferedStream ?? new MemoryStream(request.InputStream.ReadFully())
  351. : null;
  352. }
  353. }
  354. private MemoryStream bufferedStream;
  355. public Stream InputStream
  356. {
  357. get { return bufferedStream ?? request.InputStream; }
  358. }
  359. public long ContentLength
  360. {
  361. get { return request.ContentLength64; }
  362. }
  363. private IHttpFile[] httpFiles;
  364. public IHttpFile[] Files
  365. {
  366. get
  367. {
  368. if (httpFiles == null)
  369. {
  370. if (files == null)
  371. return httpFiles = new IHttpFile[0];
  372. httpFiles = new IHttpFile[files.Count];
  373. for (var i = 0; i < files.Count; i++)
  374. {
  375. var reqFile = files[i];
  376. httpFiles[i] = new HttpFile
  377. {
  378. ContentType = reqFile.ContentType,
  379. ContentLength = reqFile.ContentLength,
  380. FileName = reqFile.FileName,
  381. InputStream = reqFile.InputStream,
  382. };
  383. }
  384. }
  385. return httpFiles;
  386. }
  387. }
  388. static Stream GetSubStream(Stream stream)
  389. {
  390. if (stream is MemoryStream)
  391. {
  392. var other = (MemoryStream)stream;
  393. try
  394. {
  395. return new MemoryStream(other.GetBuffer(), 0, (int)other.Length, false, true);
  396. }
  397. catch (UnauthorizedAccessException)
  398. {
  399. return new MemoryStream(other.ToArray(), 0, (int)other.Length, false, true);
  400. }
  401. }
  402. return stream;
  403. }
  404. static void EndSubStream(Stream stream)
  405. {
  406. }
  407. public static string GetHandlerPathIfAny(string listenerUrl)
  408. {
  409. if (listenerUrl == null) return null;
  410. var pos = listenerUrl.IndexOf("://", StringComparison.InvariantCultureIgnoreCase);
  411. if (pos == -1) return null;
  412. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  413. var endPos = startHostUrl.IndexOf('/');
  414. if (endPos == -1) return null;
  415. var endHostUrl = startHostUrl.Substring(endPos + 1);
  416. return String.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  417. }
  418. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  419. {
  420. if (handlerPath != null && pathInfo.TrimStart('/').StartsWith(
  421. handlerPath, StringComparison.InvariantCultureIgnoreCase))
  422. {
  423. return pathInfo.TrimStart('/').Substring(handlerPath.Length);
  424. }
  425. return pathInfo;
  426. }
  427. }
  428. }