WebSocketSharpRequest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using MediaBrowser.Model.Services;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.Http.Extensions;
  10. using Microsoft.Extensions.Logging;
  11. using Microsoft.Extensions.Primitives;
  12. using Microsoft.Net.Http.Headers;
  13. using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
  14. using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
  15. using IResponse = MediaBrowser.Model.Services.IResponse;
  16. namespace Emby.Server.Implementations.SocketSharp
  17. {
  18. public partial class WebSocketSharpRequest : IHttpRequest
  19. {
  20. private readonly HttpRequest request;
  21. public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
  22. {
  23. this.OperationName = operationName;
  24. this.request = httpContext;
  25. this.Response = new WebSocketSharpResponse(logger, response);
  26. }
  27. public HttpRequest HttpRequest => request;
  28. public IResponse Response { get; }
  29. public string OperationName { get; set; }
  30. public object Dto { get; set; }
  31. public string RawUrl => request.GetEncodedPathAndQuery();
  32. public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');
  33. public string XForwardedFor
  34. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();
  35. public int? XForwardedPort
  36. => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);
  37. public string XForwardedProtocol => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"].ToString();
  38. public string XRealIp => StringValues.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"].ToString();
  39. private string remoteIp;
  40. public string RemoteIp
  41. {
  42. get
  43. {
  44. if (remoteIp != null)
  45. {
  46. return remoteIp;
  47. }
  48. var temp = CheckBadChars(XForwardedFor.AsSpan());
  49. if (temp.Length != 0)
  50. {
  51. return remoteIp = temp.ToString();
  52. }
  53. temp = CheckBadChars(XRealIp.AsSpan());
  54. if (temp.Length != 0)
  55. {
  56. return remoteIp = NormalizeIp(temp).ToString();
  57. }
  58. return remoteIp = NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString().AsSpan()).ToString();
  59. }
  60. }
  61. private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
  62. // CheckBadChars - throws on invalid chars to be not found in header name/value
  63. internal static ReadOnlySpan<char> CheckBadChars(ReadOnlySpan<char> name)
  64. {
  65. if (name.Length == 0)
  66. {
  67. return name;
  68. }
  69. // VALUE check
  70. // Trim spaces from both ends
  71. name = name.Trim(HttpTrimCharacters);
  72. // First, check for correctly formed multi-line value
  73. // Second, check for absence of CTL characters
  74. int crlf = 0;
  75. for (int i = 0; i < name.Length; ++i)
  76. {
  77. char c = (char)(0x000000ff & (uint)name[i]);
  78. switch (crlf)
  79. {
  80. case 0:
  81. if (c == '\r')
  82. {
  83. crlf = 1;
  84. }
  85. else if (c == '\n')
  86. {
  87. // Technically this is bad HTTP. But it would be a breaking change to throw here.
  88. // Is there an exploit?
  89. crlf = 2;
  90. }
  91. else if (c == 127 || (c < ' ' && c != '\t'))
  92. {
  93. throw new ArgumentException("net_WebHeaderInvalidControlChars", nameof(name));
  94. }
  95. break;
  96. case 1:
  97. if (c == '\n')
  98. {
  99. crlf = 2;
  100. break;
  101. }
  102. throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
  103. case 2:
  104. if (c == ' ' || c == '\t')
  105. {
  106. crlf = 0;
  107. break;
  108. }
  109. throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
  110. }
  111. }
  112. if (crlf != 0)
  113. {
  114. throw new ArgumentException("net_WebHeaderInvalidCRLFChars", nameof(name));
  115. }
  116. return name;
  117. }
  118. private ReadOnlySpan<char> NormalizeIp(ReadOnlySpan<char> ip)
  119. {
  120. if (ip.Length != 0 && !ip.IsWhiteSpace())
  121. {
  122. // Handle ipv4 mapped to ipv6
  123. const string srch = "::ffff:";
  124. var index = ip.IndexOf(srch.AsSpan(), StringComparison.OrdinalIgnoreCase);
  125. if (index == 0)
  126. {
  127. ip = ip.Slice(srch.Length);
  128. }
  129. }
  130. return ip;
  131. }
  132. public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  133. private Dictionary<string, object> items;
  134. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  135. private string responseContentType;
  136. public string ResponseContentType
  137. {
  138. get =>
  139. responseContentType
  140. ?? (responseContentType = GetResponseContentType(HttpRequest));
  141. set => this.responseContentType = value;
  142. }
  143. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  144. public const string MultiPartFormData = "multipart/form-data";
  145. public static string GetResponseContentType(HttpRequest httpReq)
  146. {
  147. var specifiedContentType = GetQueryStringContentType(httpReq);
  148. if (!string.IsNullOrEmpty(specifiedContentType))
  149. {
  150. return specifiedContentType;
  151. }
  152. const string serverDefaultContentType = "application/json";
  153. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  154. string defaultContentType = null;
  155. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  156. {
  157. defaultContentType = serverDefaultContentType;
  158. }
  159. var acceptsAnything = false;
  160. var hasDefaultContentType = defaultContentType != null;
  161. if (acceptContentTypes != null)
  162. {
  163. foreach (var acceptsType in acceptContentTypes)
  164. {
  165. // TODO: @bond move to Span when Span.Split lands
  166. // https://github.com/dotnet/corefx/issues/26528
  167. var contentType = acceptsType?.Split(';')[0].Trim();
  168. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  169. if (acceptsAnything)
  170. {
  171. break;
  172. }
  173. }
  174. if (acceptsAnything)
  175. {
  176. if (hasDefaultContentType)
  177. {
  178. return defaultContentType;
  179. }
  180. else
  181. {
  182. return serverDefaultContentType;
  183. }
  184. }
  185. }
  186. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  187. {
  188. return Soap11;
  189. }
  190. // We could also send a '406 Not Acceptable', but this is allowed also
  191. return serverDefaultContentType;
  192. }
  193. public const string Soap11 = "text/xml; charset=utf-8";
  194. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  195. {
  196. if (contentTypes == null || request.ContentType == null)
  197. {
  198. return false;
  199. }
  200. foreach (var contentType in contentTypes)
  201. {
  202. if (IsContentType(request, contentType))
  203. {
  204. return true;
  205. }
  206. }
  207. return false;
  208. }
  209. public static bool IsContentType(HttpRequest request, string contentType)
  210. {
  211. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  212. }
  213. private static string GetQueryStringContentType(HttpRequest httpReq)
  214. {
  215. ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
  216. if (format == null)
  217. {
  218. const int formatMaxLength = 4;
  219. ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
  220. if (pi == null || pi.Length <= formatMaxLength)
  221. {
  222. return null;
  223. }
  224. if (pi[0] == '/')
  225. {
  226. pi = pi.Slice(1);
  227. }
  228. format = LeftPart(pi, '/');
  229. if (format.Length > formatMaxLength)
  230. {
  231. return null;
  232. }
  233. }
  234. format = LeftPart(format, '.');
  235. if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
  236. {
  237. return "application/json";
  238. }
  239. else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
  240. {
  241. return "application/xml";
  242. }
  243. return null;
  244. }
  245. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  246. {
  247. if (strVal == null)
  248. {
  249. return null;
  250. }
  251. var pos = strVal.IndexOf(needle);
  252. return pos == -1 ? strVal : strVal.Slice(0, pos);
  253. }
  254. public string PathInfo => this.request.Path.Value;
  255. public string UserAgent => request.Headers[HeaderNames.UserAgent];
  256. public IHeaderDictionary Headers => request.Headers;
  257. public IQueryCollection QueryString => request.Query;
  258. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  259. private string httpMethod;
  260. public string HttpMethod =>
  261. httpMethod
  262. ?? (httpMethod = request.Method);
  263. public string Verb => HttpMethod;
  264. public string ContentType => request.ContentType;
  265. private Encoding ContentEncoding
  266. {
  267. get
  268. {
  269. // TODO is this necessary?
  270. if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
  271. {
  272. string postDataCharset = Headers["x-up-devcap-post-charset"];
  273. if (!string.IsNullOrEmpty(postDataCharset))
  274. {
  275. try
  276. {
  277. return Encoding.GetEncoding(postDataCharset);
  278. }
  279. catch (ArgumentException)
  280. {
  281. }
  282. }
  283. }
  284. return request.GetTypedHeaders().ContentType.Encoding ?? Encoding.UTF8;
  285. }
  286. }
  287. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  288. public static Encoding GetEncoding(string contentTypeHeader)
  289. {
  290. var param = GetParameter(contentTypeHeader.AsSpan(), "charset=");
  291. if (param == null)
  292. {
  293. return null;
  294. }
  295. try
  296. {
  297. return Encoding.GetEncoding(param);
  298. }
  299. catch (ArgumentException)
  300. {
  301. return null;
  302. }
  303. }
  304. public Stream InputStream => request.Body;
  305. public long ContentLength => request.ContentLength ?? 0;
  306. private IHttpFile[] httpFiles;
  307. public IHttpFile[] Files
  308. {
  309. get
  310. {
  311. if (httpFiles == null)
  312. {
  313. if (files == null)
  314. {
  315. return httpFiles = Array.Empty<IHttpFile>();
  316. }
  317. httpFiles = new IHttpFile[files.Count];
  318. var i = 0;
  319. foreach (var pair in files)
  320. {
  321. var reqFile = pair.Value;
  322. httpFiles[i] = new HttpFile
  323. {
  324. ContentType = reqFile.ContentType,
  325. ContentLength = reqFile.ContentLength,
  326. FileName = reqFile.FileName,
  327. InputStream = reqFile.InputStream,
  328. };
  329. i++;
  330. }
  331. }
  332. return httpFiles;
  333. }
  334. }
  335. }
  336. }