WebSocketSharpRequest.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. (XRealIp ??
  116. ((request.RemoteEndPoint != null) ? request.RemoteEndPoint.Address.ToString() : null)));
  117. }
  118. }
  119. public bool IsSecureConnection
  120. {
  121. get { return request.IsSecureConnection || XForwardedProtocol == "https"; }
  122. }
  123. public string[] AcceptTypes
  124. {
  125. get { return request.AcceptTypes; }
  126. }
  127. private Dictionary<string, object> items;
  128. public Dictionary<string, object> Items
  129. {
  130. get { return items ?? (items = new Dictionary<string, object>()); }
  131. }
  132. private string responseContentType;
  133. public string ResponseContentType
  134. {
  135. get
  136. {
  137. return responseContentType
  138. ?? (responseContentType = this.GetResponseContentType());
  139. }
  140. set
  141. {
  142. this.responseContentType = value;
  143. HasExplicitResponseContentType = true;
  144. }
  145. }
  146. public bool HasExplicitResponseContentType { get; private set; }
  147. private string pathInfo;
  148. public string PathInfo
  149. {
  150. get
  151. {
  152. if (this.pathInfo == null)
  153. {
  154. var mode = HostContext.Config.HandlerFactoryPath;
  155. var pos = request.RawUrl.IndexOf("?");
  156. if (pos != -1)
  157. {
  158. var path = request.RawUrl.Substring(0, pos);
  159. this.pathInfo = HttpRequestExtensions.GetPathInfo(
  160. path,
  161. mode,
  162. mode ?? "");
  163. }
  164. else
  165. {
  166. this.pathInfo = request.RawUrl;
  167. }
  168. this.pathInfo = this.pathInfo.UrlDecode();
  169. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  170. }
  171. return this.pathInfo;
  172. }
  173. }
  174. private Dictionary<string, System.Net.Cookie> cookies;
  175. public IDictionary<string, System.Net.Cookie> Cookies
  176. {
  177. get
  178. {
  179. if (cookies == null)
  180. {
  181. cookies = new Dictionary<string, System.Net.Cookie>();
  182. for (var i = 0; i < this.request.Cookies.Count; i++)
  183. {
  184. var httpCookie = this.request.Cookies[i];
  185. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  186. }
  187. }
  188. return cookies;
  189. }
  190. }
  191. public string UserAgent
  192. {
  193. get { return request.UserAgent; }
  194. }
  195. private NameValueCollectionWrapper headers;
  196. public INameValueCollection Headers
  197. {
  198. get { return headers ?? (headers = new NameValueCollectionWrapper(request.Headers)); }
  199. }
  200. private NameValueCollectionWrapper queryString;
  201. public INameValueCollection QueryString
  202. {
  203. get { return queryString ?? (queryString = new NameValueCollectionWrapper(MyHttpUtility.ParseQueryString(request.Url.Query))); }
  204. }
  205. private NameValueCollectionWrapper formData;
  206. public INameValueCollection FormData
  207. {
  208. get { return formData ?? (formData = new NameValueCollectionWrapper(this.Form)); }
  209. }
  210. public bool IsLocal
  211. {
  212. get { return request.IsLocal; }
  213. }
  214. private string httpMethod;
  215. public string HttpMethod
  216. {
  217. get
  218. {
  219. return httpMethod
  220. ?? (httpMethod = Param(HttpHeaders.XHttpMethodOverride)
  221. ?? request.HttpMethod);
  222. }
  223. }
  224. public string Verb
  225. {
  226. get { return HttpMethod; }
  227. }
  228. public string Param(string name)
  229. {
  230. return Headers[name]
  231. ?? QueryString[name]
  232. ?? FormData[name];
  233. }
  234. public string ContentType
  235. {
  236. get { return request.ContentType; }
  237. }
  238. public Encoding contentEncoding;
  239. public Encoding ContentEncoding
  240. {
  241. get { return contentEncoding ?? request.ContentEncoding; }
  242. set { contentEncoding = value; }
  243. }
  244. public Uri UrlReferrer
  245. {
  246. get { return request.UrlReferrer; }
  247. }
  248. public static Encoding GetEncoding(string contentTypeHeader)
  249. {
  250. var param = GetParameter(contentTypeHeader, "charset=");
  251. if (param == null) return null;
  252. try
  253. {
  254. return Encoding.GetEncoding(param);
  255. }
  256. catch (ArgumentException)
  257. {
  258. return null;
  259. }
  260. }
  261. public bool UseBufferedStream
  262. {
  263. get { return bufferedStream != null; }
  264. set
  265. {
  266. bufferedStream = value
  267. ? bufferedStream ?? new MemoryStream(request.InputStream.ReadFully())
  268. : null;
  269. }
  270. }
  271. private MemoryStream bufferedStream;
  272. public Stream InputStream
  273. {
  274. get { return bufferedStream ?? request.InputStream; }
  275. }
  276. public long ContentLength
  277. {
  278. get { return request.ContentLength64; }
  279. }
  280. private IHttpFile[] httpFiles;
  281. public IHttpFile[] Files
  282. {
  283. get
  284. {
  285. if (httpFiles == null)
  286. {
  287. if (files == null)
  288. return httpFiles = new IHttpFile[0];
  289. httpFiles = new IHttpFile[files.Count];
  290. for (var i = 0; i < files.Count; i++)
  291. {
  292. var reqFile = files[i];
  293. httpFiles[i] = new HttpFile
  294. {
  295. ContentType = reqFile.ContentType,
  296. ContentLength = reqFile.ContentLength,
  297. FileName = reqFile.FileName,
  298. InputStream = reqFile.InputStream,
  299. };
  300. }
  301. }
  302. return httpFiles;
  303. }
  304. }
  305. static Stream GetSubStream(Stream stream)
  306. {
  307. if (stream is MemoryStream)
  308. {
  309. var other = (MemoryStream)stream;
  310. try
  311. {
  312. return new MemoryStream(other.GetBuffer(), 0, (int)other.Length, false, true);
  313. }
  314. catch (UnauthorizedAccessException)
  315. {
  316. return new MemoryStream(other.ToArray(), 0, (int)other.Length, false, true);
  317. }
  318. }
  319. return stream;
  320. }
  321. static void EndSubStream(Stream stream)
  322. {
  323. }
  324. public static string GetHandlerPathIfAny(string listenerUrl)
  325. {
  326. if (listenerUrl == null) return null;
  327. var pos = listenerUrl.IndexOf("://", StringComparison.InvariantCultureIgnoreCase);
  328. if (pos == -1) return null;
  329. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  330. var endPos = startHostUrl.IndexOf('/');
  331. if (endPos == -1) return null;
  332. var endHostUrl = startHostUrl.Substring(endPos + 1);
  333. return String.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  334. }
  335. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  336. {
  337. if (handlerPath != null && pathInfo.TrimStart('/').StartsWith(
  338. handlerPath, StringComparison.InvariantCultureIgnoreCase))
  339. {
  340. return pathInfo.TrimStart('/').Substring(handlerPath.Length);
  341. }
  342. return pathInfo;
  343. }
  344. }
  345. }