WebSocketSharpRequest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Web;
  6. using Funq;
  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. public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, RequestAttributes requestAttributes, ILogger logger)
  20. {
  21. this.OperationName = operationName;
  22. this.RequestAttributes = requestAttributes;
  23. this.request = httpContext.Request;
  24. this.response = new WebSocketSharpResponse(logger, httpContext.Response);
  25. this.RequestPreferences = new RequestPreferences(this);
  26. }
  27. public HttpListenerRequest HttpRequest
  28. {
  29. get { return request; }
  30. }
  31. public object OriginalRequest
  32. {
  33. get { return request; }
  34. }
  35. public IResponse Response
  36. {
  37. get { return response; }
  38. }
  39. public IHttpResponse HttpResponse
  40. {
  41. get { return response; }
  42. }
  43. public RequestAttributes RequestAttributes { get; set; }
  44. public IRequestPreferences RequestPreferences { get; private set; }
  45. public T TryResolve<T>()
  46. {
  47. if (typeof(T) == typeof(IHttpRequest))
  48. throw new Exception("You don't need to use IHttpRequest.TryResolve<IHttpRequest> to resolve itself");
  49. if (typeof(T) == typeof(IHttpResponse))
  50. throw new Exception("Resolve IHttpResponse with 'Response' property instead of IHttpRequest.TryResolve<IHttpResponse>");
  51. return Container == null
  52. ? HostContext.TryResolve<T>()
  53. : Container.TryResolve<T>();
  54. }
  55. public string OperationName { get; set; }
  56. public object Dto { get; set; }
  57. public string GetRawBody()
  58. {
  59. if (bufferedStream != null)
  60. {
  61. return bufferedStream.ToArray().FromUtf8Bytes();
  62. }
  63. using (var reader = new StreamReader(InputStream))
  64. {
  65. return reader.ReadToEnd();
  66. }
  67. }
  68. public string RawUrl
  69. {
  70. get { return request.RawUrl; }
  71. }
  72. public string AbsoluteUri
  73. {
  74. get { return request.Url.AbsoluteUri.TrimEnd('/'); }
  75. }
  76. public string UserHostAddress
  77. {
  78. get { return request.UserHostAddress; }
  79. }
  80. public string XForwardedFor
  81. {
  82. get
  83. {
  84. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedFor]) ? null : request.Headers[HttpHeaders.XForwardedFor];
  85. }
  86. }
  87. public int? XForwardedPort
  88. {
  89. get
  90. {
  91. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedPort]) ? (int?)null : int.Parse(request.Headers[HttpHeaders.XForwardedPort]);
  92. }
  93. }
  94. public string XForwardedProtocol
  95. {
  96. get
  97. {
  98. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedProtocol]) ? null : request.Headers[HttpHeaders.XForwardedProtocol];
  99. }
  100. }
  101. public string XRealIp
  102. {
  103. get
  104. {
  105. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XRealIp]) ? null : request.Headers[HttpHeaders.XRealIp];
  106. }
  107. }
  108. private string remoteIp;
  109. public string RemoteIp
  110. {
  111. get
  112. {
  113. return remoteIp ??
  114. (remoteIp = XForwardedFor ??
  115. (NormalizeIp(XRealIp) ??
  116. ((request.RemoteEndPoint != null) ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
  117. }
  118. }
  119. private string NormalizeIp(string ip)
  120. {
  121. if (!string.IsNullOrWhiteSpace(ip))
  122. {
  123. // Handle ipv4 mapped to ipv6
  124. const string srch = "::ffff:";
  125. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  126. if (index == 0)
  127. {
  128. ip = ip.Substring(srch.Length);
  129. }
  130. }
  131. return ip;
  132. }
  133. public bool IsSecureConnection
  134. {
  135. get { return request.IsSecureConnection || XForwardedProtocol == "https"; }
  136. }
  137. public string[] AcceptTypes
  138. {
  139. get { return request.AcceptTypes; }
  140. }
  141. private Dictionary<string, object> items;
  142. public Dictionary<string, object> Items
  143. {
  144. get { return items ?? (items = new Dictionary<string, object>()); }
  145. }
  146. private string responseContentType;
  147. public string ResponseContentType
  148. {
  149. get
  150. {
  151. return responseContentType
  152. ?? (responseContentType = this.GetResponseContentType());
  153. }
  154. set
  155. {
  156. this.responseContentType = value;
  157. HasExplicitResponseContentType = true;
  158. }
  159. }
  160. public bool HasExplicitResponseContentType { get; private set; }
  161. private string pathInfo;
  162. public string PathInfo
  163. {
  164. get
  165. {
  166. if (this.pathInfo == null)
  167. {
  168. var mode = HostContext.Config.HandlerFactoryPath;
  169. var pos = request.RawUrl.IndexOf("?");
  170. if (pos != -1)
  171. {
  172. var path = request.RawUrl.Substring(0, pos);
  173. this.pathInfo = HttpRequestExtensions.GetPathInfo(
  174. path,
  175. mode,
  176. mode ?? "");
  177. }
  178. else
  179. {
  180. this.pathInfo = request.RawUrl;
  181. }
  182. this.pathInfo = this.pathInfo.UrlDecode();
  183. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  184. }
  185. return this.pathInfo;
  186. }
  187. }
  188. private Dictionary<string, System.Net.Cookie> cookies;
  189. public IDictionary<string, System.Net.Cookie> Cookies
  190. {
  191. get
  192. {
  193. if (cookies == null)
  194. {
  195. cookies = new Dictionary<string, System.Net.Cookie>();
  196. for (var i = 0; i < this.request.Cookies.Count; i++)
  197. {
  198. var httpCookie = this.request.Cookies[i];
  199. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  200. }
  201. }
  202. return cookies;
  203. }
  204. }
  205. public string UserAgent
  206. {
  207. get { return request.UserAgent; }
  208. }
  209. private NameValueCollectionWrapper headers;
  210. public INameValueCollection Headers
  211. {
  212. get { return headers ?? (headers = new NameValueCollectionWrapper(request.Headers)); }
  213. }
  214. private NameValueCollectionWrapper queryString;
  215. public INameValueCollection QueryString
  216. {
  217. get { return queryString ?? (queryString = new NameValueCollectionWrapper(MyHttpUtility.ParseQueryString(request.Url.Query))); }
  218. }
  219. private NameValueCollectionWrapper formData;
  220. public INameValueCollection FormData
  221. {
  222. get { return formData ?? (formData = new NameValueCollectionWrapper(this.Form)); }
  223. }
  224. public bool IsLocal
  225. {
  226. get { return request.IsLocal; }
  227. }
  228. private string httpMethod;
  229. public string HttpMethod
  230. {
  231. get
  232. {
  233. return httpMethod
  234. ?? (httpMethod = Param(HttpHeaders.XHttpMethodOverride)
  235. ?? request.HttpMethod);
  236. }
  237. }
  238. public string Verb
  239. {
  240. get { return HttpMethod; }
  241. }
  242. public string Param(string name)
  243. {
  244. return Headers[name]
  245. ?? QueryString[name]
  246. ?? FormData[name];
  247. }
  248. public string ContentType
  249. {
  250. get { return request.ContentType; }
  251. }
  252. public Encoding contentEncoding;
  253. public Encoding ContentEncoding
  254. {
  255. get { return contentEncoding ?? request.ContentEncoding; }
  256. set { contentEncoding = value; }
  257. }
  258. public Uri UrlReferrer
  259. {
  260. get { return request.UrlReferrer; }
  261. }
  262. public static Encoding GetEncoding(string contentTypeHeader)
  263. {
  264. var param = GetParameter(contentTypeHeader, "charset=");
  265. if (param == null) return null;
  266. try
  267. {
  268. return Encoding.GetEncoding(param);
  269. }
  270. catch (ArgumentException)
  271. {
  272. return null;
  273. }
  274. }
  275. public bool UseBufferedStream
  276. {
  277. get { return bufferedStream != null; }
  278. set
  279. {
  280. bufferedStream = value
  281. ? bufferedStream ?? new MemoryStream(request.InputStream.ReadFully())
  282. : null;
  283. }
  284. }
  285. private MemoryStream bufferedStream;
  286. public Stream InputStream
  287. {
  288. get { return bufferedStream ?? request.InputStream; }
  289. }
  290. public long ContentLength
  291. {
  292. get { return request.ContentLength64; }
  293. }
  294. private IHttpFile[] httpFiles;
  295. public IHttpFile[] Files
  296. {
  297. get
  298. {
  299. if (httpFiles == null)
  300. {
  301. if (files == null)
  302. return httpFiles = new IHttpFile[0];
  303. httpFiles = new IHttpFile[files.Count];
  304. for (var i = 0; i < files.Count; i++)
  305. {
  306. var reqFile = files[i];
  307. httpFiles[i] = new HttpFile
  308. {
  309. ContentType = reqFile.ContentType,
  310. ContentLength = reqFile.ContentLength,
  311. FileName = reqFile.FileName,
  312. InputStream = reqFile.InputStream,
  313. };
  314. }
  315. }
  316. return httpFiles;
  317. }
  318. }
  319. static Stream GetSubStream(Stream stream)
  320. {
  321. if (stream is MemoryStream)
  322. {
  323. var other = (MemoryStream)stream;
  324. try
  325. {
  326. return new MemoryStream(other.GetBuffer(), 0, (int)other.Length, false, true);
  327. }
  328. catch (UnauthorizedAccessException)
  329. {
  330. return new MemoryStream(other.ToArray(), 0, (int)other.Length, false, true);
  331. }
  332. }
  333. return stream;
  334. }
  335. static void EndSubStream(Stream stream)
  336. {
  337. }
  338. public static string GetHandlerPathIfAny(string listenerUrl)
  339. {
  340. if (listenerUrl == null) return null;
  341. var pos = listenerUrl.IndexOf("://", StringComparison.InvariantCultureIgnoreCase);
  342. if (pos == -1) return null;
  343. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  344. var endPos = startHostUrl.IndexOf('/');
  345. if (endPos == -1) return null;
  346. var endHostUrl = startHostUrl.Substring(endPos + 1);
  347. return String.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  348. }
  349. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  350. {
  351. if (handlerPath != null && pathInfo.TrimStart('/').StartsWith(
  352. handlerPath, StringComparison.InvariantCultureIgnoreCase))
  353. {
  354. return pathInfo.TrimStart('/').Substring(handlerPath.Length);
  355. }
  356. return pathInfo;
  357. }
  358. }
  359. }