2
0

WebSocketSharpRequest.cs 15 KB

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