WebSocketSharpRequest.cs 20 KB

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