WebSocketSharpRequest.cs 20 KB

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