WebSocketSharpRequest.cs 13 KB

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