WebSocketSharpRequest.cs 12 KB

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