WebSocketSharpRequest.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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()).ToString();
  54. }
  55. return remoteIp = NormalizeIp(request.HttpContext.Connection.RemoteIpAddress).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 IPAddress NormalizeIp(IPAddress ip)
  116. {
  117. if (ip.IsIPv4MappedToIPv6)
  118. {
  119. return ip.MapToIPv4();
  120. }
  121. return ip;
  122. }
  123. private IPAddress NormalizeIp(string sip)
  124. {
  125. return NormalizeIp(IPAddress.Parse(sip));
  126. }
  127. public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  128. private Dictionary<string, object> items;
  129. public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());
  130. private string responseContentType;
  131. public string ResponseContentType
  132. {
  133. get =>
  134. responseContentType
  135. ?? (responseContentType = GetResponseContentType(HttpRequest));
  136. set => this.responseContentType = value;
  137. }
  138. public const string FormUrlEncoded = "application/x-www-form-urlencoded";
  139. public const string MultiPartFormData = "multipart/form-data";
  140. public static string GetResponseContentType(HttpRequest httpReq)
  141. {
  142. var specifiedContentType = GetQueryStringContentType(httpReq);
  143. if (!string.IsNullOrEmpty(specifiedContentType))
  144. {
  145. return specifiedContentType;
  146. }
  147. const string serverDefaultContentType = "application/json";
  148. var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
  149. string defaultContentType = null;
  150. if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
  151. {
  152. defaultContentType = serverDefaultContentType;
  153. }
  154. var acceptsAnything = false;
  155. var hasDefaultContentType = defaultContentType != null;
  156. if (acceptContentTypes != null)
  157. {
  158. foreach (var acceptsType in acceptContentTypes)
  159. {
  160. // TODO: @bond move to Span when Span.Split lands
  161. // https://github.com/dotnet/corefx/issues/26528
  162. var contentType = acceptsType?.Split(';')[0].Trim();
  163. acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);
  164. if (acceptsAnything)
  165. {
  166. break;
  167. }
  168. }
  169. if (acceptsAnything)
  170. {
  171. if (hasDefaultContentType)
  172. {
  173. return defaultContentType;
  174. }
  175. else
  176. {
  177. return serverDefaultContentType;
  178. }
  179. }
  180. }
  181. if (acceptContentTypes == null && httpReq.ContentType == Soap11)
  182. {
  183. return Soap11;
  184. }
  185. // We could also send a '406 Not Acceptable', but this is allowed also
  186. return serverDefaultContentType;
  187. }
  188. public const string Soap11 = "text/xml; charset=utf-8";
  189. public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
  190. {
  191. if (contentTypes == null || request.ContentType == null)
  192. {
  193. return false;
  194. }
  195. foreach (var contentType in contentTypes)
  196. {
  197. if (IsContentType(request, contentType))
  198. {
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. public static bool IsContentType(HttpRequest request, string contentType)
  205. {
  206. return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
  207. }
  208. private static string GetQueryStringContentType(HttpRequest httpReq)
  209. {
  210. ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
  211. if (format == null)
  212. {
  213. const int formatMaxLength = 4;
  214. ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
  215. if (pi == null || pi.Length <= formatMaxLength)
  216. {
  217. return null;
  218. }
  219. if (pi[0] == '/')
  220. {
  221. pi = pi.Slice(1);
  222. }
  223. format = LeftPart(pi, '/');
  224. if (format.Length > formatMaxLength)
  225. {
  226. return null;
  227. }
  228. }
  229. format = LeftPart(format, '.');
  230. if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
  231. {
  232. return "application/json";
  233. }
  234. else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
  235. {
  236. return "application/xml";
  237. }
  238. return null;
  239. }
  240. public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
  241. {
  242. if (strVal == null)
  243. {
  244. return null;
  245. }
  246. var pos = strVal.IndexOf(needle);
  247. return pos == -1 ? strVal : strVal.Slice(0, pos);
  248. }
  249. public string PathInfo => this.request.Path.Value;
  250. public string UserAgent => request.Headers[HeaderNames.UserAgent];
  251. public IHeaderDictionary Headers => request.Headers;
  252. public IQueryCollection QueryString => request.Query;
  253. public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());
  254. private string httpMethod;
  255. public string HttpMethod =>
  256. httpMethod
  257. ?? (httpMethod = request.Method);
  258. public string Verb => HttpMethod;
  259. public string ContentType => request.ContentType;
  260. private Encoding ContentEncoding
  261. {
  262. get
  263. {
  264. // TODO is this necessary?
  265. if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
  266. {
  267. string postDataCharset = Headers["x-up-devcap-post-charset"];
  268. if (!string.IsNullOrEmpty(postDataCharset))
  269. {
  270. try
  271. {
  272. return Encoding.GetEncoding(postDataCharset);
  273. }
  274. catch (ArgumentException)
  275. {
  276. }
  277. }
  278. }
  279. return request.GetTypedHeaders().ContentType.Encoding ?? Encoding.UTF8;
  280. }
  281. }
  282. public Uri UrlReferrer => request.GetTypedHeaders().Referer;
  283. public static Encoding GetEncoding(string contentTypeHeader)
  284. {
  285. var param = GetParameter(contentTypeHeader.AsSpan(), "charset=");
  286. if (param == null)
  287. {
  288. return null;
  289. }
  290. try
  291. {
  292. return Encoding.GetEncoding(param);
  293. }
  294. catch (ArgumentException)
  295. {
  296. return null;
  297. }
  298. }
  299. public Stream InputStream => request.Body;
  300. public long ContentLength => request.ContentLength ?? 0;
  301. private IHttpFile[] httpFiles;
  302. public IHttpFile[] Files
  303. {
  304. get
  305. {
  306. if (httpFiles == null)
  307. {
  308. if (files == null)
  309. {
  310. return httpFiles = Array.Empty<IHttpFile>();
  311. }
  312. httpFiles = new IHttpFile[files.Count];
  313. var i = 0;
  314. foreach (var pair in files)
  315. {
  316. var reqFile = pair.Value;
  317. httpFiles[i] = new HttpFile
  318. {
  319. ContentType = reqFile.ContentType,
  320. ContentLength = reqFile.ContentLength,
  321. FileName = reqFile.FileName,
  322. InputStream = reqFile.InputStream,
  323. };
  324. i++;
  325. }
  326. }
  327. return httpFiles;
  328. }
  329. }
  330. }
  331. }