WebSocketSharpRequest.cs 20 KB

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