WebSocketSharpRequest.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.Text;
  6. using Emby.Server.Implementations.HttpServer.SocketSharp;
  7. using Funq;
  8. using MediaBrowser.Common.IO;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Services;
  12. using ServiceStack;
  13. using ServiceStack.Host;
  14. using ServiceStack.Web;
  15. using SocketHttpListener.Net;
  16. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  17. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  18. using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
  19. using IResponse = MediaBrowser.Model.Services.IResponse;
  20. namespace MediaBrowser.Server.Implementations.HttpServer.SocketSharp
  21. {
  22. public partial class WebSocketSharpRequest : IHttpRequest
  23. {
  24. public Container Container { get; set; }
  25. private readonly HttpListenerRequest request;
  26. private readonly IHttpResponse response;
  27. private readonly IMemoryStreamProvider _memoryStreamProvider;
  28. public WebSocketSharpRequest(HttpListenerContext httpContext, string operationName, RequestAttributes requestAttributes, ILogger logger, IMemoryStreamProvider memoryStreamProvider)
  29. {
  30. this.OperationName = operationName;
  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 T TryResolve<T>()
  52. {
  53. if (typeof(T) == typeof(IHttpRequest))
  54. throw new Exception("You don't need to use IHttpRequest.TryResolve<IHttpRequest> to resolve itself");
  55. if (typeof(T) == typeof(IHttpResponse))
  56. throw new Exception("Resolve IHttpResponse with 'Response' property instead of IHttpRequest.TryResolve<IHttpResponse>");
  57. return Container == null
  58. ? HostContext.TryResolve<T>()
  59. : Container.TryResolve<T>();
  60. }
  61. public string OperationName { get; set; }
  62. public object Dto { get; set; }
  63. public string GetRawBody()
  64. {
  65. if (bufferedStream != null)
  66. {
  67. return bufferedStream.ToArray().FromUtf8Bytes();
  68. }
  69. using (var reader = new StreamReader(InputStream))
  70. {
  71. return reader.ReadToEnd();
  72. }
  73. }
  74. public string RawUrl
  75. {
  76. get { return request.RawUrl; }
  77. }
  78. public string AbsoluteUri
  79. {
  80. get { return request.Url.AbsoluteUri.TrimEnd('/'); }
  81. }
  82. public string UserHostAddress
  83. {
  84. get { return request.UserHostAddress; }
  85. }
  86. public string XForwardedFor
  87. {
  88. get
  89. {
  90. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedFor]) ? null : request.Headers[HttpHeaders.XForwardedFor];
  91. }
  92. }
  93. public int? XForwardedPort
  94. {
  95. get
  96. {
  97. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedPort]) ? (int?)null : int.Parse(request.Headers[HttpHeaders.XForwardedPort]);
  98. }
  99. }
  100. public string XForwardedProtocol
  101. {
  102. get
  103. {
  104. return string.IsNullOrEmpty(request.Headers[HttpHeaders.XForwardedProtocol]) ? null : request.Headers[HttpHeaders.XForwardedProtocol];
  105. }
  106. }
  107. public string XRealIp
  108. {
  109. get
  110. {
  111. return String.IsNullOrEmpty(request.Headers[HttpHeaders.XRealIp]) ? null : request.Headers[HttpHeaders.XRealIp];
  112. }
  113. }
  114. private string remoteIp;
  115. public string RemoteIp
  116. {
  117. get
  118. {
  119. return remoteIp ??
  120. (remoteIp = (CheckBadChars(XForwardedFor)) ??
  121. (NormalizeIp(CheckBadChars(XRealIp)) ??
  122. (request.RemoteEndPoint != null ? NormalizeIp(request.RemoteEndPoint.Address.ToString()) : null)));
  123. }
  124. }
  125. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  126. //
  127. // CheckBadChars - throws on invalid chars to be not found in header name/value
  128. //
  129. internal static string CheckBadChars(string name)
  130. {
  131. if (name == null || name.Length == 0)
  132. {
  133. return name;
  134. }
  135. // VALUE check
  136. //Trim spaces from both ends
  137. name = name.Trim(HttpTrimCharacters);
  138. //First, check for correctly formed multi-line value
  139. //Second, check for absenece of CTL characters
  140. int crlf = 0;
  141. for (int i = 0; i < name.Length; ++i)
  142. {
  143. char c = (char)(0x000000ff & (uint)name[i]);
  144. switch (crlf)
  145. {
  146. case 0:
  147. if (c == '\r')
  148. {
  149. crlf = 1;
  150. }
  151. else if (c == '\n')
  152. {
  153. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  154. // Is there an exploit?
  155. crlf = 2;
  156. }
  157. else if (c == 127 || (c < ' ' && c != '\t'))
  158. {
  159. throw new ArgumentException("net_WebHeaderInvalidControlChars");
  160. }
  161. break;
  162. case 1:
  163. if (c == '\n')
  164. {
  165. crlf = 2;
  166. break;
  167. }
  168. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  169. case 2:
  170. if (c == ' ' || c == '\t')
  171. {
  172. crlf = 0;
  173. break;
  174. }
  175. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  176. }
  177. }
  178. if (crlf != 0)
  179. {
  180. throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
  181. }
  182. return name;
  183. }
  184. internal static bool ContainsNonAsciiChars(string token)
  185. {
  186. for (int i = 0; i < token.Length; ++i)
  187. {
  188. if ((token[i] < 0x20) || (token[i] > 0x7e))
  189. {
  190. return true;
  191. }
  192. }
  193. return false;
  194. }
  195. private string NormalizeIp(string ip)
  196. {
  197. if (!string.IsNullOrWhiteSpace(ip))
  198. {
  199. // Handle ipv4 mapped to ipv6
  200. const string srch = "::ffff:";
  201. var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  202. if (index == 0)
  203. {
  204. ip = ip.Substring(srch.Length);
  205. }
  206. }
  207. return ip;
  208. }
  209. public bool IsSecureConnection
  210. {
  211. get { return request.IsSecureConnection || XForwardedProtocol == "https"; }
  212. }
  213. public string[] AcceptTypes
  214. {
  215. get { return request.AcceptTypes; }
  216. }
  217. private Dictionary<string, object> items;
  218. public Dictionary<string, object> Items
  219. {
  220. get { return items ?? (items = new Dictionary<string, object>()); }
  221. }
  222. private string responseContentType;
  223. public string ResponseContentType
  224. {
  225. get
  226. {
  227. return responseContentType
  228. ?? (responseContentType = GetResponseContentType(this));
  229. }
  230. set
  231. {
  232. this.responseContentType = value;
  233. HasExplicitResponseContentType = true;
  234. }
  235. }
  236. private static string GetResponseContentType(IRequest httpReq)
  237. {
  238. var specifiedContentType = GetQueryStringContentType(httpReq);
  239. if (!string.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
  240. var acceptContentTypes = httpReq.AcceptTypes;
  241. var defaultContentType = httpReq.ContentType;
  242. if (httpReq.HasAnyOfContentTypes(MimeTypes.FormUrlEncoded, MimeTypes.MultiPartFormData))
  243. {
  244. defaultContentType = HostContext.Config.DefaultContentType;
  245. }
  246. var customContentTypes = HostContext.ContentTypes.ContentTypeFormats.Values;
  247. var preferredContentTypes = new string[] {};
  248. var acceptsAnything = false;
  249. var hasDefaultContentType = !string.IsNullOrEmpty(defaultContentType);
  250. if (acceptContentTypes != null)
  251. {
  252. var hasPreferredContentTypes = new bool[preferredContentTypes.Length];
  253. foreach (var acceptsType in acceptContentTypes)
  254. {
  255. var contentType = ContentFormat.GetRealContentType(acceptsType);
  256. acceptsAnything = acceptsAnything || contentType == "*/*";
  257. for (var i = 0; i < preferredContentTypes.Length; i++)
  258. {
  259. if (hasPreferredContentTypes[i]) continue;
  260. var preferredContentType = preferredContentTypes[i];
  261. hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
  262. //Prefer Request.ContentType if it is also a preferredContentType
  263. if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
  264. return preferredContentType;
  265. }
  266. }
  267. for (var i = 0; i < preferredContentTypes.Length; i++)
  268. {
  269. if (hasPreferredContentTypes[i]) return preferredContentTypes[i];
  270. }
  271. if (acceptsAnything)
  272. {
  273. if (hasDefaultContentType)
  274. return defaultContentType;
  275. if (HostContext.Config.DefaultContentType != null)
  276. return HostContext.Config.DefaultContentType;
  277. }
  278. foreach (var contentType in acceptContentTypes)
  279. {
  280. foreach (var customContentType in customContentTypes)
  281. {
  282. if (contentType.StartsWith(customContentType, StringComparison.OrdinalIgnoreCase))
  283. return customContentType;
  284. }
  285. }
  286. }
  287. if (httpReq.ContentType.MatchesContentType(MimeTypes.Soap12))
  288. {
  289. return MimeTypes.Soap12;
  290. }
  291. if (acceptContentTypes == null && httpReq.ContentType == MimeTypes.Soap11)
  292. {
  293. return MimeTypes.Soap11;
  294. }
  295. //We could also send a '406 Not Acceptable', but this is allowed also
  296. return HostContext.Config.DefaultContentType;
  297. }
  298. private static string GetQueryStringContentType(IRequest httpReq)
  299. {
  300. var callback = httpReq.QueryString[Keywords.Callback];
  301. if (!string.IsNullOrEmpty(callback)) return MimeTypes.Json;
  302. var format = httpReq.QueryString[Keywords.Format];
  303. if (format == null)
  304. {
  305. const int formatMaxLength = 4;
  306. var pi = httpReq.PathInfo;
  307. if (pi == null || pi.Length <= formatMaxLength) return null;
  308. if (pi[0] == '/') pi = pi.Substring(1);
  309. format = pi.LeftPart('/');
  310. if (format.Length > formatMaxLength) return null;
  311. }
  312. format = format.LeftPart('.').ToLower();
  313. if (format.Contains("json")) return MimeTypes.Json;
  314. if (format.Contains("xml")) return MimeTypes.Xml;
  315. if (format.Contains("jsv")) return MimeTypes.Jsv;
  316. string contentType;
  317. HostContext.ContentTypes.ContentTypeFormats.TryGetValue(format, out contentType);
  318. return contentType;
  319. }
  320. public bool HasExplicitResponseContentType { get; private set; }
  321. private string pathInfo;
  322. public string PathInfo
  323. {
  324. get
  325. {
  326. if (this.pathInfo == null)
  327. {
  328. var mode = HostContext.Config.HandlerFactoryPath;
  329. var pos = request.RawUrl.IndexOf("?");
  330. if (pos != -1)
  331. {
  332. var path = request.RawUrl.Substring(0, pos);
  333. this.pathInfo = GetPathInfo(
  334. path,
  335. mode,
  336. mode ?? "");
  337. }
  338. else
  339. {
  340. this.pathInfo = request.RawUrl;
  341. }
  342. this.pathInfo = this.pathInfo.UrlDecode();
  343. this.pathInfo = NormalizePathInfo(pathInfo, mode);
  344. }
  345. return this.pathInfo;
  346. }
  347. }
  348. private static string GetPathInfo(string fullPath, string mode, string appPath)
  349. {
  350. var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
  351. if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;
  352. //Wildcard mode relies on this to work out the handlerPath
  353. pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
  354. if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;
  355. return fullPath;
  356. }
  357. private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
  358. {
  359. if (mappedPathRoot == null) return null;
  360. var sbPathInfo = new StringBuilder();
  361. var fullPathParts = fullPath.Split('/');
  362. var mappedPathRootParts = mappedPathRoot.Split('/');
  363. var fullPathIndexOffset = mappedPathRootParts.Length - 1;
  364. var pathRootFound = false;
  365. for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
  366. {
  367. if (pathRootFound)
  368. {
  369. sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
  370. }
  371. else if (fullPathIndex - fullPathIndexOffset >= 0)
  372. {
  373. pathRootFound = true;
  374. for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
  375. {
  376. if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
  377. {
  378. pathRootFound = false;
  379. break;
  380. }
  381. }
  382. }
  383. }
  384. if (!pathRootFound) return null;
  385. var path = sbPathInfo.ToString();
  386. return path.Length > 1 ? path.TrimEnd('/') : "/";
  387. }
  388. private Dictionary<string, System.Net.Cookie> cookies;
  389. public IDictionary<string, System.Net.Cookie> Cookies
  390. {
  391. get
  392. {
  393. if (cookies == null)
  394. {
  395. cookies = new Dictionary<string, System.Net.Cookie>();
  396. for (var i = 0; i < this.request.Cookies.Count; i++)
  397. {
  398. var httpCookie = this.request.Cookies[i];
  399. cookies[httpCookie.Name] = new System.Net.Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain);
  400. }
  401. }
  402. return cookies;
  403. }
  404. }
  405. public string UserAgent
  406. {
  407. get { return request.UserAgent; }
  408. }
  409. private QueryParamCollection headers;
  410. public QueryParamCollection Headers
  411. {
  412. get { return headers ?? (headers = ToQueryParams(request.Headers)); }
  413. }
  414. private QueryParamCollection queryString;
  415. public QueryParamCollection QueryString
  416. {
  417. get { return queryString ?? (queryString = MyHttpUtility.ParseQueryString(request.Url.Query)); }
  418. }
  419. private QueryParamCollection formData;
  420. public QueryParamCollection FormData
  421. {
  422. get { return formData ?? (formData = this.Form); }
  423. }
  424. private QueryParamCollection ToQueryParams(NameValueCollection collection)
  425. {
  426. var result = new QueryParamCollection();
  427. foreach (var key in collection.AllKeys)
  428. {
  429. result[key] = collection[key];
  430. }
  431. return result;
  432. }
  433. public bool IsLocal
  434. {
  435. get { return request.IsLocal; }
  436. }
  437. private string httpMethod;
  438. public string HttpMethod
  439. {
  440. get
  441. {
  442. return httpMethod
  443. ?? (httpMethod = Param(HttpHeaders.XHttpMethodOverride)
  444. ?? request.HttpMethod);
  445. }
  446. }
  447. public string Verb
  448. {
  449. get { return HttpMethod; }
  450. }
  451. public string Param(string name)
  452. {
  453. return Headers[name]
  454. ?? QueryString[name]
  455. ?? FormData[name];
  456. }
  457. public string ContentType
  458. {
  459. get { return request.ContentType; }
  460. }
  461. public Encoding contentEncoding;
  462. public Encoding ContentEncoding
  463. {
  464. get { return contentEncoding ?? request.ContentEncoding; }
  465. set { contentEncoding = value; }
  466. }
  467. public Uri UrlReferrer
  468. {
  469. get { return request.UrlReferrer; }
  470. }
  471. public static Encoding GetEncoding(string contentTypeHeader)
  472. {
  473. var param = GetParameter(contentTypeHeader, "charset=");
  474. if (param == null) return null;
  475. try
  476. {
  477. return Encoding.GetEncoding(param);
  478. }
  479. catch (ArgumentException)
  480. {
  481. return null;
  482. }
  483. }
  484. public bool UseBufferedStream
  485. {
  486. get { return bufferedStream != null; }
  487. set
  488. {
  489. bufferedStream = value
  490. ? bufferedStream ?? _memoryStreamProvider.CreateNew(request.InputStream.ReadFully())
  491. : null;
  492. }
  493. }
  494. private MemoryStream bufferedStream;
  495. public Stream InputStream
  496. {
  497. get { return bufferedStream ?? request.InputStream; }
  498. }
  499. public long ContentLength
  500. {
  501. get { return request.ContentLength64; }
  502. }
  503. private IHttpFile[] httpFiles;
  504. public IHttpFile[] Files
  505. {
  506. get
  507. {
  508. if (httpFiles == null)
  509. {
  510. if (files == null)
  511. return httpFiles = new IHttpFile[0];
  512. httpFiles = new IHttpFile[files.Count];
  513. for (var i = 0; i < files.Count; i++)
  514. {
  515. var reqFile = files[i];
  516. httpFiles[i] = new HttpFile
  517. {
  518. ContentType = reqFile.ContentType,
  519. ContentLength = reqFile.ContentLength,
  520. FileName = reqFile.FileName,
  521. InputStream = reqFile.InputStream,
  522. };
  523. }
  524. }
  525. return httpFiles;
  526. }
  527. }
  528. static Stream GetSubStream(Stream stream, IMemoryStreamProvider streamProvider)
  529. {
  530. if (stream is MemoryStream)
  531. {
  532. var other = (MemoryStream)stream;
  533. try
  534. {
  535. return new MemoryStream(other.GetBuffer(), 0, (int)other.Length, false, true);
  536. }
  537. catch (UnauthorizedAccessException)
  538. {
  539. return new MemoryStream(other.ToArray(), 0, (int)other.Length, false, true);
  540. }
  541. }
  542. return stream;
  543. }
  544. public static string GetHandlerPathIfAny(string listenerUrl)
  545. {
  546. if (listenerUrl == null) return null;
  547. var pos = listenerUrl.IndexOf("://", StringComparison.InvariantCultureIgnoreCase);
  548. if (pos == -1) return null;
  549. var startHostUrl = listenerUrl.Substring(pos + "://".Length);
  550. var endPos = startHostUrl.IndexOf('/');
  551. if (endPos == -1) return null;
  552. var endHostUrl = startHostUrl.Substring(endPos + 1);
  553. return String.IsNullOrEmpty(endHostUrl) ? null : endHostUrl.TrimEnd('/');
  554. }
  555. public static string NormalizePathInfo(string pathInfo, string handlerPath)
  556. {
  557. if (handlerPath != null && pathInfo.TrimStart('/').StartsWith(
  558. handlerPath, StringComparison.InvariantCultureIgnoreCase))
  559. {
  560. return pathInfo.TrimStart('/').Substring(handlerPath.Length);
  561. }
  562. return pathInfo;
  563. }
  564. }
  565. }