WebSocketSharpRequest.cs 12 KB

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