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