WebSocketSharpRequest.cs 16 KB

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